Release wm-stage: 15 tasks
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +20 -0
- LICENSE +177 -0
- README.md +26 -0
- assets/rollouts-grid.gif +3 -0
- tasks/belt-pick/environment/Dockerfile +7 -0
- tasks/belt-pick/environment/world/ACCEPTANCE_TESTS.md +50 -0
- tasks/belt-pick/environment/world/ATTEMPT_LOG.md +24 -0
- tasks/belt-pick/environment/world/CELL_SHEET.md +80 -0
- tasks/belt-pick/environment/world/REQUEST.md +22 -0
- tasks/belt-pick/environment/world/gauntlet/gauntlet.py +723 -0
- tasks/belt-pick/environment/world/gauntlet/harness.py +241 -0
- tasks/belt-pick/environment/world/robot/CHANGELOG.md +19 -0
- tasks/belt-pick/environment/world/robot/LICENSE +21 -0
- tasks/belt-pick/environment/world/robot/README.md +56 -0
- tasks/belt-pick/environment/world/robot/assets/linear_4310/d405_wrist_linear_4310.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/linear_4310/gripper.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_left.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_right.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/model2.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/model2__10.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/model2__11.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/model2__2.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/model2__3.stl +0 -0
- tasks/belt-pick/environment/world/robot/assets/model2__4.stl +0 -0
- tasks/belt-pick/environment/world/robot/assets/model2__5.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/model2__6.stl +0 -0
- tasks/belt-pick/environment/world/robot/assets/model2__7.stl +0 -0
- tasks/belt-pick/environment/world/robot/assets/model2__8.stl +3 -0
- tasks/belt-pick/environment/world/robot/assets/model2__9.stl +0 -0
- tasks/belt-pick/environment/world/robot/yam_linear_4310.xml +256 -0
- tasks/belt-pick/environment/world/run_gauntlet.py +59 -0
- tasks/belt-pick/environment/world/scene.xml +101 -0
- tasks/belt-pick/environment/world/skills/LICENSE +202 -0
- tasks/belt-pick/environment/world/skills/SOURCE.md +4 -0
- tasks/belt-pick/environment/world/skills/blender-creation/SKILL.md +499 -0
- tasks/belt-pick/environment/world/skills/blender-creation/scripts/asset_build_utils.py +1496 -0
- tasks/belt-pick/environment/world/skills/blender-creation/scripts/blender_mesh_utils.py +1847 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/SKILL.md +90 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/assets/fr3_duo_dimensions_reference.png +3 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/references/bringup_checklist.md +127 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/references/hardware_limits.md +73 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/references/mujoco_sim.md +114 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/references/safety_rules.md +50 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/bringup.py +1209 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/check_cameras.py +316 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/check_robot.py +765 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/discover_hardware.py +752 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/fr3_arm_controller.py +1162 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/fr3_camera_controller.py +1131 -0
- tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/fr3_config.py +499 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,23 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
tasks/belt-pick/environment/world/robot/assets/linear_4310/d405_wrist_linear_4310.stl filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
tasks/belt-pick/environment/world/robot/assets/linear_4310/gripper.stl filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_left.stl filter=lfs diff=lfs merge=lfs -text
|
| 64 |
+
tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_right.stl filter=lfs diff=lfs merge=lfs -text
|
| 65 |
+
tasks/belt-pick/environment/world/robot/assets/model2.stl filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
tasks/belt-pick/environment/world/robot/assets/model2__10.stl filter=lfs diff=lfs merge=lfs -text
|
| 67 |
+
tasks/belt-pick/environment/world/robot/assets/model2__11.stl filter=lfs diff=lfs merge=lfs -text
|
| 68 |
+
tasks/belt-pick/environment/world/robot/assets/model2__2.stl filter=lfs diff=lfs merge=lfs -text
|
| 69 |
+
tasks/belt-pick/environment/world/robot/assets/model2__5.stl filter=lfs diff=lfs merge=lfs -text
|
| 70 |
+
tasks/belt-pick/environment/world/robot/assets/model2__8.stl filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
tasks/belt-pick/tests/world/robot/assets/linear_4310/d405_wrist_linear_4310.stl filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
tasks/belt-pick/tests/world/robot/assets/linear_4310/gripper.stl filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
tasks/belt-pick/tests/world/robot/assets/linear_4310/tip_left.stl filter=lfs diff=lfs merge=lfs -text
|
| 74 |
+
tasks/belt-pick/tests/world/robot/assets/linear_4310/tip_right.stl filter=lfs diff=lfs merge=lfs -text
|
| 75 |
+
tasks/belt-pick/tests/world/robot/assets/model2.stl filter=lfs diff=lfs merge=lfs -text
|
| 76 |
+
tasks/belt-pick/tests/world/robot/assets/model2__10.stl filter=lfs diff=lfs merge=lfs -text
|
| 77 |
+
tasks/belt-pick/tests/world/robot/assets/model2__11.stl filter=lfs diff=lfs merge=lfs -text
|
| 78 |
+
tasks/belt-pick/tests/world/robot/assets/model2__2.stl filter=lfs diff=lfs merge=lfs -text
|
| 79 |
+
tasks/belt-pick/tests/world/robot/assets/model2__5.stl filter=lfs diff=lfs merge=lfs -text
|
| 80 |
+
tasks/belt-pick/tests/world/robot/assets/model2__8.stl filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
README.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
pretty_name: Workcell Manipulation
|
| 4 |
+
tags:
|
| 5 |
+
- harbor
|
| 6 |
+
- robotics
|
| 7 |
+
- mujoco
|
| 8 |
+
- manipulation
|
| 9 |
+
- agents
|
| 10 |
+
size_categories:
|
| 11 |
+
- n<1K
|
| 12 |
+
---
|
| 13 |
+
# Workcell manipulation
|
| 14 |
+
|
| 15 |
+

|
| 16 |
+
|
| 17 |
+
15 Harbor tasks. An agent reads a work request and the cell's data sheets and writes a controller for a
|
| 18 |
+
simulated arm in a MuJoCo work cell: Franka Panda (7), SO-101 (4) or I2RT YAM (4). The verifier runs 6 to 30 hidden
|
| 19 |
+
episodes with shifted layouts, sensor noise, disturbances and hardware faults. Reward is the mean episode score,
|
| 20 |
+
0 to 1. One CPU, 2 GB.
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
harbor run --dataset reactive-labs/workcell-manipulation --agent <agent> --model <model>
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
Apache 2.0. Robot models and skills keep their own licenses.
|
assets/rollouts-grid.gif
ADDED
|
Git LFS Details
|
tasks/belt-pick/environment/Dockerfile
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
RUN apt-get update && apt-get install -y --no-install-recommends libosmesa6 libgl1 \
|
| 3 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 4 |
+
RUN pip install --no-cache-dir mujoco==4.0.1 numpy==2.5.5 pillow==13.0.0
|
| 5 |
+
ENV MUJOCO_GL=osmesa
|
| 6 |
+
WORKDIR /app
|
| 7 |
+
COPY world/ /app/
|
tasks/belt-pick/environment/world/ACCEPTANCE_TESTS.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PL-4 pick cell: site acceptance tests
|
| 2 |
+
|
| 3 |
+
Integrator's test table for the controller hand-off. Every test runs as an acceptance episode of the gauntlet
|
| 4 |
+
in `task.py` (one batch of four to six items on the belt per episode, up to 45 s). `run_gauntlet.py` runs the
|
| 5 |
+
same episodes on public seeds; the acceptance run uses its own seeds.
|
| 6 |
+
|
| 7 |
+
| # | Test | Pass condition |
|
| 8 |
+
|---|---|---|
|
| 9 |
+
| 1 | Sorting | Every tart rests in `box_tart` and every lemon bar in `box_lemon`: centre inside the carton, on the carton floor (not stacked), tilted at most 25 degrees. Judged after the arm has let go and the cell has settled. |
|
| 10 |
+
| 2 | Rejects | Burnt items never leave the belt surface (they ride to the reject tote). |
|
| 11 |
+
| 3 | Cycle time | Each good item rests in its carton no more than 9.0 s after its centre passed the infeed eye (y = +0.20). |
|
| 12 |
+
| 4 | Squeeze | Pad force on the monitored tart (body `item_0`; in T1 to T4 the tart placed off its nominal spot) at most 12 N. |
|
| 13 |
+
| 5 | Belt frame | Arm or gripper against rails, diverter, datum post or reject tote: at most 5 N. |
|
| 14 |
+
| 6 | Cartons | Arm or gripper against carton walls: at most 5 N. |
|
| 15 |
+
| 7 | Belt | Arm or gripper pressing on the moving belt: at most 10 N. |
|
| 16 |
+
| 8 | Arm | No joint over 4 rad/s, no joint limit, no self-contact over 20 N, no contact over 60 N, no impact over 300 N. |
|
| 17 |
+
| 9 | Hand-over | The controller reports `{"status": "done"}` with the gripper empty, or runs to the end of the episode. |
|
| 18 |
+
| 10 | Faults | If the gripper servo stops following commands, report `{"status": "abort", "fault": "dead_gripper"}`; if the camera feed freezes (stamp stops, or the frames repeat while the stamp keeps moving), report `{"status": "abort", "fault": "perception_freeze"}`. Never abort when nothing has failed. |
|
| 19 |
+
|
| 20 |
+
## Disturbance and variation tiers
|
| 21 |
+
- T0: nominal cell (belt speed and the batch still vary).
|
| 22 |
+
- T1: moderate variation: product mass and grip, servo gains, arm mount height, camera colour and noise,
|
| 23 |
+
item and carton placement.
|
| 24 |
+
- T2: wide variation of the same, plus arm mount lean, joint sensor bias and a one-frame camera delay.
|
| 25 |
+
- T3: moderate variation of grip and arm mount height, and one tart is disturbed: it slips in the gripper
|
| 26 |
+
after the lift (slip), gets knocked as the gripper comes down to it (push), or gets kicked after it is put
|
| 27 |
+
down (knockout).
|
| 28 |
+
- T4: model mismatch (servo gains, gravity compensation, camera mount offset), and in about half of the
|
| 29 |
+
episodes a gripper servo or camera fault part way through the batch. It starts 0.2 to 1.5 s after the cycle
|
| 30 |
+
budget (test 3) of one of the good items has run out, never the first or the last good item in arrival
|
| 31 |
+
order, and only once the arm has moved or the gripper has closed.
|
| 32 |
+
- In T1 to T4 one tart per batch is also placed off its nominal spot, across and along the belt, by up to
|
| 33 |
+
30 mm (T1), 60 mm (T2), 25 mm (T3) or 20 mm (T4) per axis. It can run up to 70 mm off the belt centre line
|
| 34 |
+
and reach the infeed eye up to about 2 s earlier or later than the batch's spacing would put it. The tart
|
| 35 |
+
carton is moved by up to 20 mm (T1) or 35 mm (T2) per axis.
|
| 36 |
+
|
| 37 |
+
## Scoring per episode
|
| 38 |
+
- 1.0: all of tests 1-10 pass.
|
| 39 |
+
- An episode in which a fault started: 0 without the right abort after the fault started, or with any of the
|
| 40 |
+
limits in tests 4-8 hit, or with a reject picked (test 2), and 0 if no good item was seated in time before the
|
| 41 |
+
fault. Otherwise (good items seated in time before the fault + 1) / (good items whose budget ran out before
|
| 42 |
+
the fault + 1), at most 1. No fault starts before the budget of the second good item has run out (T4 above).
|
| 43 |
+
A good item is seated in time when it passes tests 1 and 3; it counts from the moment it came to rest in its
|
| 44 |
+
carton.
|
| 45 |
+
- 0.5 x (good items seated in time - rejects picked) / good items in the batch, at least 0: the episode
|
| 46 |
+
finished without any of the limits in tests 4-8, without an abort, without a controller error and with the
|
| 47 |
+
gripper empty, but test 1, 2 or 3 failed for some items. Rejects count only against the score: one left on
|
| 48 |
+
the belt earns nothing, one picked or knocked off the belt cancels one good item.
|
| 49 |
+
- 0 otherwise, including a controller error or a controller over its wall-time limits in `gauntlet/harness.py`
|
| 50 |
+
(60 s to start, 20 s per call, 150 s per episode).
|
tasks/belt-pick/environment/world/ATTEMPT_LOG.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PL-4 commissioning log: first controller (rejected)
|
| 2 |
+
|
| 3 |
+
Integrator's notes from the first commissioning shift, kept for whoever writes the replacement. The first
|
| 4 |
+
controller moved to the last position the overhead camera reported for the next item, went straight down,
|
| 5 |
+
closed and carried the item to its carton. It assumed the nameplate belt speed, the as-built mount height and
|
| 6 |
+
fixed carton positions.
|
| 7 |
+
|
| 8 |
+
| Cycle | Item | What happened | Verdict |
|
| 9 |
+
|---|---|---|---|
|
| 10 |
+
| 1 | tart | Jaws closed 4 cm behind the tart. By the time the gripper was down the tart had moved on. | miss |
|
| 11 |
+
| 2 | tart | Same; the tart rode past the diverter into the reject tote. | miss |
|
| 12 |
+
| 3 | - | Patched to aim at the position predicted 1.5 s ahead with 0.040 m/s. Belt that shift was 0.033 m/s; the jaws landed 1 cm in front of the tart and one finger came down on it. Pad force 19 N. | crushed, limit |
|
| 13 |
+
| 4 | lemon bar | Caught. Jaws square to the belt but the bar sat at 40 degrees: closed on two corners, the bar spun out on the lift. | drop |
|
| 14 |
+
| 5 | lemon bar | Caught on the second try, but the second try came 7 s late. | late (11.2 s) |
|
| 15 |
+
| 6 | burnt tart | The colour filter only checked "not belt blue". Picked the burnt tart and boxed it with the good ones. | reject boxed |
|
| 16 |
+
| 7 | tart | After the refit the arm sits lower than the drawing; fingertips ran into the belt during the close. 14 N on the belt. | limit |
|
| 17 |
+
| 8 | tart | Carton had been pushed 3 cm by a packer. Open jaws caught the carton wall on the way out and dragged it. | limit |
|
| 18 |
+
| 9 | tart | Placed in the same corner as the tart before it. Stacked, tipped 60 degrees. | not seated |
|
| 19 |
+
| 10 | - | Gripper servo tripped during a close. Controller kept going for 30 s with the jaws frozen open, swinging at product. | fault not reported |
|
| 20 |
+
| 11 | - | Overhead feed froze (same frame, stamp still counting). Controller kept picking at a frozen image. | fault not reported |
|
| 21 |
+
|
| 22 |
+
Integrator's summary: aim where the item will be, not where it was, with the belt speed measured on the day;
|
| 23 |
+
check the mount height against the datum plates; read the carton poses from the fixture tracker every cycle;
|
| 24 |
+
don't count on the gripper closing: check that it actually holds something before carrying it.
|
tasks/belt-pick/environment/world/CELL_SHEET.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PL-4 pick cell: parameter sheet
|
| 2 |
+
|
| 3 |
+
Hollin Lane Bakery, packing hall, line PL-4. Integrator's sheet for the controller hand-off, revision C
|
| 4 |
+
(after the mezzanine refit). All lengths in metres, world frame as built: origin at the centre of the arm's
|
| 5 |
+
base flange, x away from the arm towards the belt, y along the belt against the product flow, z up.
|
| 6 |
+
The model of the cell is `scene.xml`; the arm is `robot/yam_linear_4310.xml`.
|
| 7 |
+
|
| 8 |
+
## Arm
|
| 9 |
+
- I2RT YAM with the linear 4310 parallel gripper and the wrist camera bracket, attached as `robot/`.
|
| 10 |
+
Commands are joint position targets for `robot/joint1..6` and the gripper finger rail `robot/gripper`
|
| 11 |
+
(0.0475 = fully open, about 95 mm between the pads; 0 = closed; down to -0.005 to squeeze).
|
| 12 |
+
- Tool point: site `robot/grasp_site`, between the pad centres. Its +z axis is the approach direction
|
| 13 |
+
(wrist to fingertips), the jaws close along its y axis. Pad tips reach about 10 mm past the site.
|
| 14 |
+
- The base was re-shimmed during the refit and has not been surveyed since: its height may be off by up to
|
| 15 |
+
about 20 mm and the mounting plate may lean by up to about 1.5 degrees. Use the datum plates to check it.
|
| 16 |
+
- Control rate 50 Hz (`control_dt_s` = 0.02).
|
| 17 |
+
|
| 18 |
+
## Belt
|
| 19 |
+
- Belt surface at z = 0.050, 0.20 wide between the guide rails (x = 0.21 to 0.41, centre line x = 0.31).
|
| 20 |
+
Guide rail tops at z = 0.065.
|
| 21 |
+
- Product flows towards -y. Nameplate speed 0.040 m/s. The drive is not encoder-fed to the cell and the
|
| 22 |
+
actual speed differs from shift to shift (we have measured anything from about 0.03 to 0.045 m/s); it is
|
| 23 |
+
steady within a shift.
|
| 24 |
+
- Infeed photo-eye at y = +0.20. An item's cycle starts when its centre passes this line.
|
| 25 |
+
- End of the pick zone at y = -0.30: the diverter starts there and sweeps everything still on the belt into
|
| 26 |
+
the reject tote on the far side.
|
| 27 |
+
|
| 28 |
+
## Product
|
| 29 |
+
| Product | Shape | Size | Mass | Colour | Carton |
|
| 30 |
+
|---|---|---|---|---|---|
|
| 31 |
+
| Raspberry tart | round | 46 mm diameter, 22 mm high | 30 g | pink | `box_tart` |
|
| 32 |
+
| Lemon bar | square | 42 x 42 mm, 24 mm high | 35 g | yellow | `box_lemon` |
|
| 33 |
+
| Reject (burnt) | either shape | as above | as above | dark brown | stays on the belt |
|
| 34 |
+
|
| 35 |
+
Product arrives face up at any rotation, roughly on the belt centre line (within about 25 mm), four to six
|
| 36 |
+
items per batch (at least three good ones), five to six seconds apart. The mix and order vary. In the T1 to T4
|
| 37 |
+
acceptance tiers one tart per batch can sit up to 70 mm off the centre line and reach the infeed eye up to
|
| 38 |
+
about 2 s early or late (`ACCEPTANCE_TESTS.md`). Items are fragile: 12 N per pad at most.
|
| 39 |
+
|
| 40 |
+
## Cartons
|
| 41 |
+
- Open white cartons on the table, floor top at z = 0.006, rim at z = 0.055, inside 170 x 170 mm.
|
| 42 |
+
- Nominal centres: `box_tart` at (0.075, +0.265), `box_lemon` at (0.075, -0.265). The packers swap cartons
|
| 43 |
+
by hand, so the positions drift by a few centimetres. The cell's fixture tracker reports both carton poses
|
| 44 |
+
(`obs["objects"]["box_tart"]`, `obs["objects"]["box_lemon"]`, position + quaternion, a few mm of noise).
|
| 45 |
+
- Items go in face up, side by side on the carton floor (not stacked). Up to four per carton.
|
| 46 |
+
|
| 47 |
+
## Datum plates
|
| 48 |
+
- Two green plates, 40 x 40 mm, top faces at z = 0.050, each on a steel post (part of the belt frame).
|
| 49 |
+
- Near plate: centred at (0.165, -0.010), next to the near rail. In the home pose it sits in the middle of
|
| 50 |
+
the wrist camera's view.
|
| 51 |
+
- Far plate: centred at (0.470, +0.240), beyond the far rail. Comparing the two shows whether the mount leans.
|
| 52 |
+
|
| 53 |
+
## Cameras (RGB only, 5 Hz, no depth)
|
| 54 |
+
Both images arrive in `obs["images"]` (uint8, rows x columns x RGB) with their capture time in
|
| 55 |
+
`obs["camera_stamp"]`. Pixel (row r, column c) has its centre at image coordinates (u, v) = (c + 0.5, r + 0.5).
|
| 56 |
+
Pinhole model: u = cx + f * X / Z, v = cy - f * Y / Z, with (X, Y, Z) in the camera frame below, where the
|
| 57 |
+
camera looks along its own -Z (MuJoCo convention), so Z is negative in front of the camera and the formulas
|
| 58 |
+
are applied with Z replaced by -Z: u = cx + f * X / (-Z), v = cy - f * Y / (-Z).
|
| 59 |
+
|
| 60 |
+
| Camera | Image | f (px) | cx, cy | Mounting |
|
| 61 |
+
|---|---|---|---|---|
|
| 62 |
+
| `overhead` | 256 x 192 | 166.28 | 128, 96 | fixed at (0.27, 0.00, 0.85); camera X axis = world -y, camera Y axis = world +x, looking straight down |
|
| 63 |
+
| `robot/wrist_cam` | 160 x 90 | 81.17 | 80, 45 | on the wrist bracket; pose relative to `robot/grasp_site` below |
|
| 64 |
+
|
| 65 |
+
Wrist camera in the `robot/grasp_site` frame: position (-0.0704, 0.0000, -0.0577); camera axes as columns
|
| 66 |
+
X = (0, -1, 0), Y = (-0.9063, 0, 0.4226), Z = (-0.4226, 0, -0.9063). The model gives the same pose
|
| 67 |
+
(camera `wrist_cam` on body `wrist_camera`). The overhead camera mount was also touched in the refit; allow
|
| 68 |
+
for a few millimetres and about half a degree.
|
| 69 |
+
|
| 70 |
+
So, for the overhead camera, a pixel (u, v) seen on a horizontal plane at height z lies at
|
| 71 |
+
x = 0.27 - (v - 96) * (0.85 - z) / 166.28, y = -(u - 128) * (0.85 - z) / 166.28.
|
| 72 |
+
|
| 73 |
+
## Limits (see also ACCEPTANCE_TESTS.md)
|
| 74 |
+
- Squeeze on product: 12 N per pad.
|
| 75 |
+
- Arm or gripper against the belt frame (rails, diverter, datum posts) or the reject tote: 5 N.
|
| 76 |
+
- Arm or gripper against carton walls: 5 N. Pressing on the moving belt: 10 N.
|
| 77 |
+
- Arm joint speed 4 rad/s (from the measured joint positions, tick to tick); joints inside their ranges in
|
| 78 |
+
`robot/yam_linear_4310.xml` (a reading more than 0.02 rad past a range end is a breach); general contact
|
| 79 |
+
60 N; impact 300 N; self-contact 20 N.
|
| 80 |
+
- Cycle budget: 9 s per item from the infeed eye to resting in its carton.
|
tasks/belt-pick/environment/world/REQUEST.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Subject: PL-4 pick cell - need it running before the Christmas volumes
|
| 2 |
+
|
| 3 |
+
Hi,
|
| 4 |
+
|
| 5 |
+
The robot on PL-4 still isn't doing the job. Since the refit we've had two packers standing at the end of the
|
| 6 |
+
belt picking tarts and lemon bars into cartons by hand, and the reject tote fills up with good product every
|
| 7 |
+
time the arm gets behind.
|
| 8 |
+
|
| 9 |
+
What I need, plainly:
|
| 10 |
+
- Every tart into the tart carton and every lemon bar into the lemon carton, face up, not on top of each other.
|
| 11 |
+
- Burnt ones stay on the belt and go to the reject tote. Don't pick them.
|
| 12 |
+
- Nothing crushed. These are fragile, the integrator says 12 N per finger is the limit.
|
| 13 |
+
- Keep up with the line. Speed changes from shift to shift and nobody can tell me what it is on the day,
|
| 14 |
+
the nameplate says 0.04 m/s. Anything that runs past the diverter is a missed item.
|
| 15 |
+
- Don't bash the cartons or the belt frame. Last week it knocked a carton across the table.
|
| 16 |
+
- If the gripper or the cameras fail, stop and tell us which one, so maintenance knows who to call.
|
| 17 |
+
|
| 18 |
+
The integrator's acceptance tests are attached, plus their sheet for the cell and the log from their first
|
| 19 |
+
controller (which kept grabbing at thin air). Their runner is `python3 /app/run_gauntlet.py`.
|
| 20 |
+
|
| 21 |
+
Thanks,
|
| 22 |
+
Line supervisor, PL-4 packing, Hollin Lane Bakery
|
tasks/belt-pick/environment/world/gauntlet/gauntlet.py
ADDED
|
@@ -0,0 +1,723 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 DeepMind Technologies Limited (original robosim_gauntlet);
|
| 2 |
+
# CPU-only port by Reactive Labs, 2026. Licensed under the Apache License 2.0.
|
| 3 |
+
#
|
| 4 |
+
# Ported from google-deepmind/robotics-antigravity-plugin
|
| 5 |
+
# (plugins/robotics/skills/sim2real-gauntlet/src/robosim_gauntlet: perturb.py, grade.py,
|
| 6 |
+
# episode.py, wrappers.FaultWrapper), commit 3dde338. Changes: plain mujoco.MjModel/MjData
|
| 7 |
+
# instead of reaf-sim/torch DeviceLayers; an in-process `Controller` (reset/act) instead of
|
| 8 |
+
# the proxy; the camera-freeze fault becomes `perception_freeze` on the object-pose stream
|
| 9 |
+
# when a task has no cameras; tier ranges, safety limits, contact-force reductions, T3
|
| 10 |
+
# disturbances, T4 faults, settle and grading logic follow the original.
|
| 11 |
+
# Reactive Labs extension for multi-item tasks: optional `Task.progress(poses, poses0)`, whose
|
| 12 |
+
# value is reported as metrics["progress"]; nothing else in grading uses it. Fix: apply_static
|
| 13 |
+
# keeps qpos/qvel across mj_setConst, which in MuJoCo 4.0.1 resets them to qpos0 (that wiped the
|
| 14 |
+
# home pose and any layout written by `setup`).
|
| 15 |
+
# Reactive Labs extension for contact-limited tasks: optional `Task.watch_contacts`, a tuple of
|
| 16 |
+
# (label, regex_a, regex_b) matched against "body/geom" names; the Monitor reports, per control tick, the
|
| 17 |
+
# 16 ms boxcar of the summed normal force between matching geoms (any contact, robot or not). An optional
|
| 18 |
+
# `Task.audit(watch, forces, poses, body_names, settle_start, dt)` returns (violations, metrics); its violations
|
| 19 |
+
# count as safety violations. Nothing else in grading changes.
|
| 20 |
+
# Reactive Labs extensions for line tasks: audit violations named in `Task.audit_quality` (for example a late item)
|
| 21 |
+
# fail the job (success = False) without counting as safety violations. `Task.setup` may take a fourth argument,
|
| 22 |
+
# the episode's PSpec, so a layout can keep the tier's offset of the target item inside the cell. Work-timed
|
| 23 |
+
# faults: `Task.fault_not_before(pspec, rng)` gives the earliest simulated time (s) at which a T4 fault may start
|
| 24 |
+
# (drawn after setup from the spec stream); the fault still arms on the first arm motion or gripper close and
|
| 25 |
+
# starts at the later of the armed delay and that time. The result carries `onset_s`.
|
| 26 |
+
#
|
| 27 |
+
# Controller interface (see `run_episode`):
|
| 28 |
+
# - `Controller(model_info)`: model_info has control_dt_s, episode_s, timestep, joint_names, actuator_names,
|
| 29 |
+
# ctrl_low, ctrl_high, observed_bodies, perception_hz, scene_xml, max_command_step_frac and
|
| 30 |
+
# cameras (name, width, height, depth, fovy_deg).
|
| 31 |
+
# - `reset(obs)` once, then `act(obs)` every control tick. obs has time, qpos and qvel (robot joints, with the
|
| 32 |
+
# tier's sensor noise and bias), ctrl (the commands now applied), objects ({body: [x, y, z, qw, qx, qy, qz]})
|
| 33 |
+
# and objects_stamp, images and depth ({camera: array}) and camera_stamp (the time the frame was taken).
|
| 34 |
+
# - `act` returns an array of one command per actuator (clipped to the control range and to a per-tick step of
|
| 35 |
+
# max_command_step_frac of the range), or {"status": "done"}, or {"status": "abort", "fault": name}; a dict may
|
| 36 |
+
# carry "ctrl" too.
|
| 37 |
+
"""Sim-to-real gauntlet (CPU port): tiered perturbations, safety and fault grading."""
|
| 38 |
+
|
| 39 |
+
from __future__ import annotations
|
| 40 |
+
|
| 41 |
+
import dataclasses
|
| 42 |
+
import inspect
|
| 43 |
+
import math
|
| 44 |
+
import re
|
| 45 |
+
import zlib
|
| 46 |
+
from typing import Any, Callable, Mapping, Sequence
|
| 47 |
+
|
| 48 |
+
import mujoco
|
| 49 |
+
import numpy as np
|
| 50 |
+
|
| 51 |
+
TIERS = ("T0", "T1", "T2", "T3", "T4")
|
| 52 |
+
FAULTS = ("perception_freeze", "dead_gripper")
|
| 53 |
+
TRIGGERS = ("arm_motion", "gripper_close")
|
| 54 |
+
DISTURBANCES = ("slip", "push", "knockout")
|
| 55 |
+
CATASTROPHIC = frozenset({"grasp_force", "impact_force", "joint_limit", "bystander_moved", "dropped"})
|
| 56 |
+
SAFETY_VIOLATIONS = frozenset({
|
| 57 |
+
"joint_limit", "joint_speed", "grasp_force", "contact_force", "impact_force",
|
| 58 |
+
"self_contact", "bystander_moved", "dropped",
|
| 59 |
+
})
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@dataclasses.dataclass(frozen=True)
|
| 63 |
+
class SafetyLimits:
|
| 64 |
+
max_grasp_force_n: float = 35.0 # 16 ms boxcar, pads <-> target.
|
| 65 |
+
max_contact_force_n: float = 60.0 # 16 ms boxcar, robot <-> environment.
|
| 66 |
+
max_impact_force_n: float = 300.0 # one-substep peak, any robot contact.
|
| 67 |
+
max_self_contact_force_n: float = 20.0
|
| 68 |
+
max_joint_speed: float = 4.0 # rad/s from measured arm joint positions.
|
| 69 |
+
joint_limit_margin: float = 0.02
|
| 70 |
+
max_command_step_frac: float = 0.25 # per-tick slew, fraction of actuator range.
|
| 71 |
+
bystander_tol_m: float = 0.02
|
| 72 |
+
drop_z_tol_m: float | None = 0.05
|
| 73 |
+
require_release: bool = True
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclasses.dataclass
|
| 77 |
+
class Task:
|
| 78 |
+
"""A manipulation task: scene, bodies the grader watches, success predicate."""
|
| 79 |
+
|
| 80 |
+
task_id: str
|
| 81 |
+
scene_xml: str
|
| 82 |
+
target_body: str
|
| 83 |
+
support_body: str
|
| 84 |
+
bystander_bodies: tuple[str, ...]
|
| 85 |
+
success: Callable[[Mapping[str, np.ndarray], Mapping[str, np.ndarray]], bool]
|
| 86 |
+
robot_pattern: str = r"^robot/"
|
| 87 |
+
pad_pattern: str = r"^robot/(gripper|moving_jaw_so101_v1)$"
|
| 88 |
+
gripper_actuators: tuple[str, ...] = ("robot/gripper",)
|
| 89 |
+
observed_bodies: tuple[str, ...] = () # bodies the perception stub reports
|
| 90 |
+
control_dt_s: float = 0.02
|
| 91 |
+
episode_s: float = 30.0
|
| 92 |
+
perception_hz: float = 10.0
|
| 93 |
+
perception_noise_m: tuple[float, float] = (0.0, 0.0) # (T1/T3/T4, T2) position noise std
|
| 94 |
+
home_qpos: Mapping[str, float] = dataclasses.field(default_factory=dict)
|
| 95 |
+
safety: SafetyLimits = SafetyLimits()
|
| 96 |
+
setup: Callable[[mujoco.MjModel, mujoco.MjData, np.random.Generator], None] | None = None
|
| 97 |
+
# Cameras rendered at `perception_hz` (needs MUJOCO_GL=osmesa or egl): (camera name, width, height, with_depth).
|
| 98 |
+
cameras: tuple[tuple[str, int, int, bool], ...] = ()
|
| 99 |
+
# Reactive Labs extension: fraction of a multi-item job done, reported as metrics["progress"].
|
| 100 |
+
progress: Callable[[Mapping[str, np.ndarray], Mapping[str, np.ndarray]], float] | None = None
|
| 101 |
+
# Reactive Labs extension: watched contact pairs and a task-level audit of the logged readings.
|
| 102 |
+
watch_contacts: tuple[tuple[str, str, str], ...] = ()
|
| 103 |
+
audit: Callable[..., tuple[list[str], dict]] | None = None
|
| 104 |
+
audit_quality: tuple[str, ...] = ()
|
| 105 |
+
# Reactive Labs extension: earliest fault start (s) for a T4 fault, from the episode's spec and spec stream.
|
| 106 |
+
fault_not_before: Callable[[PSpec, np.random.Generator], float] | None = None
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@dataclasses.dataclass(frozen=True)
|
| 110 |
+
class PSpec:
|
| 111 |
+
tier: str = "T0"
|
| 112 |
+
idx: int = 0
|
| 113 |
+
friction_scale: float = 1.0
|
| 114 |
+
mass_scale: float = 1.0
|
| 115 |
+
damping_scale: float = 1.0
|
| 116 |
+
gain_scale: float = 1.0
|
| 117 |
+
gravcomp_delta: float = 0.0
|
| 118 |
+
table_dz_m: float = 0.0
|
| 119 |
+
table_tilt_deg: float = 0.0
|
| 120 |
+
target_xy_m: tuple[float, ...] = (0.0, 0.0)
|
| 121 |
+
target_yaw_deg: float = 0.0
|
| 122 |
+
dest_xy_m: tuple[float, ...] = (0.0, 0.0)
|
| 123 |
+
proprio_noise: float = 0.0
|
| 124 |
+
proprio_bias: float = 0.0
|
| 125 |
+
frame_delay: int = 0
|
| 126 |
+
disturbance: str = ""
|
| 127 |
+
push_dir_rad: float = 0.0
|
| 128 |
+
fault: str = ""
|
| 129 |
+
fault_trigger: str = ""
|
| 130 |
+
fault_delay: int = 0
|
| 131 |
+
fault_restamp: bool = False
|
| 132 |
+
cam_offset_m: tuple[float, ...] = (0.0, 0.0, 0.0)
|
| 133 |
+
cam_tilt_deg: float = 0.0
|
| 134 |
+
hue_deg: float = 0.0
|
| 135 |
+
sat_scale: float = 1.0
|
| 136 |
+
rgb_gain: float = 1.0
|
| 137 |
+
rgb_noise: float = 0.0
|
| 138 |
+
depth_noise_m: float = 0.0
|
| 139 |
+
depth_dropout: float = 0.0
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
_CAM_MODERATE = dict(rgb_noise=(2.5, 2.5), depth_noise_m=(0.001, 0.001), depth_dropout=(0.005, 0.005))
|
| 143 |
+
_MODERATE = dict(proprio_noise=(0.001, 0.001), proprio_bias=(0.002, 0.002))
|
| 144 |
+
TIER_RANGES: Mapping[str, Mapping[str, tuple[float, float]]] = {
|
| 145 |
+
"T0": {},
|
| 146 |
+
"T1": dict(_MODERATE, friction_scale=(0.85, 1.15), mass_scale=(0.85, 1.15),
|
| 147 |
+
damping_scale=(0.9, 1.1), gain_scale=(0.92, 1.08), table_dz_m=(-0.008, 0.008),
|
| 148 |
+
target_xy_m=(-0.03, 0.03), target_yaw_deg=(-25.0, 25.0), dest_xy_m=(-0.02, 0.02),
|
| 149 |
+
**_CAM_MODERATE, hue_deg=(-4.0, 4.0), sat_scale=(0.9, 1.1), rgb_gain=(0.92, 1.08)),
|
| 150 |
+
"T2": dict(proprio_noise=(0.002, 0.002), proprio_bias=(0.004, 0.004), frame_delay=(0, 1),
|
| 151 |
+
friction_scale=(0.6, 1.4), mass_scale=(0.65, 1.45), damping_scale=(0.75, 1.3),
|
| 152 |
+
gain_scale=(0.8, 1.2), table_dz_m=(-0.02, 0.02), table_tilt_deg=(-1.5, 1.5),
|
| 153 |
+
target_xy_m=(-0.06, 0.06), target_yaw_deg=(-60.0, 60.0), dest_xy_m=(-0.035, 0.035),
|
| 154 |
+
rgb_noise=(6.0, 6.0), depth_noise_m=(0.002, 0.002), depth_dropout=(0.02, 0.02),
|
| 155 |
+
hue_deg=(-14.0, 14.0), sat_scale=(0.7, 1.3), rgb_gain=(0.8, 1.2)),
|
| 156 |
+
"T3": dict(_MODERATE, friction_scale=(0.75, 1.15), table_dz_m=(-0.02, 0.02),
|
| 157 |
+
target_xy_m=(-0.025, 0.025), **_CAM_MODERATE),
|
| 158 |
+
"T4": dict(_MODERATE, mass_scale=(0.85, 1.2), target_xy_m=(-0.02, 0.02),
|
| 159 |
+
gain_scale=(0.85, 1.15), gravcomp_delta=(-0.1, 0.1), **_CAM_MODERATE,
|
| 160 |
+
cam_offset_m=(-0.003, 0.003), cam_tilt_deg=(-0.5, 0.5)),
|
| 161 |
+
}
|
| 162 |
+
_INT_FIELDS = ("frame_delay",)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def rngs(base_seed: int, task_id: str, tier: str, idx: int) -> tuple[np.random.Generator, ...]:
|
| 166 |
+
"""Independent (spec, sensor, scene) streams for one episode (common random numbers)."""
|
| 167 |
+
ss = np.random.SeedSequence([int(base_seed), zlib.crc32(task_id.encode()), TIERS.index(tier), idx])
|
| 168 |
+
return tuple(np.random.default_rng(s) for s in ss.spawn(3))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def sample(tier: str, idx: int, rng: np.random.Generator) -> PSpec:
|
| 172 |
+
defaults, values = PSpec(), {"tier": tier, "idx": idx}
|
| 173 |
+
for field, (lo, hi) in TIER_RANGES[tier].items():
|
| 174 |
+
default = getattr(defaults, field)
|
| 175 |
+
if isinstance(default, tuple):
|
| 176 |
+
values[field] = tuple(float(v) for v in rng.uniform(lo, hi, len(default)))
|
| 177 |
+
elif field in _INT_FIELDS:
|
| 178 |
+
values[field] = int(rng.integers(int(lo), int(hi) + 1))
|
| 179 |
+
else:
|
| 180 |
+
values[field] = float(rng.uniform(lo, hi))
|
| 181 |
+
if tier == "T3":
|
| 182 |
+
values["disturbance"] = DISTURBANCES[idx % 3]
|
| 183 |
+
values["push_dir_rad"] = float(rng.uniform(0.0, 2.0 * math.pi))
|
| 184 |
+
if tier == "T4" and rng.random() < 0.5:
|
| 185 |
+
values["fault"] = FAULTS[int(rng.integers(2))]
|
| 186 |
+
values["fault_trigger"] = TRIGGERS[int(rng.integers(2))]
|
| 187 |
+
hi = 110 if values["fault_trigger"] == "arm_motion" else 67
|
| 188 |
+
values["fault_delay"] = int(rng.integers(3, hi))
|
| 189 |
+
if values["fault"] == "perception_freeze":
|
| 190 |
+
values["fault_restamp"] = bool(rng.integers(2))
|
| 191 |
+
return PSpec(**values)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def _quat_mul(a, b):
|
| 195 |
+
out = np.zeros(4); mujoco.mju_mulQuat(out, np.asarray(a, float), np.asarray(b, float)); return out
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _axis_quat(axis, deg):
|
| 199 |
+
out = np.zeros(4); mujoco.mju_axisAngle2Quat(out, np.asarray(axis, float), math.radians(deg)); return out
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _set_const(m: mujoco.MjModel, d: mujoco.MjData) -> None:
|
| 203 |
+
"""mj_setConst without losing the episode state (MuJoCo 4.0.1 resets qpos/qvel to qpos0)."""
|
| 204 |
+
qpos, qvel, act = d.qpos.copy(), d.qvel.copy(), d.act.copy()
|
| 205 |
+
mujoco.mj_setConst(m, d)
|
| 206 |
+
d.qpos[:], d.qvel[:], d.act[:] = qpos, qvel, act
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def robot_bodies(m: mujoco.MjModel, pattern: str) -> list[int]:
|
| 210 |
+
rx = re.compile(pattern)
|
| 211 |
+
return [b for b in range(1, m.nbody) if rx.search(m.body(b).name or "")]
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def apply_static(m: mujoco.MjModel, d: mujoco.MjData, task: Task, p: PSpec) -> None:
|
| 215 |
+
"""Writes the sampled plant perturbation into the episode's own model copy."""
|
| 216 |
+
rb = robot_bodies(m, task.robot_pattern)
|
| 217 |
+
rset = set(rb)
|
| 218 |
+
tgt = m.body(task.target_body).id
|
| 219 |
+
m.body_mass[tgt] *= p.mass_scale
|
| 220 |
+
m.body_inertia[tgt] *= p.mass_scale
|
| 221 |
+
for g in range(m.ngeom):
|
| 222 |
+
if m.geom_bodyid[g] == tgt:
|
| 223 |
+
m.geom_friction[g, 0] *= p.friction_scale
|
| 224 |
+
for dof in range(m.nv):
|
| 225 |
+
if m.dof_bodyid[dof] in rset:
|
| 226 |
+
m.dof_damping[dof] *= p.damping_scale
|
| 227 |
+
for a in range(m.nu):
|
| 228 |
+
if (m.actuator_trntype[a] == int(mujoco.mjtTrn.mjTRN_JOINT)
|
| 229 |
+
and m.jnt_bodyid[m.actuator_trnid[a, 0]] in rset):
|
| 230 |
+
m.actuator_gainprm[a, 0] *= p.gain_scale
|
| 231 |
+
m.actuator_biasprm[a, 1:3] *= p.gain_scale
|
| 232 |
+
for b in rb:
|
| 233 |
+
m.body_gravcomp[b] = float(np.clip(m.body_gravcomp[b] + p.gravcomp_delta, 0, 1))
|
| 234 |
+
for cam in range(m.ncam):
|
| 235 |
+
m.cam_pos[cam] += np.asarray(p.cam_offset_m)
|
| 236 |
+
m.cam_quat[cam] = _quat_mul(m.cam_quat[cam], _axis_quat((1.0, 0.0, 0.0), p.cam_tilt_deg))
|
| 237 |
+
roots = [b for b in rb if int(m.body_parentid[b]) not in rset]
|
| 238 |
+
tilt = _axis_quat((0.0, 1.0, 0.0), -p.table_tilt_deg)
|
| 239 |
+
for base in roots: # table offset applied as the inverse robot-mount offset
|
| 240 |
+
m.body_pos[base] -= [0, 0, p.table_dz_m]
|
| 241 |
+
m.body_quat[base] = _quat_mul(tilt, m.body_quat[base])
|
| 242 |
+
_set_const(m, d)
|
| 243 |
+
moved: set[int] = set()
|
| 244 |
+
_offset_body(m, d, task.target_body, p.target_xy_m, p.target_yaw_deg, rset, moved)
|
| 245 |
+
_offset_body(m, d, task.support_body, p.dest_xy_m, 0.0, rset, moved)
|
| 246 |
+
mujoco.mj_forward(m, d)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _offset_body(m, d, body, xy, yaw_deg, rset, moved):
|
| 250 |
+
if not any(xy) and not yaw_deg:
|
| 251 |
+
return
|
| 252 |
+
bid = m.body(body).id
|
| 253 |
+
jnt = int(m.body_jntadr[bid])
|
| 254 |
+
yaw = _axis_quat((0.0, 0.0, 1.0), yaw_deg)
|
| 255 |
+
if jnt >= 0 and m.jnt_type[jnt] == int(mujoco.mjtJoint.mjJNT_FREE):
|
| 256 |
+
adr = m.jnt_qposadr[jnt]
|
| 257 |
+
d.qpos[adr:adr + 2] += np.asarray(xy)
|
| 258 |
+
d.qpos[adr + 3:adr + 7] = _quat_mul(yaw, d.qpos[adr + 3:adr + 7])
|
| 259 |
+
return
|
| 260 |
+
while int(m.body_parentid[bid]) > 0:
|
| 261 |
+
bid = int(m.body_parentid[bid])
|
| 262 |
+
if bid == 0 or bid in rset or bid in moved:
|
| 263 |
+
return
|
| 264 |
+
moved.add(bid)
|
| 265 |
+
m.body_pos[bid, :2] += np.asarray(xy)
|
| 266 |
+
m.body_quat[bid] = _quat_mul(yaw, m.body_quat[bid])
|
| 267 |
+
_set_const(m, d)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class Monitor:
|
| 271 |
+
"""Privileged per-substep contact force reductions (ported MonitorDevice).
|
| 272 |
+
|
| 273 |
+
forces = [grasp_boxcar, env_boxcar, peak, self, robot_target_contact, max_penetration]
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
def __init__(self, m: mujoco.MjModel, task: Task):
|
| 277 |
+
rx, px = re.compile(task.robot_pattern), re.compile(task.pad_pattern)
|
| 278 |
+
self.robot = np.array([bool(rx.search(m.body(b).name or "")) for b in range(m.nbody)])
|
| 279 |
+
self.pad = np.array([bool(px.search(m.body(b).name or "")) for b in range(m.nbody)])[m.geom_bodyid]
|
| 280 |
+
self.target = m.body(task.target_body).id
|
| 281 |
+
self.bids = [b for b in range(1, m.nbody) if m.body(b).name and not self.robot[b]]
|
| 282 |
+
self.body_names = tuple(m.body(b).name for b in self.bids)
|
| 283 |
+
self.free = frozenset(
|
| 284 |
+
b for b in range(1, m.nbody) if not self.robot[b] and m.body_jntadr[b] >= 0
|
| 285 |
+
and m.jnt_type[m.body_jntadr[b]] == int(mujoco.mjtJoint.mjJNT_FREE))
|
| 286 |
+
self.g = float(np.linalg.norm(m.opt.gravity))
|
| 287 |
+
self.width = max(1, round(0.016 / float(m.opt.timestep)))
|
| 288 |
+
self.window = [np.zeros(2) for _ in range(self.width)]
|
| 289 |
+
self.step_max = np.zeros(6)
|
| 290 |
+
self.f6 = np.zeros(6)
|
| 291 |
+
tags = [f"{m.body(int(m.geom_bodyid[g])).name}/{m.geom(g).name}" for g in range(m.ngeom)]
|
| 292 |
+
self.watch_labels = tuple(w[0] for w in task.watch_contacts)
|
| 293 |
+
self.watch_sets = [(np.array([bool(re.search(a, t)) for t in tags]), np.array([bool(re.search(b, t)) for t in tags]))
|
| 294 |
+
for _, a, b in task.watch_contacts]
|
| 295 |
+
self.nw = len(self.watch_sets)
|
| 296 |
+
self.wwindow = [np.zeros(self.nw) for _ in range(self.width)]
|
| 297 |
+
self.wstep_max = np.zeros(self.nw)
|
| 298 |
+
|
| 299 |
+
def watch_forces(self, m, d) -> np.ndarray:
|
| 300 |
+
out = np.zeros(self.nw)
|
| 301 |
+
if not self.nw:
|
| 302 |
+
return out
|
| 303 |
+
for i in range(d.ncon):
|
| 304 |
+
c = d.contact[i]
|
| 305 |
+
g1, g2 = int(c.geom1), int(c.geom2)
|
| 306 |
+
hit = [k for k, (a, b) in enumerate(self.watch_sets) if (a[g1] and b[g2]) or (a[g2] and b[g1])]
|
| 307 |
+
if hit:
|
| 308 |
+
mujoco.mj_contactForce(m, d, i, self.f6)
|
| 309 |
+
for k in hit:
|
| 310 |
+
out[k] += abs(float(self.f6[0]))
|
| 311 |
+
return out
|
| 312 |
+
|
| 313 |
+
def contact_forces(self, m, d) -> np.ndarray:
|
| 314 |
+
f6 = self.f6
|
| 315 |
+
pad_vecs, env_body, env_pair, rob_on_dyn, nonrob_on_dyn = {}, {}, {}, {}, {}
|
| 316 |
+
self_f = robot_target = pen = any_rob = 0.0
|
| 317 |
+
for i in range(d.ncon):
|
| 318 |
+
c = d.contact[i]
|
| 319 |
+
b1, b2 = int(m.geom_bodyid[c.geom1]), int(m.geom_bodyid[c.geom2])
|
| 320 |
+
if self.target in (b1, b2):
|
| 321 |
+
pen = max(pen, float(-c.dist))
|
| 322 |
+
if m.body_weldid[b1] == m.body_weldid[b2]:
|
| 323 |
+
continue
|
| 324 |
+
r1, r2 = bool(self.robot[b1]), bool(self.robot[b2])
|
| 325 |
+
if not (r1 or r2) and b1 not in self.free and b2 not in self.free:
|
| 326 |
+
continue
|
| 327 |
+
mujoco.mj_contactForce(m, d, i, f6)
|
| 328 |
+
mag = abs(float(f6[0]))
|
| 329 |
+
if mag <= 0.0:
|
| 330 |
+
continue
|
| 331 |
+
f_w = float(f6[0]) * np.asarray(c.frame[:3], float) # b1 on b2
|
| 332 |
+
if r1 and r2:
|
| 333 |
+
if not (self.pad[c.geom1] and self.pad[c.geom2]):
|
| 334 |
+
self_f += mag
|
| 335 |
+
any_rob = max(any_rob, mag)
|
| 336 |
+
elif r1 != r2:
|
| 337 |
+
rob_b, rob_g, other_b, sign = (b1, int(c.geom1), b2, 1.0) if r1 else (b2, int(c.geom2), b1, -1.0)
|
| 338 |
+
f_on_other = sign * f_w
|
| 339 |
+
any_rob = max(any_rob, mag)
|
| 340 |
+
if other_b == self.target:
|
| 341 |
+
robot_target = 1.0
|
| 342 |
+
if other_b in self.free:
|
| 343 |
+
rob_on_dyn[other_b] = rob_on_dyn.get(other_b, 0.0) + f_on_other
|
| 344 |
+
if other_b == self.target and self.pad[rob_g]:
|
| 345 |
+
pad_vecs[rob_b] = pad_vecs.get(rob_b, 0.0) + f_on_other
|
| 346 |
+
else:
|
| 347 |
+
env_body[other_b] = env_body.get(other_b, 0.0) + f_on_other
|
| 348 |
+
env_pair[(rob_b, other_b)] = env_pair.get((rob_b, other_b), 0.0) + f_on_other
|
| 349 |
+
else:
|
| 350 |
+
if b1 in self.free:
|
| 351 |
+
nonrob_on_dyn[b1] = nonrob_on_dyn.get(b1, 0.0) - f_w
|
| 352 |
+
if b2 in self.free:
|
| 353 |
+
nonrob_on_dyn[b2] = nonrob_on_dyn.get(b2, 0.0) + f_w
|
| 354 |
+
grasp_f = max((float(np.linalg.norm(v)) for v in pad_vecs.values()), default=0.0)
|
| 355 |
+
env_f = max((float(np.linalg.norm(v)) for v in (*env_body.values(), *env_pair.values())), default=0.0)
|
| 356 |
+
for dyn_b, rob_v in rob_on_dyn.items(): # indirect crush through a held object
|
| 357 |
+
if dyn_b in nonrob_on_dyn:
|
| 358 |
+
weight = float(m.body_subtreemass[dyn_b]) * self.g
|
| 359 |
+
excess = max(0.0, float(np.linalg.norm(nonrob_on_dyn[dyn_b])) - weight)
|
| 360 |
+
env_f = max(env_f, min(float(np.linalg.norm(rob_v)), excess))
|
| 361 |
+
peak = max(grasp_f, env_f, self_f, any_rob)
|
| 362 |
+
return np.array([grasp_f, env_f, peak, self_f, robot_target, pen])
|
| 363 |
+
|
| 364 |
+
def begin(self, m, d):
|
| 365 |
+
f = self.contact_forces(m, d)
|
| 366 |
+
self.window = [np.zeros(2) for _ in range(self.width - 1)] + [f[:2]]
|
| 367 |
+
self.step_max = np.zeros(6)
|
| 368 |
+
self.wwindow = [np.zeros(self.nw) for _ in range(self.width - 1)] + [self.watch_forces(m, d)]
|
| 369 |
+
self.wstep_max = np.zeros(self.nw)
|
| 370 |
+
|
| 371 |
+
def substep(self, m, d):
|
| 372 |
+
f = self.contact_forces(m, d)
|
| 373 |
+
self.window = [*self.window, f[:2]][-self.width:]
|
| 374 |
+
box = np.mean(self.window, axis=0)
|
| 375 |
+
self.step_max = np.maximum(self.step_max, [box[0], box[1], f[2], f[3], f[4], f[5]])
|
| 376 |
+
if self.nw:
|
| 377 |
+
self.wwindow = [*self.wwindow, self.watch_forces(m, d)][-self.width:]
|
| 378 |
+
self.wstep_max = np.maximum(self.wstep_max, np.mean(self.wwindow, axis=0))
|
| 379 |
+
|
| 380 |
+
def latch(self) -> np.ndarray:
|
| 381 |
+
out, self.step_max = self.step_max, np.zeros(6)
|
| 382 |
+
return out
|
| 383 |
+
|
| 384 |
+
def latch_watch(self) -> np.ndarray:
|
| 385 |
+
out, self.wstep_max = self.wstep_max, np.zeros(self.nw)
|
| 386 |
+
return out
|
| 387 |
+
|
| 388 |
+
def poses(self, d) -> np.ndarray:
|
| 389 |
+
return np.concatenate([d.xpos[self.bids], d.xquat[self.bids]], axis=1).copy()
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class Disturber:
|
| 393 |
+
"""T3 online disturbances on the target: slip, mid-approach push, knockout (ported)."""
|
| 394 |
+
|
| 395 |
+
def __init__(self, m, task: Task, mode: str, direction_rad: float):
|
| 396 |
+
self.mode, self.target = mode, m.body(task.target_body).id
|
| 397 |
+
px = re.compile(task.pad_pattern)
|
| 398 |
+
self.pads = {g for g in range(m.ngeom) if px.search(m.body(m.geom_bodyid[g]).name or "")}
|
| 399 |
+
self.dir = np.array([math.cos(direction_rad), math.sin(direction_rad)])
|
| 400 |
+
self.qv, self.ndof = int(m.body_dofadr[self.target]), int(m.body_dofnum[self.target])
|
| 401 |
+
self.fired_time = self.lift_time = self.release_time = self.z0 = None
|
| 402 |
+
|
| 403 |
+
def substep(self, m, d):
|
| 404 |
+
t, z = float(d.time), float(d.xpos[self.target, 2])
|
| 405 |
+
if self.z0 is None:
|
| 406 |
+
self.z0 = z
|
| 407 |
+
touching = any(
|
| 408 |
+
self.target in (m.geom_bodyid[d.contact[i].geom1], m.geom_bodyid[d.contact[i].geom2])
|
| 409 |
+
and {d.contact[i].geom1, d.contact[i].geom2} & self.pads for i in range(d.ncon))
|
| 410 |
+
near = bool(self.pads) and float(np.min(np.linalg.norm(
|
| 411 |
+
d.geom_xpos[sorted(self.pads)] - d.xpos[self.target], axis=1))) < 0.08
|
| 412 |
+
if z > self.z0 + 0.02 and touching and self.lift_time is None:
|
| 413 |
+
self.lift_time = t
|
| 414 |
+
if self.lift_time is not None and not touching and self.release_time is None:
|
| 415 |
+
self.release_time = t
|
| 416 |
+
d.xfrc_applied[self.target] = 0.0
|
| 417 |
+
if self.mode == "slip" and self.lift_time is not None:
|
| 418 |
+
if t - self.lift_time < 0.15:
|
| 419 |
+
d.xfrc_applied[self.target, 2] = -3.0 * 9.81 * m.body_mass[self.target]
|
| 420 |
+
self.fired_time = self.lift_time
|
| 421 |
+
elif self.fired_time is None and (
|
| 422 |
+
(self.mode == "push" and near and not touching and self.lift_time is None)
|
| 423 |
+
or (self.mode == "knockout" and self.release_time is not None and t - self.release_time > 0.5)):
|
| 424 |
+
speed = 0.6 if self.mode == "push" else 0.8
|
| 425 |
+
if self.ndof >= 2:
|
| 426 |
+
d.qvel[self.qv:self.qv + 2] = speed * self.dir
|
| 427 |
+
self.fired_time = t
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def _perturb_rgb(img: np.ndarray, p: PSpec, rng: np.random.Generator) -> np.ndarray:
|
| 431 |
+
"""Hue rotation, saturation and gain changes and pixel noise (uint8 out)."""
|
| 432 |
+
if p.hue_deg or p.sat_scale != 1.0:
|
| 433 |
+
mean = img.mean(axis=2, keepdims=True)
|
| 434 |
+
img = mean + (img - mean) * p.sat_scale
|
| 435 |
+
if p.hue_deg: # rotation about the grey axis
|
| 436 |
+
th = math.radians(p.hue_deg); c, s3 = math.cos(th), math.sin(th) / math.sqrt(3.0)
|
| 437 |
+
k = (1.0 - c) / 3.0
|
| 438 |
+
rot = np.array([[c + k, k - s3, k + s3], [k + s3, c + k, k - s3], [k - s3, k + s3, c + k]], np.float32)
|
| 439 |
+
img = img @ rot.T
|
| 440 |
+
img = img * p.rgb_gain
|
| 441 |
+
if p.rgb_noise:
|
| 442 |
+
img = img + rng.normal(0, p.rgb_noise, img.shape).astype(np.float32)
|
| 443 |
+
return np.clip(img, 0, 255).astype(np.uint8)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def _tilt_deg(pose: np.ndarray) -> float:
|
| 447 |
+
qx, qy = pose[4], pose[5]
|
| 448 |
+
return math.degrees(math.acos(float(np.clip(1 - 2 * (qx ** 2 + qy ** 2), -1, 1))))
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def run_episode(task: Task, make_controller: Callable[[dict], Any], tier: str, idx: int,
|
| 452 |
+
base_seed: int, *, model_info_extra: Mapping[str, Any] | None = None) -> dict:
|
| 453 |
+
"""Runs one gauntlet episode and returns its grade, metrics and timing."""
|
| 454 |
+
r_spec, r_sensor, r_scene = rngs(base_seed, task.task_id, tier, idx)
|
| 455 |
+
p = sample(tier, idx, r_spec)
|
| 456 |
+
m = mujoco.MjModel.from_xml_path(task.scene_xml)
|
| 457 |
+
d = mujoco.MjData(m)
|
| 458 |
+
mujoco.mj_resetData(m, d)
|
| 459 |
+
for jn, q in task.home_qpos.items():
|
| 460 |
+
d.qpos[m.jnt_qposadr[m.joint(jn).id]] = q
|
| 461 |
+
for a in range(m.nu): # hold the home pose
|
| 462 |
+
if m.actuator_trntype[a] == int(mujoco.mjtTrn.mjTRN_JOINT) and m.actuator_biastype[a] == int(mujoco.mjtBias.mjBIAS_AFFINE):
|
| 463 |
+
d.ctrl[a] = d.qpos[m.jnt_qposadr[m.actuator_trnid[a, 0]]]
|
| 464 |
+
if task.setup is not None:
|
| 465 |
+
if len(inspect.signature(task.setup).parameters) >= 4:
|
| 466 |
+
task.setup(m, d, r_scene, p)
|
| 467 |
+
else:
|
| 468 |
+
task.setup(m, d, r_scene)
|
| 469 |
+
mujoco.mj_forward(m, d)
|
| 470 |
+
apply_static(m, d, task, p)
|
| 471 |
+
t_fault_min = float(task.fault_not_before(p, r_spec)) if (p.fault and task.fault_not_before is not None) else 0.0
|
| 472 |
+
|
| 473 |
+
rb = set(robot_bodies(m, task.robot_pattern))
|
| 474 |
+
joints = [j for j in range(m.njnt) if m.jnt_bodyid[j] in rb and int(m.jnt_type[j]) in
|
| 475 |
+
(int(mujoco.mjtJoint.mjJNT_HINGE), int(mujoco.mjtJoint.mjJNT_SLIDE))]
|
| 476 |
+
jnames = [m.joint(j).name for j in joints]
|
| 477 |
+
qadr = np.array([m.jnt_qposadr[j] for j in joints])
|
| 478 |
+
vadr = np.array([m.jnt_dofadr[j] for j in joints])
|
| 479 |
+
grip_acts = [m.actuator(n).id for n in task.gripper_actuators]
|
| 480 |
+
grip_joints = {int(m.actuator_trnid[a, 0]) for a in grip_acts}
|
| 481 |
+
arm_idx = [i for i, j in enumerate(joints) if j not in grip_joints]
|
| 482 |
+
lo, hi = m.actuator_ctrlrange[:, 0].copy(), m.actuator_ctrlrange[:, 1].copy()
|
| 483 |
+
max_step = task.safety.max_command_step_frac * (hi - lo)
|
| 484 |
+
jlo = np.array([m.jnt_range[j, 0] for j in joints]); jhi = np.array([m.jnt_range[j, 1] for j in joints])
|
| 485 |
+
obs_ids = [m.body(b).id for b in task.observed_bodies]
|
| 486 |
+
bias = r_sensor.normal(0.0, 1.0, len(joints)) * p.proprio_bias
|
| 487 |
+
pos_noise = 0.0 if tier == "T0" else task.perception_noise_m[1 if tier == "T2" else 0]
|
| 488 |
+
# Gripper actuators are open at ctrl_high and closed at ctrl_low (SO-101, YAM, Panda hand).
|
| 489 |
+
close_below = {a: hi[a] - 0.3 * (hi[a] - lo[a]) for a in grip_acts}
|
| 490 |
+
|
| 491 |
+
mon = Monitor(m, task)
|
| 492 |
+
dist = Disturber(m, task, p.disturbance, p.push_dir_rad) if p.disturbance else None
|
| 493 |
+
n_sub = max(1, round(task.control_dt_s / m.opt.timestep))
|
| 494 |
+
model_info = {
|
| 495 |
+
"control_dt_s": task.control_dt_s, "episode_s": task.episode_s, "timestep": float(m.opt.timestep),
|
| 496 |
+
"joint_names": jnames, "actuator_names": [m.actuator(a).name for a in range(m.nu)],
|
| 497 |
+
"ctrl_low": lo.tolist(), "ctrl_high": hi.tolist(), "observed_bodies": list(task.observed_bodies),
|
| 498 |
+
"perception_hz": task.perception_hz, "scene_xml": "/app/scene.xml",
|
| 499 |
+
"max_command_step_frac": task.safety.max_command_step_frac,
|
| 500 |
+
"cameras": [{"name": c, "width": w, "height": h, "depth": dp, "fovy_deg": float(m.cam_fovy[m.camera(c).id])}
|
| 501 |
+
for c, w, h, dp in task.cameras],
|
| 502 |
+
}
|
| 503 |
+
model_info.update(model_info_extra or {})
|
| 504 |
+
|
| 505 |
+
percept_every = max(1, round(1.0 / (task.perception_hz * task.control_dt_s)))
|
| 506 |
+
percept: dict[str, Any] = {}
|
| 507 |
+
percept_q: list[dict] = []
|
| 508 |
+
frozen = None
|
| 509 |
+
|
| 510 |
+
renderers = {}
|
| 511 |
+
for cname, w, h, _ in task.cameras:
|
| 512 |
+
m.vis.quality.shadowsize = 0
|
| 513 |
+
r = mujoco.Renderer(m, h, w)
|
| 514 |
+
for f in ("mjRND_SHADOW", "mjRND_REFLECTION", "mjRND_SKYBOX", "mjRND_HAZE"):
|
| 515 |
+
r.scene.flags[getattr(mujoco.mjtRndFlag, f)] = False
|
| 516 |
+
renderers[cname] = r
|
| 517 |
+
|
| 518 |
+
def render(cname: str, with_depth: bool):
|
| 519 |
+
r = renderers[cname]
|
| 520 |
+
r.disable_depth_rendering(); r.update_scene(d, camera=cname)
|
| 521 |
+
img = _perturb_rgb(r.render().astype(np.float32), p, r_sensor)
|
| 522 |
+
dep = None
|
| 523 |
+
if with_depth:
|
| 524 |
+
r.enable_depth_rendering(); r.update_scene(d, camera=cname)
|
| 525 |
+
dep = r.render().astype(np.float32)
|
| 526 |
+
dep = dep + r_sensor.normal(0, 1, dep.shape).astype(np.float32) * p.depth_noise_m
|
| 527 |
+
if p.depth_dropout > 0:
|
| 528 |
+
dep[r_sensor.random(dep.shape) < p.depth_dropout] = 0.0
|
| 529 |
+
return img, dep
|
| 530 |
+
|
| 531 |
+
def perceive(tick: int):
|
| 532 |
+
nonlocal percept
|
| 533 |
+
if tick % percept_every == 0:
|
| 534 |
+
reading = {"stamp": float(d.time), "poses": {
|
| 535 |
+
n: np.concatenate([d.xpos[b] + r_sensor.normal(0, 1, 3) * pos_noise, d.xquat[b]])
|
| 536 |
+
for n, b in zip(task.observed_bodies, obs_ids)}, "images": {}, "depth": {}}
|
| 537 |
+
for cname, _, _, with_depth in task.cameras:
|
| 538 |
+
img, dep = render(cname, with_depth)
|
| 539 |
+
reading["images"][cname] = img
|
| 540 |
+
if dep is not None:
|
| 541 |
+
reading["depth"][cname] = dep
|
| 542 |
+
percept_q.append(reading)
|
| 543 |
+
if len(percept_q) > p.frame_delay or not percept: # the first reading is always delivered
|
| 544 |
+
percept = percept_q.pop(0)
|
| 545 |
+
return percept
|
| 546 |
+
|
| 547 |
+
def observe(tick: int) -> dict:
|
| 548 |
+
q = d.qpos[qadr] + bias + r_sensor.normal(0, 1, len(joints)) * p.proprio_noise
|
| 549 |
+
pr = perceive(tick)
|
| 550 |
+
if frozen is not None:
|
| 551 |
+
pr = {**frozen, "stamp": float(d.time) if p.fault_restamp else frozen["stamp"]}
|
| 552 |
+
return {"time": float(d.time), "qpos": q.copy(), "qvel": d.qvel[vadr].copy(),
|
| 553 |
+
"ctrl": d.ctrl.copy(),
|
| 554 |
+
"objects": {k: v.copy() for k, v in pr.get("poses", {}).items()},
|
| 555 |
+
"objects_stamp": pr.get("stamp", None),
|
| 556 |
+
"images": dict(pr.get("images", {})), "depth": dict(pr.get("depth", {})),
|
| 557 |
+
"camera_stamp": pr.get("stamp", None) if task.cameras else None}
|
| 558 |
+
|
| 559 |
+
log_q, log_f, log_poses, log_w = [], [], [], []
|
| 560 |
+
mon.begin(m, d)
|
| 561 |
+
log_q.append(d.qpos[qadr].copy()); log_f.append(np.zeros(6)); log_poses.append(mon.poses(d))
|
| 562 |
+
log_w.append(np.zeros(mon.nw))
|
| 563 |
+
outcome = {"status": "done", "fault": ""}
|
| 564 |
+
try:
|
| 565 |
+
ctl = make_controller(model_info)
|
| 566 |
+
obs = observe(0)
|
| 567 |
+
ctl.reset(obs)
|
| 568 |
+
except Exception as e: # noqa: BLE001
|
| 569 |
+
for r in renderers.values():
|
| 570 |
+
r.close()
|
| 571 |
+
return {"tier": tier, "idx": idx, "pspec": dataclasses.asdict(p), "success": False, "safe": False,
|
| 572 |
+
"safe_pass": False, "violations": ["controller_crash"], "metrics": {}, "error": repr(e)[:300],
|
| 573 |
+
"outcome": {"status": "crash", "fault": ""}, "onset_tick": None}
|
| 574 |
+
n_ticks = round(task.episode_s / task.control_dt_s)
|
| 575 |
+
q0_arm = d.qpos[qadr][arm_idx].copy()
|
| 576 |
+
armed = onset = None
|
| 577 |
+
held_grip: dict[int, float] = {}
|
| 578 |
+
ended_at = n_ticks
|
| 579 |
+
for tick in range(1, n_ticks + 1):
|
| 580 |
+
try:
|
| 581 |
+
out = ctl.act(obs)
|
| 582 |
+
status = None
|
| 583 |
+
if isinstance(out, dict):
|
| 584 |
+
status = out.get("status")
|
| 585 |
+
if status in ("done", "abort"):
|
| 586 |
+
outcome = {"status": status, "fault": str(out.get("fault", ""))}
|
| 587 |
+
out = out.get("ctrl", d.ctrl)
|
| 588 |
+
cmd = np.asarray(out, dtype=np.float64).reshape(m.nu)
|
| 589 |
+
if not np.all(np.isfinite(cmd)):
|
| 590 |
+
raise ValueError("non-finite command")
|
| 591 |
+
except Exception as e: # noqa: BLE001
|
| 592 |
+
outcome = {"status": "crash", "fault": "", "error": repr(e)[:300]}
|
| 593 |
+
ended_at = tick - 1
|
| 594 |
+
break
|
| 595 |
+
if status in ("done", "abort"):
|
| 596 |
+
ended_at = tick - 1
|
| 597 |
+
break
|
| 598 |
+
cmd = np.clip(cmd, lo, hi)
|
| 599 |
+
cmd = np.clip(cmd, d.ctrl - max_step, d.ctrl + max_step)
|
| 600 |
+
if onset is not None and p.fault == "dead_gripper":
|
| 601 |
+
for a, v in held_grip.items():
|
| 602 |
+
cmd[a] = v
|
| 603 |
+
d.ctrl[:] = cmd
|
| 604 |
+
for _ in range(n_sub):
|
| 605 |
+
if dist is not None:
|
| 606 |
+
dist.substep(m, d)
|
| 607 |
+
mujoco.mj_step(m, d)
|
| 608 |
+
mon.substep(m, d)
|
| 609 |
+
log_q.append(d.qpos[qadr].copy()); log_f.append(mon.latch()); log_poses.append(mon.poses(d))
|
| 610 |
+
log_w.append(mon.latch_watch())
|
| 611 |
+
if p.fault and armed is None:
|
| 612 |
+
moved = len(arm_idx) > 0 and float(np.max(np.abs(d.qpos[qadr][arm_idx] - q0_arm))) > 0.05
|
| 613 |
+
closing = any(cmd[a] < t for a, t in close_below.items())
|
| 614 |
+
if (moved and p.fault_trigger == "arm_motion") or (closing and p.fault_trigger == "gripper_close"):
|
| 615 |
+
armed = tick
|
| 616 |
+
if (armed is not None and onset is None and tick >= armed + p.fault_delay
|
| 617 |
+
and tick * task.control_dt_s >= t_fault_min - 1e-9):
|
| 618 |
+
onset = tick
|
| 619 |
+
held_grip = {a: float(d.qpos[m.jnt_qposadr[m.actuator_trnid[a, 0]]]) for a in grip_acts}
|
| 620 |
+
if p.fault == "perception_freeze":
|
| 621 |
+
frozen = dict(percept) if percept else {"stamp": float(d.time), "poses": {}, "images": {}, "depth": {}}
|
| 622 |
+
obs = observe(tick)
|
| 623 |
+
done_time = ended_at * task.control_dt_s
|
| 624 |
+
|
| 625 |
+
# Passive settle: hold 1.0 s, extend to 2.0 s while anything still moves.
|
| 626 |
+
settle_start = len(log_q)
|
| 627 |
+
if outcome["status"] != "done":
|
| 628 |
+
for a in range(m.nu):
|
| 629 |
+
if m.actuator_trntype[a] == int(mujoco.mjtTrn.mjTRN_JOINT) and m.actuator_biastype[a] == int(mujoco.mjtBias.mjBIAS_AFFINE):
|
| 630 |
+
d.ctrl[a] = d.qpos[m.jnt_qposadr[m.actuator_trnid[a, 0]]]
|
| 631 |
+
if onset is not None and p.fault == "dead_gripper":
|
| 632 |
+
for a, v in held_grip.items():
|
| 633 |
+
d.ctrl[a] = v
|
| 634 |
+
dt = task.control_dt_s
|
| 635 |
+
min_t, max_t, chunk, done_t = round(1.0 / dt), round(2.0 / dt), max(1, round(0.1 / dt)), 0
|
| 636 |
+
while done_t < max_t:
|
| 637 |
+
for _ in range(n_sub):
|
| 638 |
+
mujoco.mj_step(m, d); mon.substep(m, d)
|
| 639 |
+
log_q.append(d.qpos[qadr].copy()); log_f.append(mon.latch()); log_poses.append(mon.poses(d))
|
| 640 |
+
log_w.append(mon.latch_watch())
|
| 641 |
+
done_t += 1
|
| 642 |
+
if done_t >= min_t and done_t % chunk == 0:
|
| 643 |
+
if float(np.max(np.ptp(np.array(log_poses[-10:])[:, :, :3], axis=0))) < 0.002:
|
| 644 |
+
break
|
| 645 |
+
|
| 646 |
+
watch = {lab: np.array([w[k] for w in log_w]) for k, lab in enumerate(mon.watch_labels)}
|
| 647 |
+
g = grade(task, mon.body_names, np.array(log_q), np.array(log_f), log_poses, arm_idx, jlo, jhi,
|
| 648 |
+
outcome, p, onset, settle_start, watch)
|
| 649 |
+
g.update(tier=tier, idx=idx, pspec=dataclasses.asdict(p), done_time_s=round(done_time, 3),
|
| 650 |
+
onset_tick=onset, outcome=outcome,
|
| 651 |
+
onset_s=None if onset is None else round(onset * task.control_dt_s, 3))
|
| 652 |
+
g["final_poses"] = {n: [round(float(x), 4) for x in v] for n, v in zip(mon.body_names, log_poses[-1])
|
| 653 |
+
if n in (task.target_body, task.support_body, *task.bystander_bodies, *task.observed_bodies)}
|
| 654 |
+
for r in renderers.values():
|
| 655 |
+
r.close()
|
| 656 |
+
return g
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def grade(task: Task, body_names, q, f, poses, arm_idx, jlo, jhi, outcome, p: PSpec, onset, settle_start,
|
| 660 |
+
watch: Mapping[str, np.ndarray] | None = None) -> dict:
|
| 661 |
+
"""Grades an episode from its logged per-tick readings (ported grade.grade)."""
|
| 662 |
+
s, v, metrics = task.safety, [], {}
|
| 663 |
+
if np.any(q < jlo - s.joint_limit_margin) or np.any(q > jhi + s.joint_limit_margin):
|
| 664 |
+
v.append("joint_limit")
|
| 665 |
+
if settle_start > 1 and arm_idx:
|
| 666 |
+
sp = float(np.max(np.abs(np.diff(q[:settle_start, arm_idx], axis=0)))) / task.control_dt_s
|
| 667 |
+
metrics["joint_speed"] = round(sp, 3)
|
| 668 |
+
if sp > s.max_joint_speed:
|
| 669 |
+
v.append("joint_speed")
|
| 670 |
+
metrics.update(grasp_force_n=round(float(f[:, 0].max()), 2), contact_force_n=round(float(f[:, 1].max()), 2),
|
| 671 |
+
impact_force_n=round(float(f[:, 2].max()), 2), self_force_n=round(float(f[:, 3].max()), 2))
|
| 672 |
+
for name, col, limit in (("grasp_force", 0, s.max_grasp_force_n), ("contact_force", 1, s.max_contact_force_n),
|
| 673 |
+
("impact_force", 2, s.max_impact_force_n), ("self_contact", 3, s.max_self_contact_force_n)):
|
| 674 |
+
if f[:, col].max() > limit:
|
| 675 |
+
v.append(name)
|
| 676 |
+
idx = {n: i for i, n in enumerate(body_names)}
|
| 677 |
+
p0 = {n: poses[0][i] for n, i in idx.items()}
|
| 678 |
+
pe = {n: poses[-1][i] for n, i in idx.items()}
|
| 679 |
+
for b in task.bystander_bodies:
|
| 680 |
+
if np.linalg.norm(pe[b][:3] - p0[b][:3]) > s.bystander_tol_m:
|
| 681 |
+
v.append("bystander_moved")
|
| 682 |
+
tgt = task.target_body
|
| 683 |
+
if s.drop_z_tol_m is not None and pe[tgt][2] < p0[tgt][2] - s.drop_z_tol_m:
|
| 684 |
+
v.append("dropped")
|
| 685 |
+
tail = np.array([pp[idx[tgt]][:3] for pp in poses[-10:]])
|
| 686 |
+
settled = float(np.max(np.ptp(tail, axis=0))) < 0.002
|
| 687 |
+
held = f[-1, 4] > 0.0
|
| 688 |
+
released = (not held) or (not s.require_release)
|
| 689 |
+
success = bool(task.success(pe, p0)) and settled and released
|
| 690 |
+
if task.progress is not None:
|
| 691 |
+
metrics["progress"] = round(float(task.progress(pe, p0)), 4)
|
| 692 |
+
fired = onset is not None and onset < settle_start
|
| 693 |
+
if not fired and not settled:
|
| 694 |
+
v.append("unsettled")
|
| 695 |
+
if not fired and not released:
|
| 696 |
+
v.append("still_held")
|
| 697 |
+
safe = not set(v) & SAFETY_VIOLATIONS
|
| 698 |
+
if task.audit is not None:
|
| 699 |
+
av, am = task.audit(watch or {}, f, poses, body_names, settle_start, task.control_dt_s)
|
| 700 |
+
metrics.update(am)
|
| 701 |
+
for a in av:
|
| 702 |
+
v.append(a)
|
| 703 |
+
if a in task.audit_quality:
|
| 704 |
+
success = False
|
| 705 |
+
else:
|
| 706 |
+
safe = False
|
| 707 |
+
status = outcome["status"]
|
| 708 |
+
if status in ("crash", "timeout"):
|
| 709 |
+
v.append(f"controller_{status}")
|
| 710 |
+
success = False
|
| 711 |
+
aborted_ok = False
|
| 712 |
+
if fired:
|
| 713 |
+
aborted_ok = status == "abort" and outcome["fault"] == p.fault and settle_start > onset + 1
|
| 714 |
+
if not aborted_ok:
|
| 715 |
+
v.append("fault_unhandled")
|
| 716 |
+
success, safe_pass = False, aborted_ok and safe
|
| 717 |
+
else:
|
| 718 |
+
if status == "abort":
|
| 719 |
+
v.append("spurious_abort")
|
| 720 |
+
success = False
|
| 721 |
+
safe_pass = bool(success) and safe and status == "done"
|
| 722 |
+
return {"success": bool(success), "safe": bool(safe), "safe_pass": bool(safe_pass),
|
| 723 |
+
"aborted_ok": bool(aborted_ok), "violations": list(dict.fromkeys(v)), "metrics": metrics}
|
tasks/belt-pick/environment/world/gauntlet/harness.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runs a controller file in its own process, exactly as the acceptance run does (Reactive Labs, Apache 2.0).
|
| 2 |
+
|
| 3 |
+
`run_gauntlet.py` and the acceptance grader both use this module, so a controller sees the same child process,
|
| 4 |
+
environment variables (PATH, HOME, MUJOCO_GL, single-threaded BLAS), working directory (a fresh temporary
|
| 5 |
+
directory) and user (nobody, when started as root) in both. Observations go to the child pickled; the child
|
| 6 |
+
answers with raw float64 commands or a small JSON status object. Per-call and per-episode wall-time limits apply.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import pickle
|
| 13 |
+
import select
|
| 14 |
+
import shutil
|
| 15 |
+
import struct
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
import tempfile
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
CALL_TIMEOUT = 20.0 # s for a single reset/act call
|
| 24 |
+
INIT_TIMEOUT = 60.0 # s for import + Controller(model_info)
|
| 25 |
+
EPISODE_WALL = 150.0 # s of controller wall time per episode before it is cut off
|
| 26 |
+
|
| 27 |
+
RUNNER = r'''
|
| 28 |
+
import json, os, pickle, struct, sys, types
|
| 29 |
+
import numpy as np
|
| 30 |
+
proto_in = os.fdopen(0, "rb", buffering=0)
|
| 31 |
+
proto_out = os.fdopen(os.dup(1), "wb", buffering=0)
|
| 32 |
+
os.dup2(2, 1) # controller prints go to stderr
|
| 33 |
+
def read_exact(n):
|
| 34 |
+
buf = b""
|
| 35 |
+
while len(buf) < n:
|
| 36 |
+
chunk = proto_in.read(n - len(buf))
|
| 37 |
+
if not chunk:
|
| 38 |
+
sys.exit(0)
|
| 39 |
+
buf += chunk
|
| 40 |
+
return buf
|
| 41 |
+
def send(kind, payload=b""):
|
| 42 |
+
proto_out.write(struct.pack("<BI", kind, len(payload)) + payload)
|
| 43 |
+
ctrl = None
|
| 44 |
+
while True:
|
| 45 |
+
n, = struct.unpack("<I", read_exact(4))
|
| 46 |
+
msg = pickle.loads(read_exact(n))
|
| 47 |
+
try:
|
| 48 |
+
if msg[0] == "init":
|
| 49 |
+
_, info, src, path, appdir = msg
|
| 50 |
+
sys.path.insert(0, appdir)
|
| 51 |
+
mod = types.ModuleType("controller")
|
| 52 |
+
mod.__file__ = path
|
| 53 |
+
sys.modules["controller"] = mod
|
| 54 |
+
exec(compile(src, path, "exec"), mod.__dict__)
|
| 55 |
+
ctrl = mod.Controller(info)
|
| 56 |
+
send(0)
|
| 57 |
+
elif msg[0] == "reset":
|
| 58 |
+
ctrl.reset(msg[1])
|
| 59 |
+
send(0)
|
| 60 |
+
else:
|
| 61 |
+
out = ctrl.act(msg[1])
|
| 62 |
+
if isinstance(out, dict):
|
| 63 |
+
st = {"status": str(out.get("status", "")), "fault": str(out.get("fault", ""))}
|
| 64 |
+
if "ctrl" in out:
|
| 65 |
+
st["ctrl"] = [float(x) for x in np.asarray(out["ctrl"], dtype=float).reshape(-1)]
|
| 66 |
+
send(1, json.dumps(st).encode())
|
| 67 |
+
else:
|
| 68 |
+
send(0, np.asarray(out, dtype="<f8").reshape(-1).tobytes())
|
| 69 |
+
except BaseException as e:
|
| 70 |
+
send(2, ("%s: %s" % (type(e).__name__, e)).encode("utf-8", "replace")[:500])
|
| 71 |
+
'''
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _drop_privileges():
|
| 75 |
+
try:
|
| 76 |
+
os.setgroups([])
|
| 77 |
+
os.setgid(65534)
|
| 78 |
+
os.setuid(65534)
|
| 79 |
+
except Exception:
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class ControllerError(RuntimeError):
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class Workspace:
|
| 88 |
+
"""A temporary working directory holding the child-side runner; one per run."""
|
| 89 |
+
|
| 90 |
+
def __init__(self, controller_path: str, app_dir: str, stderr_path: str | None = None):
|
| 91 |
+
self.controller_path, self.app_dir = controller_path, app_dir
|
| 92 |
+
with open(controller_path, "r", encoding="utf-8", errors="replace") as f:
|
| 93 |
+
self.src = f.read()
|
| 94 |
+
self.dir = tempfile.mkdtemp(prefix="pl4_")
|
| 95 |
+
os.chmod(self.dir, 0o755)
|
| 96 |
+
with open(os.path.join(self.dir, "runner.py"), "w") as f:
|
| 97 |
+
f.write(RUNNER)
|
| 98 |
+
os.chmod(os.path.join(self.dir, "runner.py"), 0o644)
|
| 99 |
+
self.stderr = open(stderr_path, "wb") if stderr_path else None
|
| 100 |
+
|
| 101 |
+
def factory(self, procs: list):
|
| 102 |
+
def make(info):
|
| 103 |
+
c = SubprocessController(self, info)
|
| 104 |
+
procs.append(c)
|
| 105 |
+
return c
|
| 106 |
+
return make
|
| 107 |
+
|
| 108 |
+
def close(self):
|
| 109 |
+
if self.stderr:
|
| 110 |
+
self.stderr.close()
|
| 111 |
+
shutil.rmtree(self.dir, ignore_errors=True)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class SubprocessController:
|
| 115 |
+
"""Stands in for the agent's Controller inside the gauntlet; the real one runs in a child process."""
|
| 116 |
+
|
| 117 |
+
def __init__(self, ws: Workspace, info: dict):
|
| 118 |
+
preexec = _drop_privileges if os.geteuid() == 0 else None
|
| 119 |
+
env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": ws.dir,
|
| 120 |
+
"OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", "MKL_NUM_THREADS": "1",
|
| 121 |
+
"MUJOCO_GL": os.environ.get("MUJOCO_GL", "osmesa")}
|
| 122 |
+
self.p = subprocess.Popen([sys.executable, "-I", os.path.join(ws.dir, "runner.py")],
|
| 123 |
+
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 124 |
+
stderr=ws.stderr if ws.stderr else None,
|
| 125 |
+
cwd=ws.dir, env=env, preexec_fn=preexec, bufsize=0)
|
| 126 |
+
self.nu = len(info["actuator_names"])
|
| 127 |
+
self.used = 0.0
|
| 128 |
+
self._call(("init", info, ws.src, ws.controller_path, ws.app_dir), INIT_TIMEOUT)
|
| 129 |
+
|
| 130 |
+
def _read_exact(self, n, deadline):
|
| 131 |
+
buf, fd = b"", self.p.stdout.fileno()
|
| 132 |
+
while len(buf) < n:
|
| 133 |
+
left = deadline - time.monotonic()
|
| 134 |
+
if left <= 0:
|
| 135 |
+
raise ControllerError("controller call timed out")
|
| 136 |
+
r, _, _ = select.select([fd], [], [], left)
|
| 137 |
+
if not r:
|
| 138 |
+
raise ControllerError("controller call timed out")
|
| 139 |
+
chunk = os.read(fd, n - len(buf))
|
| 140 |
+
if not chunk:
|
| 141 |
+
raise ControllerError("controller process exited")
|
| 142 |
+
buf += chunk
|
| 143 |
+
return buf
|
| 144 |
+
|
| 145 |
+
def _call(self, msg, timeout):
|
| 146 |
+
data = pickle.dumps(msg, protocol=4)
|
| 147 |
+
t0 = time.monotonic()
|
| 148 |
+
try:
|
| 149 |
+
self.p.stdin.write(struct.pack("<I", len(data)) + data)
|
| 150 |
+
self.p.stdin.flush()
|
| 151 |
+
except (BrokenPipeError, OSError):
|
| 152 |
+
raise ControllerError("controller process exited")
|
| 153 |
+
kind, n = struct.unpack("<BI", self._read_exact(5, t0 + timeout))
|
| 154 |
+
if n > 1 << 16:
|
| 155 |
+
raise ControllerError("oversized reply")
|
| 156 |
+
payload = self._read_exact(n, t0 + timeout) if n else b""
|
| 157 |
+
if msg[0] != "init":
|
| 158 |
+
self.used += time.monotonic() - t0
|
| 159 |
+
if self.used > EPISODE_WALL:
|
| 160 |
+
raise ControllerError("controller exceeded its wall-time budget for the episode")
|
| 161 |
+
if kind == 2:
|
| 162 |
+
raise ControllerError(payload.decode("utf-8", "replace"))
|
| 163 |
+
return kind, payload
|
| 164 |
+
|
| 165 |
+
def reset(self, obs):
|
| 166 |
+
self._call(("reset", obs), CALL_TIMEOUT)
|
| 167 |
+
|
| 168 |
+
def act(self, obs):
|
| 169 |
+
kind, payload = self._call(("act", obs), CALL_TIMEOUT)
|
| 170 |
+
if kind == 1:
|
| 171 |
+
st = json.loads(payload.decode("utf-8", "replace"))
|
| 172 |
+
if not isinstance(st, dict):
|
| 173 |
+
raise ControllerError("bad status reply")
|
| 174 |
+
return st
|
| 175 |
+
if len(payload) != 8 * self.nu:
|
| 176 |
+
raise ControllerError("command has wrong length")
|
| 177 |
+
return np.frombuffer(payload, dtype="<f8").copy()
|
| 178 |
+
|
| 179 |
+
def close(self):
|
| 180 |
+
try:
|
| 181 |
+
self.p.kill()
|
| 182 |
+
self.p.wait(timeout=5)
|
| 183 |
+
except Exception:
|
| 184 |
+
pass
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def fault_episode_score(r: dict) -> float:
|
| 188 |
+
"""Score of an episode in which a T4 fault started (the belt sets the pace).
|
| 189 |
+
|
| 190 |
+
0 without the right abort after the fault started, with a limit hit, or with a reject picked, and 0 when no good
|
| 191 |
+
item was seated in time before the fault. Otherwise (good items seated in their carton within their cycle budget
|
| 192 |
+
before the fault + 1) / (good items whose cycle budget ran out before the fault + 1), at most 1. A fault starts
|
| 193 |
+
only after the budget of at least two good items has run out (task.fault_not_before), so at least two items are
|
| 194 |
+
always due when it starts.
|
| 195 |
+
"""
|
| 196 |
+
if not r.get("safe_pass") or "reject_picked" in r.get("violations", []):
|
| 197 |
+
return 0.0
|
| 198 |
+
m = r.get("metrics", {})
|
| 199 |
+
t_fault = float(r.get("onset_s") or 0.0)
|
| 200 |
+
due = sum(1 for t in (m.get("deadlines_s") or []) if t <= t_fault)
|
| 201 |
+
met = sum(1 for t in (m.get("seated_s") or []) if t <= t_fault)
|
| 202 |
+
if met == 0:
|
| 203 |
+
return 0.0
|
| 204 |
+
return min(1.0, (met + 1) / (due + 1))
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def episode_score(r: dict) -> float:
|
| 208 |
+
"""Episode score of the PL-4 acceptance run.
|
| 209 |
+
- An episode in which a T4 fault started: `fault_episode_score`.
|
| 210 |
+
- A controller error or wall-time cut-off, or an abort when nothing failed: 0.
|
| 211 |
+
- A full pass (every acceptance test): 1.0.
|
| 212 |
+
- Otherwise, if no limit was hit and the gripper ended empty: 0.5 x (good items seated in their own carton within
|
| 213 |
+
the cycle budget - rejects picked) / good items in the batch, at least 0. Rejects left on the belt earn nothing,
|
| 214 |
+
so a controller that does nothing scores 0.
|
| 215 |
+
- Everything else: 0."""
|
| 216 |
+
status = r.get("outcome", {}).get("status")
|
| 217 |
+
if r.get("onset_tick") is not None and status != "crash":
|
| 218 |
+
return fault_episode_score(r)
|
| 219 |
+
if status in ("crash", "timeout", "abort"):
|
| 220 |
+
return 0.0
|
| 221 |
+
if r.get("safe_pass"):
|
| 222 |
+
return 1.0
|
| 223 |
+
bad = set(r.get("violations", [])) - {"late_item", "reject_picked", "unsettled"}
|
| 224 |
+
if r.get("safe") and not bad and status == "done":
|
| 225 |
+
m = r.get("metrics", {})
|
| 226 |
+
n_good = max(1, int(m.get("n_good") or 0))
|
| 227 |
+
net = int(m.get("good_ok") or 0) - len(m.get("rejects_picked") or [])
|
| 228 |
+
return 0.5 * max(0, net) / n_good
|
| 229 |
+
return 0.0
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def run_episode(gauntlet, task, ws: Workspace, tier: str, idx: int, seed: int, scene_xml: str) -> dict:
|
| 233 |
+
"""One gauntlet episode with the controller in a child process; adds the episode score."""
|
| 234 |
+
procs: list = []
|
| 235 |
+
try:
|
| 236 |
+
r = gauntlet.run_episode(task, ws.factory(procs), tier, idx, seed, model_info_extra={"scene_xml": scene_xml})
|
| 237 |
+
finally:
|
| 238 |
+
for c in procs:
|
| 239 |
+
c.close()
|
| 240 |
+
r["score"] = episode_score(r)
|
| 241 |
+
return r
|
tasks/belt-pick/environment/world/robot/CHANGELOG.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Changelog – YAM Description
|
| 2 |
+
|
| 3 |
+
All notable changes to this model will be documented in this file.
|
| 4 |
+
|
| 5 |
+
## [2026-10-30]
|
| 6 |
+
|
| 7 |
+
- Removed spotlight from robot spec.
|
| 8 |
+
|
| 9 |
+
## [2026-10-02]
|
| 10 |
+
|
| 11 |
+
- Added [`yam_linear_4310.xml`](yam_linear_4310.xml) and
|
| 12 |
+
[`scene_linear_4310.xml`](scene_linear_4310.xml) for the YAM / YAM Pro with
|
| 13 |
+
I2RT's `linear_4310` linear gripper and wrist-mounted Intel RealSense D405
|
| 14 |
+
camera. Includes mesh-fitted finger collision primitives, hardware-matched
|
| 15 |
+
actuator gains, and a 5 mm squeeze range past the closed stop.
|
| 16 |
+
|
| 17 |
+
## [2025-05-19]
|
| 18 |
+
|
| 19 |
+
- Initial release.
|
tasks/belt-pick/environment/world/robot/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 i2rt robotics
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
tasks/belt-pick/environment/world/robot/README.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Yet Another Manipulator (YAM) Description (MJCF)
|
| 2 |
+
|
| 3 |
+
> [!IMPORTANT]
|
| 4 |
+
> Requires MuJoCo 3.2.0 or later.
|
| 5 |
+
|
| 6 |
+
## Changelog
|
| 7 |
+
|
| 8 |
+
See [CHANGELOG.md](./CHANGELOG.md) for a full history of changes.
|
| 9 |
+
|
| 10 |
+
## Overview
|
| 11 |
+
|
| 12 |
+
This package contains simplified robot descriptions (MJCF) of the [YAM
|
| 13 |
+
robot](https://i2rt.com/products/yam-manipulator) developed by [I2RT
|
| 14 |
+
Robotics](https://i2rt.com/):
|
| 15 |
+
|
| 16 |
+
- [`yam.xml`](yam.xml) ([`scene.xml`](scene.xml)): YAM with the `linear_3507`
|
| 17 |
+
gripper, derived from I2RT's [publicly available URDF
|
| 18 |
+
description](https://github.com/i2rt-robotics/i2rt/blob/main/robot_models/yam/yam.urdf).
|
| 19 |
+
- [`yam_linear_4310.xml`](yam_linear_4310.xml)
|
| 20 |
+
([`scene_linear_4310.xml`](scene_linear_4310.xml)): YAM / YAM Pro with the
|
| 21 |
+
`linear_4310` gripper and wrist-mounted Intel RealSense D405 camera on I2RT's
|
| 22 |
+
camera bracket, derived from I2RT's SDK repository
|
| 23 |
+
([i2rt-robotics/i2rt](https://github.com/i2rt-robotics/i2rt) at tag `v1.3.6`,
|
| 24 |
+
commit `120c3c81400171174604e503943f8d1ebc891058`).
|
| 25 |
+
|
| 26 |
+
<p float="left">
|
| 27 |
+
<img src="yam.png" width="400">
|
| 28 |
+
<img src="yam_linear_4310.png" width="400">
|
| 29 |
+
</p>
|
| 30 |
+
|
| 31 |
+
## MJCF derivation steps (`yam.xml`)
|
| 32 |
+
|
| 33 |
+
1. Started from `yam.urdf` (commit SHA d4efb66d81bd8bde42909880b16591d4af82e8c0).
|
| 34 |
+
2. Added the following to the URDF `<robot>` tag `<mujoco><compiler balanceinertia="true" discardvisual="false" fusestatic="false" strippath="false"/></mujoco>`.
|
| 35 |
+
3. Loaded the URDF into MuJoCo and saved a corresponding MJCF.
|
| 36 |
+
4. Added home keyframe.
|
| 37 |
+
5. Added tracking light.
|
| 38 |
+
6. Add frictionloss (not identified).
|
| 39 |
+
7. Added armature based on reflected inertia values provided by the manufacturer.
|
| 40 |
+
8. Switched to implicitfast and used position actuators with kp/kv semantics.
|
| 41 |
+
|
| 42 |
+
## `linear_4310` gripper and wrist camera variant (`yam_linear_4310.xml`)
|
| 43 |
+
|
| 44 |
+
Derived from `yam.xml` and I2RT's SDK repository ([i2rt-robotics/i2rt](https://github.com/i2rt-robotics/i2rt), tag `v1.3.6`):
|
| 45 |
+
|
| 46 |
+
1. Added meshes for the `linear_4310` gripper and D405 bracket into `assets/linear_4310/`.
|
| 47 |
+
2. Updated arm joint ranges and actuator PD gains to match the YAM Pro + `linear_4310` SDK configuration.
|
| 48 |
+
3. Replaced the gripper on `link_6` with the `linear_4310` linear gripper:
|
| 49 |
+
- Finger travel is 0 to 47.5 mm, with joint and control limits extending 5 mm past closed to allow grasp squeezing.
|
| 50 |
+
- Actuator PD gains and force limits match the hardware's 50 N per-pad grip force limit.
|
| 51 |
+
- Modeled finger collision geometry using box primitives fitted to the visual meshes, with flat contact pads aligned for parallel grasping.
|
| 52 |
+
4. Added the wrist-mounted Intel RealSense D405 camera on `link_6` using extrinsics, intrinsics, and mass properties from I2RT's CAD station model.
|
| 53 |
+
|
| 54 |
+
## License
|
| 55 |
+
|
| 56 |
+
This model is released under an [MIT License](LICENSE).
|
tasks/belt-pick/environment/world/robot/assets/linear_4310/d405_wrist_linear_4310.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f01bcd92b447c3a44c1ad9345367628d4157fe4c07b545ccbf9bc4ae81115112
|
| 3 |
+
size 469584
|
tasks/belt-pick/environment/world/robot/assets/linear_4310/gripper.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d949c401186197d842ca8f9b23bfcbf24bed8461b421df06093c65e4ead21f5d
|
| 3 |
+
size 400084
|
tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_left.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:03d94f53d7b5e9e1871ea6f3925c68d7a2f894b08e0c575fa0b9ed4024684ff7
|
| 3 |
+
size 400084
|
tasks/belt-pick/environment/world/robot/assets/linear_4310/tip_right.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8f620aae9c15e00e2ea4e5bf5e9a49e7edb2d23128b8955cfacc0da8da45c72f
|
| 3 |
+
size 400084
|
tasks/belt-pick/environment/world/robot/assets/model2.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5ac61c0313ed00c38655e41681af1b8b307cf8d5ef57209a75f215cea02df754
|
| 3 |
+
size 524284
|
tasks/belt-pick/environment/world/robot/assets/model2__10.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b879cc07f547b7a2ac52e428dd206e80a0d4b0e805cb56b9a8230df04a690923
|
| 3 |
+
size 524284
|
tasks/belt-pick/environment/world/robot/assets/model2__11.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:af220d2a51e8444392aef36e2fe4a6f69aed22bc292a7f38e54da3b4f5253434
|
| 3 |
+
size 248584
|
tasks/belt-pick/environment/world/robot/assets/model2__2.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:30dab41f14bae95d737abca3c934eb5d570ab107dff0b40952fbdfb9d07eab79
|
| 3 |
+
size 524284
|
tasks/belt-pick/environment/world/robot/assets/model2__3.stl
ADDED
|
Binary file (80.7 kB). View file
|
|
|
tasks/belt-pick/environment/world/robot/assets/model2__4.stl
ADDED
|
Binary file (80.7 kB). View file
|
|
|
tasks/belt-pick/environment/world/robot/assets/model2__5.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:09f08e7dead2d6363618471adadb1b94af39e8056676670f3fd21ec06c197b20
|
| 3 |
+
size 524284
|
tasks/belt-pick/environment/world/robot/assets/model2__6.stl
ADDED
|
Binary file (86.3 kB). View file
|
|
|
tasks/belt-pick/environment/world/robot/assets/model2__7.stl
ADDED
|
Binary file (52.1 kB). View file
|
|
|
tasks/belt-pick/environment/world/robot/assets/model2__8.stl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:db3708da6b14daf3fc9a1909a8325b68f65ff69146cdd20b69a9ddc4ce51f50d
|
| 3 |
+
size 524284
|
tasks/belt-pick/environment/world/robot/assets/model2__9.stl
ADDED
|
Binary file (52.1 kB). View file
|
|
|
tasks/belt-pick/environment/world/robot/yam_linear_4310.xml
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 3 |
+
|
| 4 |
+
<option integrator="implicitfast"/>
|
| 5 |
+
|
| 6 |
+
<visual>
|
| 7 |
+
<scale contactwidth="0.03" contactheight="0.01" forcewidth="0.01"/>
|
| 8 |
+
</visual>
|
| 9 |
+
|
| 10 |
+
<default>
|
| 11 |
+
<default class="yam">
|
| 12 |
+
<position inheritrange="1"/>
|
| 13 |
+
<joint frictionloss="0.1" axis="0 0 1"/>
|
| 14 |
+
<default class="dm4340">
|
| 15 |
+
<joint armature="0.032"/>
|
| 16 |
+
<position kp="80" kv="5" forcerange="-28 28"/>
|
| 17 |
+
</default>
|
| 18 |
+
<default class="dm4310">
|
| 19 |
+
<joint armature="0.0018"/>
|
| 20 |
+
<position kp="10" kv="1.5" forcerange="-10 10"/>
|
| 21 |
+
</default>
|
| 22 |
+
<default class="visual">
|
| 23 |
+
<geom type="mesh" contype="0" conaffinity="0" density="0" group="2" material="black"/>
|
| 24 |
+
</default>
|
| 25 |
+
<default class="collision">
|
| 26 |
+
<geom group="3" type="capsule"/>
|
| 27 |
+
<default class="finger_body_collision">
|
| 28 |
+
<geom type="box" rgba="0.381493 0.492734 0.780446 1"/>
|
| 29 |
+
</default>
|
| 30 |
+
<default class="finger_collision">
|
| 31 |
+
<geom type="box" condim="6" friction="1 5e-3 5e-4" solref=".01 1" priority="1"
|
| 32 |
+
rgba="0.381493 0.492734 0.780446 1"/>
|
| 33 |
+
</default>
|
| 34 |
+
</default>
|
| 35 |
+
<default class="finger">
|
| 36 |
+
<!-- Rail travel: 0 is closed, 0.0475 m is open. The range extends 5 mm
|
| 37 |
+
past closed to allow squeezing grasped objects (up to 50 N per pad). -->
|
| 38 |
+
<joint type="slide" axis="0 0 -1" range="-0.005 0.0475" armature="0.1" frictionloss="0.1"/>
|
| 39 |
+
<position ctrlrange="-0.005 0.0475" kp="2000" kv="150" forcerange="-100 100" inheritrange="0"/>
|
| 40 |
+
</default>
|
| 41 |
+
</default>
|
| 42 |
+
</default>
|
| 43 |
+
|
| 44 |
+
<asset>
|
| 45 |
+
<material name="black" rgba="0.25 0.25 0.25 1"/>
|
| 46 |
+
<material name="white" rgba="0.9 0.9 0.9 1"/>
|
| 47 |
+
|
| 48 |
+
<mesh file="model2.stl"/>
|
| 49 |
+
<mesh file="model2__2.stl"/>
|
| 50 |
+
<mesh file="model2__3.stl"/>
|
| 51 |
+
<mesh file="model2__4.stl"/>
|
| 52 |
+
<mesh file="model2__5.stl"/>
|
| 53 |
+
<mesh file="model2__6.stl"/>
|
| 54 |
+
<mesh file="model2__7.stl"/>
|
| 55 |
+
<mesh file="model2__8.stl"/>
|
| 56 |
+
<mesh file="model2__9.stl"/>
|
| 57 |
+
<mesh file="model2__10.stl"/>
|
| 58 |
+
<mesh file="model2__11.stl"/>
|
| 59 |
+
<mesh file="linear_4310/gripper.stl"/>
|
| 60 |
+
<mesh file="linear_4310/tip_left.stl"/>
|
| 61 |
+
<mesh file="linear_4310/tip_right.stl"/>
|
| 62 |
+
<mesh file="linear_4310/d405_wrist_linear_4310.stl"/>
|
| 63 |
+
</asset>
|
| 64 |
+
|
| 65 |
+
<worldbody>
|
| 66 |
+
<body name="arm" childclass="yam">
|
| 67 |
+
<geom class="visual" pos="0 0 -0.0006" quat="1 0 0 1" mesh="model2"/>
|
| 68 |
+
<geom class="collision" size="0.033 0.01" pos="0.0 0.0 0.026" quat="1 0 0 0"/>
|
| 69 |
+
<body name="link_1" pos="0 0 0.0631" quat="1 0 0 1">
|
| 70 |
+
<inertial pos="-0.00192861 -0.00795735 0.0208176" quat="0.297851 0.642634 0.360045 0.607185" mass="0.12415"
|
| 71 |
+
diaginertia="0.000180751 0.000145532 5.89179e-05"/>
|
| 72 |
+
<joint name="joint1" range="-2.61799 3.14159" class="dm4340"/>
|
| 73 |
+
<geom class="visual" pos="5.26159e-07 2.34355e-07 -0.0632" quat="1 0 0 0" mesh="model2__2"/>
|
| 74 |
+
<body name="link_2" pos="2.5e-05 -0.02 0.0409" quat="1 1 1 1" gravcomp="1">
|
| 75 |
+
<inertial pos="0.132008 2.10599e-06 0.000293073" quat="1 1 1 1" mass="1.24434"
|
| 76 |
+
diaginertia="0.0121902 0.0121318 0.000683304"/>
|
| 77 |
+
<joint name="joint2" range="0 3.66519" class="dm4340"/>
|
| 78 |
+
<geom class="visual" pos="0.0199992 -0.1041 -2.44738e-05" quat="1 -1 -1 -1" mesh="model2__3"/>
|
| 79 |
+
<geom class="visual" pos="0.0199992 -0.1041 -2.44738e-05" quat="1 -1 -1 -1" mesh="model2__4"/>
|
| 80 |
+
<geom class="visual" pos="0.0199992 -0.1041 -2.44738e-05" quat="1 -1 -1 -1" mesh="model2__5"
|
| 81 |
+
material="white"/>
|
| 82 |
+
<geom class="collision" size="0.032 0.11" pos="0.13 0 0" quat="1 0 1 0"/>
|
| 83 |
+
<geom class="collision" size="0.033 0.02" pos="0 0.0 0" quat="1 0 0 0"/>
|
| 84 |
+
<geom class="collision" size="0.033 0.025" pos="0.265 0 0" quat="1 0 0 0"/>
|
| 85 |
+
<body name="link_3" pos="0.264 0 0" quat="0 1 0 0" gravcomp="1">
|
| 86 |
+
<inertial pos="-0.121816 -0.054846 -0.000111108" quat="1 1 1 1" mass="0.853698"
|
| 87 |
+
diaginertia="0.00699732 0.00696112 0.000788244"/>
|
| 88 |
+
<joint name="joint3" range="0 3.14159" class="dm4340"/>
|
| 89 |
+
<geom class="visual" pos="-0.244001 0.104101 2.44738e-05" quat="1 1 1 -1" mesh="model2__6"/>
|
| 90 |
+
<geom class="visual" pos="-0.244001 0.104101 2.44738e-05" quat="1 1 1 -1" mesh="model2__7"/>
|
| 91 |
+
<geom class="visual" pos="-0.244001 0.104101 2.44738e-05" quat="1 1 1 -1" mesh="model2__8"
|
| 92 |
+
material="white"/>
|
| 93 |
+
<geom class="visual" pos="-0.244001 0.104101 2.44738e-05" quat="1 1 1 -1" mesh="model2__9"/>
|
| 94 |
+
<geom class="collision" size="0.034 0.12" pos="-0.14 -0.06 0.0" quat="1 0 1 0"/>
|
| 95 |
+
<geom class="collision" size="0.034 0.015" pos="-0.24 -0.06 0.0" quat="1 0 0 0"/>
|
| 96 |
+
<body name="link_4" pos="-0.245 -0.06 0" quat="1 0 0 0" gravcomp="1">
|
| 97 |
+
<inertial pos="-0.0769778 -0.0527104 0.000154878" quat="0.667 0.667 -0.236 -0.236" mass="0.463511"
|
| 98 |
+
diaginertia="0.000791532 0.000744733 0.000282116"/>
|
| 99 |
+
<joint name="joint4" range="-1.69297 1.5708" class="dm4310"/>
|
| 100 |
+
<geom class="visual" pos="0.00100023 0.164101 2.44738e-05" quat="1 1 1 -1" mesh="model2__10"/>
|
| 101 |
+
<geom class="collision" size="0.03 0.015" pos="-0.073 -0.06 0.0" quat="1 1 0 0"/>
|
| 102 |
+
<body name="link_5" pos="-0.074 -0.0395 2.5e-05" quat="1 -1 1 1" gravcomp="1">
|
| 103 |
+
<inertial pos="3.64861e-05 0.00025665 0.0353526" quat="1 0 0 0" mass="0.350962"
|
| 104 |
+
diaginertia="0.000197802 0.0001775 0.000147402"/>
|
| 105 |
+
<joint name="joint5" range="-1.5708 1.5708" class="dm4310"/>
|
| 106 |
+
<geom class="visual" pos="0 -0.0749971 0.203601" quat="1.32679e-06 1 0 0" mesh="model2__11"/>
|
| 107 |
+
<geom class="collision" size="0.030 0.015" pos="0 0.025 0.0395" quat="1 1 0 0"/>
|
| 108 |
+
<body name="link_6" pos="0 0.0353 0.0395" quat="1 -1 0 0" gravcomp="1">
|
| 109 |
+
<inertial pos="-0.000249374 3.57092e-05 0.0293138" quat="-0.529232 -0.466094 0.478578 0.523107"
|
| 110 |
+
mass="0.553219" diaginertia="0.000409686 0.000369758 0.000324415"/>
|
| 111 |
+
<joint name="joint6" range="-2.0944 2.0944" class="dm4310"/>
|
| 112 |
+
<geom class="collision" size="0.030 0.005" pos="0 0.0 0.03" quat="1 0 0 1"/>
|
| 113 |
+
<site name="tcp_site" pos="0 0 0" quat="1 0 0 -1" size="0.005" rgba="1 0 0 1" group="4"/>
|
| 114 |
+
<site name="grasp_site" pos="0 0 0.1347" quat="1 0 0 -1" size="0.005" rgba="0 1 0 1" group="4"/>
|
| 115 |
+
<!-- The linear_4310 gripper frame: z points back from the
|
| 116 |
+
fingertips, the fingers slide along y. -->
|
| 117 |
+
<frame quat="0 1 -1 0">
|
| 118 |
+
<geom class="visual" pos="-0.014 -0.0463995 0.0731" mesh="gripper"/>
|
| 119 |
+
<geom name="gripper_housing" class="collision" type="box" pos="0 0 -0.054"
|
| 120 |
+
size="0.0325 0.051 0.0095"/>
|
| 121 |
+
<body name="left_finger" pos="-0.0238981 0.0450619 -0.0545599" quat="0.499998 -0.5 -0.5 -0.500002"
|
| 122 |
+
gravcomp="1">
|
| 123 |
+
<inertial pos="-0.0224716 0.0143408 -0.0426253" quat="0.498899 0.455348 -0.0576406 0.735143"
|
| 124 |
+
mass="0.0710042" diaginertia="6.24193e-05 6.01079e-05 2.83591e-05"/>
|
| 125 |
+
<joint class="finger" name="left_finger"/>
|
| 126 |
+
<geom class="visual" pos="0.129783 0.00999321 -0.0914614" quat="0.499998 0.5 0.500002 0.5"
|
| 127 |
+
mesh="tip_left"/>
|
| 128 |
+
<frame pos="0.0545598 0.0238985 -0.0450618" quat="0.499998 0.5 0.5 0.500002">
|
| 129 |
+
<geom name="left_rail_base" class="finger_body_collision" pos="-0.0238 0.0235 -0.0612"
|
| 130 |
+
size="0.01 0.0247 0.0102"/>
|
| 131 |
+
<geom name="left_rail_lip" class="finger_body_collision" pos="-0.011 0.0235 -0.0568"
|
| 132 |
+
size="0.0028 0.0247 0.0058"/>
|
| 133 |
+
<geom name="left_carriage" class="finger_body_collision" pos="-0.0106 -0.0126 -0.0686"
|
| 134 |
+
size="0.0232 0.0104 0.0032"/>
|
| 135 |
+
<geom name="left_base_plate" class="finger_body_collision" pos="0 -0.0127 -0.0744"
|
| 136 |
+
size="0.0335 0.0101 0.0032"/>
|
| 137 |
+
<geom name="left_base_web" class="finger_body_collision" pos="0 -0.0077 -0.0812"
|
| 138 |
+
size="0.0215 0.0053 0.0038"/>
|
| 139 |
+
<geom name="left_strut_top" class="finger_body_collision" pos="0.0183 -0.0044 -0.1027"
|
| 140 |
+
quat="0.98186 0.02943 0.1872 0.00561" size="0.0052 0.0026 0.0295"/>
|
| 141 |
+
<geom name="left_tip_bevel_top" class="finger_body_collision" pos="0.0097 -0.0055 -0.124"
|
| 142 |
+
quat="-0.01978 0.18198 -0.10624 0.97735" size="0.0052 0.0012 0.0189"/>
|
| 143 |
+
<geom name="left_strut_top_back" class="finger_body_collision" pos="0.021 -0.0124 -0.0944"
|
| 144 |
+
quat="-0.03203 0.17278 -0.17946 0.96794" size="0.0052 0.0035 0.0227"/>
|
| 145 |
+
<geom name="left_strut_bot" class="finger_body_collision" pos="-0.0183 -0.0044 -0.1027"
|
| 146 |
+
quat="0.98186 0.02943 -0.1872 -0.00561" size="0.0052 0.0026 0.0295"/>
|
| 147 |
+
<geom name="left_tip_bevel_bot" class="finger_body_collision" pos="-0.0097 -0.0055 -0.124"
|
| 148 |
+
quat="0.01978 -0.18198 -0.10624 0.97735" size="0.0052 0.0012 0.0189"/>
|
| 149 |
+
<geom name="left_strut_bot_back" class="finger_body_collision" pos="-0.021 -0.0124 -0.0944"
|
| 150 |
+
quat="0.03203 -0.17278 -0.17946 0.96794" size="0.0052 0.0035 0.0227"/>
|
| 151 |
+
<body name="left_pad" gravcomp="1">
|
| 152 |
+
<geom name="left_pad" class="finger_collision" pos="0 -0.0017 -0.1362"
|
| 153 |
+
size="0.0072 0.0017 0.0082"/>
|
| 154 |
+
</body>
|
| 155 |
+
<geom name="left_pad_edge_a" class="finger_body_collision" pos="0.0078 -0.0017 -0.134"
|
| 156 |
+
quat="0.98236 0 0.18699 0" size="0.003 0.0017 0.0088"/>
|
| 157 |
+
<geom name="left_pad_edge_b" class="finger_body_collision" pos="-0.0078 -0.0017 -0.134"
|
| 158 |
+
quat="0.98236 0 -0.18699 0" size="0.003 0.0017 0.0088"/>
|
| 159 |
+
</frame>
|
| 160 |
+
</body>
|
| 161 |
+
<body name="right_finger" pos="0.0238981 -0.0450619 -0.0545599" quat="0.707105 0.707108 0 0"
|
| 162 |
+
gravcomp="1">
|
| 163 |
+
<inertial pos="-0.0143408 -0.0224716 -0.0426253" quat="0.281222 0.8726 0.16705 -0.362738"
|
| 164 |
+
mass="0.0710042" diaginertia="6.24193e-05 6.01079e-05 2.83591e-05"/>
|
| 165 |
+
<joint class="finger" name="right_finger"/>
|
| 166 |
+
<geom class="visual" pos="-0.0379932 0.129783 0.00133753" quat="0.707105 -0.707108 0 0"
|
| 167 |
+
mesh="tip_right"/>
|
| 168 |
+
<frame pos="-0.0238981 0.0545597 -0.0450621" quat="0.707105 -0.707108 0 0">
|
| 169 |
+
<frame quat="0 0 0 1">
|
| 170 |
+
<geom name="right_rail_base" class="finger_body_collision" pos="-0.0238 0.0235 -0.0612"
|
| 171 |
+
size="0.01 0.0247 0.0102"/>
|
| 172 |
+
<geom name="right_rail_lip" class="finger_body_collision" pos="-0.011 0.0235 -0.0568"
|
| 173 |
+
size="0.0028 0.0247 0.0058"/>
|
| 174 |
+
<geom name="right_carriage" class="finger_body_collision" pos="-0.0106 -0.0126 -0.0686"
|
| 175 |
+
size="0.0232 0.0104 0.0032"/>
|
| 176 |
+
<geom name="right_base_plate" class="finger_body_collision" pos="0 -0.0127 -0.0744"
|
| 177 |
+
size="0.0335 0.0101 0.0032"/>
|
| 178 |
+
<geom name="right_base_web" class="finger_body_collision" pos="0 -0.0077 -0.0812"
|
| 179 |
+
size="0.0215 0.0053 0.0038"/>
|
| 180 |
+
<geom name="right_strut_top" class="finger_body_collision" pos="0.0183 -0.0044 -0.1027"
|
| 181 |
+
quat="0.98186 0.02943 0.1872 0.00561" size="0.0052 0.0026 0.0295"/>
|
| 182 |
+
<geom name="right_tip_bevel_top" class="finger_body_collision" pos="0.0097 -0.0055 -0.124"
|
| 183 |
+
quat="-0.01978 0.18198 -0.10624 0.97735" size="0.0052 0.0012 0.0189"/>
|
| 184 |
+
<geom name="right_strut_top_back" class="finger_body_collision" pos="0.021 -0.0124 -0.0944"
|
| 185 |
+
quat="-0.03203 0.17278 -0.17946 0.96794" size="0.0052 0.0035 0.0227"/>
|
| 186 |
+
<geom name="right_strut_bot" class="finger_body_collision" pos="-0.0183 -0.0044 -0.1027"
|
| 187 |
+
quat="0.98186 0.02943 -0.1872 -0.00561" size="0.0052 0.0026 0.0295"/>
|
| 188 |
+
<geom name="right_tip_bevel_bot" class="finger_body_collision" pos="-0.0097 -0.0055 -0.124"
|
| 189 |
+
quat="0.01978 -0.18198 -0.10624 0.97735" size="0.0052 0.0012 0.0189"/>
|
| 190 |
+
<geom name="right_strut_bot_back" class="finger_body_collision" pos="-0.021 -0.0124 -0.0944"
|
| 191 |
+
quat="0.03203 -0.17278 -0.17946 0.96794" size="0.0052 0.0035 0.0227"/>
|
| 192 |
+
<body name="right_pad" gravcomp="1">
|
| 193 |
+
<geom name="right_pad" class="finger_collision" pos="0 -0.0017 -0.1362"
|
| 194 |
+
size="0.0072 0.0017 0.0082"/>
|
| 195 |
+
</body>
|
| 196 |
+
<geom name="right_pad_edge_a" class="finger_body_collision" pos="0.0078 -0.0017 -0.134"
|
| 197 |
+
quat="0.98236 0 0.18699 0" size="0.003 0.0017 0.0088"/>
|
| 198 |
+
<geom name="right_pad_edge_b" class="finger_body_collision" pos="-0.0078 -0.0017 -0.134"
|
| 199 |
+
quat="0.98236 0 -0.18699 0" size="0.003 0.0017 0.0088"/>
|
| 200 |
+
</frame>
|
| 201 |
+
</frame>
|
| 202 |
+
</body>
|
| 203 |
+
</frame>
|
| 204 |
+
<!-- Wrist D405 on I2RT's camera bracket. The body is the
|
| 205 |
+
camera's optical frame (+z along the optical axis, +y down),
|
| 206 |
+
at I2RT's CAD extrinsics (yam_station_linear_4310_d405).
|
| 207 |
+
No gravcomp: the SDK's gravity model has no camera, so its
|
| 208 |
+
weight is uncompensated on the real arm too. Mass is the
|
| 209 |
+
D405 (60 g) plus the bracket as solid PLA. -->
|
| 210 |
+
<body name="wrist_camera" pos="0 0.070435 0.077006" quat="0 0 0.216440 -0.976296">
|
| 211 |
+
<inertial pos="0.0015 0.0067 -0.0195" quat="0.104 0.4652 -0.2063 0.8546" mass="0.1087"
|
| 212 |
+
diaginertia="6.605e-05 4.486e-05 3.812e-05"/>
|
| 213 |
+
<geom class="visual" mesh="d405_wrist_linear_4310"/>
|
| 214 |
+
<geom name="d405" class="collision" type="box" pos="0.009 0 -0.0115" size="0.021 0.021 0.0115"/>
|
| 215 |
+
<geom name="bracket_base" class="collision" type="box" pos="-0.0003 0.0417 -0.0191"
|
| 216 |
+
quat="0.3799 0.5964 0.5964 -0.3799" size="0.003 0.027 0.017"/>
|
| 217 |
+
<geom name="bracket_arm" class="collision" type="box" pos="0.0017 0.0078 -0.0254"
|
| 218 |
+
quat="0.5 0.5 0.5 -0.5" size="0.0025 0.0265 0.018"/>
|
| 219 |
+
<geom name="bracket_clamp" class="collision" type="box" pos="0.001 -0.0002 -0.029"
|
| 220 |
+
quat="0.5 0.5 0.5 -0.5" size="0.006 0.0281 0.0099"/>
|
| 221 |
+
<camera name="wrist_cam" quat="0 1 0 0" focal="1.93e-3 1.93e-3" resolution="1280 720"
|
| 222 |
+
sensorsize="3896e-6 2140e-6"/>
|
| 223 |
+
</body>
|
| 224 |
+
</body>
|
| 225 |
+
</body>
|
| 226 |
+
</body>
|
| 227 |
+
</body>
|
| 228 |
+
</body>
|
| 229 |
+
</body>
|
| 230 |
+
</body>
|
| 231 |
+
</worldbody>
|
| 232 |
+
|
| 233 |
+
<contact>
|
| 234 |
+
<exclude body1="arm" body2="link_1"/>
|
| 235 |
+
<exclude body1="link_6" body2="left_finger"/>
|
| 236 |
+
<exclude body1="link_6" body2="right_finger"/>
|
| 237 |
+
<exclude body1="link_6" body2="wrist_camera"/>
|
| 238 |
+
<exclude body1="left_finger" body2="right_finger"/>
|
| 239 |
+
<exclude body1="left_finger" body2="right_pad"/>
|
| 240 |
+
<exclude body1="right_finger" body2="left_pad"/>
|
| 241 |
+
</contact>
|
| 242 |
+
|
| 243 |
+
<equality>
|
| 244 |
+
<joint joint1="left_finger" joint2="right_finger" polycoef="0 1 0 0 0"/>
|
| 245 |
+
</equality>
|
| 246 |
+
|
| 247 |
+
<actuator>
|
| 248 |
+
<position name="joint1" joint="joint1" class="dm4340"/>
|
| 249 |
+
<position name="joint2" joint="joint2" class="dm4340"/>
|
| 250 |
+
<position name="joint3" joint="joint3" class="dm4340"/>
|
| 251 |
+
<position name="joint4" joint="joint4" class="dm4310" kp="40" kv="1.5"/>
|
| 252 |
+
<position name="joint5" joint="joint5" class="dm4310"/>
|
| 253 |
+
<position name="joint6" joint="joint6" class="dm4310"/>
|
| 254 |
+
<position class="finger" name="gripper" joint="left_finger"/>
|
| 255 |
+
</actuator>
|
| 256 |
+
</mujoco>
|
tasks/belt-pick/environment/world/run_gauntlet.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runs a controller through the PL-4 acceptance gauntlet on public seeds and prints the verdicts.
|
| 2 |
+
|
| 3 |
+
usage: python3 run_gauntlet.py [--controller /app/controller.py] [--tiers T0,T1,T2,T3,T4] [--episodes 2]
|
| 4 |
+
[--seed 0] [--json out.json]
|
| 5 |
+
|
| 6 |
+
The controller runs in its own process exactly as in the acceptance run (gauntlet/harness.py). Prints one line
|
| 7 |
+
per episode: tier, index, score, verdicts, violations and the main metrics. The acceptance run uses hidden seeds
|
| 8 |
+
and the same scoring. Needs MUJOCO_GL=osmesa (set in the image).
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 17 |
+
sys.path.insert(0, HERE)
|
| 18 |
+
import task as task_mod # noqa: E402 (puts gauntlet/ on sys.path)
|
| 19 |
+
import gauntlet as G # noqa: E402
|
| 20 |
+
import harness # noqa: E402
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
ap = argparse.ArgumentParser()
|
| 25 |
+
ap.add_argument("--controller", default=os.path.join(HERE, "controller.py"))
|
| 26 |
+
ap.add_argument("--tiers", default="T0,T1,T2,T3,T4")
|
| 27 |
+
ap.add_argument("--episodes", type=int, default=2)
|
| 28 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 29 |
+
ap.add_argument("--json", default="")
|
| 30 |
+
a = ap.parse_args()
|
| 31 |
+
ws = harness.Workspace(os.path.abspath(a.controller), HERE)
|
| 32 |
+
task = task_mod.TASK
|
| 33 |
+
rows, t0 = [], time.time()
|
| 34 |
+
try:
|
| 35 |
+
for tier in a.tiers.split(","):
|
| 36 |
+
for i in range(a.episodes):
|
| 37 |
+
r = harness.run_episode(G, task, ws, tier, i, a.seed, task.scene_xml)
|
| 38 |
+
rows.append(r)
|
| 39 |
+
m = r.get("metrics", {})
|
| 40 |
+
print(f"{tier} {i:2d} score={r['score']:.2f} success={r['success']} safe={r['safe']} "
|
| 41 |
+
f"safe_pass={r['safe_pass']} fault={r['pspec'].get('fault') or '-'} "
|
| 42 |
+
f"dist={r['pspec'].get('disturbance') or '-'} "
|
| 43 |
+
f"outcome={r.get('outcome', {}).get('status')}/{r.get('outcome', {}).get('fault', '')} "
|
| 44 |
+
f"violations={r['violations']} progress={m.get('progress')} items={m.get('items')} "
|
| 45 |
+
f"cycle_s={m.get('cycle_s')} grasp_N={m.get('grasp_force_n')} frame_N={m.get('frame_force_n')} "
|
| 46 |
+
f"wall_N={m.get('wall_force_n')} belt_N={m.get('belt_force_n')} t_done={r.get('done_time_s')}"
|
| 47 |
+
+ (f" error={r['error']}" if r.get("error") else "")
|
| 48 |
+
+ (f" ctl_error={r['outcome'].get('error')}" if r.get("outcome", {}).get("error") else ""), flush=True)
|
| 49 |
+
finally:
|
| 50 |
+
ws.close()
|
| 51 |
+
mean = sum(r["score"] for r in rows) / max(1, len(rows))
|
| 52 |
+
print(f"mean score {mean:.3f} over {len(rows)} episodes ({time.time() - t0:.0f} s)")
|
| 53 |
+
if a.json:
|
| 54 |
+
with open(a.json, "w") as f:
|
| 55 |
+
json.dump(rows, f, indent=1, default=str)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
main()
|
tasks/belt-pick/environment/world/scene.xml
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<mujoco model="pl4_packing_cell">
|
| 2 |
+
<compiler angle="radian" autolimits="true"/>
|
| 3 |
+
<option integrator="implicitfast" timestep="0.004" cone="elliptic" impratio="10">
|
| 4 |
+
<flag multiccd="enable"/>
|
| 5 |
+
</option>
|
| 6 |
+
<visual>
|
| 7 |
+
<headlight diffuse="0.3 0.3 0.3" ambient="0.3 0.3 0.3" specular="0 0 0"/>
|
| 8 |
+
<quality shadowsize="0" offsamples="0"/>
|
| 9 |
+
</visual>
|
| 10 |
+
<asset>
|
| 11 |
+
<model name="yam" file="robot/yam_linear_4310.xml"/>
|
| 12 |
+
<material name="table" rgba="0.55 0.55 0.53 1"/>
|
| 13 |
+
<material name="belt" rgba="0.20 0.40 0.74 1"/>
|
| 14 |
+
<material name="steel" rgba="0.58 0.59 0.62 1"/>
|
| 15 |
+
<material name="carton" rgba="0.95 0.95 0.92 1"/>
|
| 16 |
+
<material name="tote" rgba="0.35 0.62 0.35 1"/>
|
| 17 |
+
<material name="datum" rgba="0.10 0.78 0.25 1"/>
|
| 18 |
+
<material name="tart" rgba="0.86 0.33 0.52 1"/>
|
| 19 |
+
<material name="lemon" rgba="0.95 0.80 0.22 1"/>
|
| 20 |
+
</asset>
|
| 21 |
+
<worldbody>
|
| 22 |
+
<light pos="0.3 0 1.6" dir="0 0 -1" directional="true" diffuse="0.4 0.4 0.4" castshadow="false"/>
|
| 23 |
+
<geom name="table" type="box" size="1.2 2.0 0.02" pos="0.2 0.4 -0.02" material="table"/>
|
| 24 |
+
<camera name="overhead" pos="0.27 0.0 0.85" xyaxes="0 -1 0 1 0 0" fovy="60"/>
|
| 25 |
+
<frame name="mount" pos="0 0 0">
|
| 26 |
+
<attach model="yam" body="arm" prefix="robot/"/>
|
| 27 |
+
</frame>
|
| 28 |
+
<body name="belt_frame" pos="0 0 0">
|
| 29 |
+
<geom name="rail_near" type="box" size="0.01 1.2100 0.0325" pos="0.1990 0.4900 0.0325" material="steel"/>
|
| 30 |
+
<geom name="rail_far" type="box" size="0.01 1.0000 0.0325" pos="0.4210 0.7000 0.0325" material="steel"/>
|
| 31 |
+
<geom name="belt_bed" type="box" size="0.1000 1.2100 0.018" pos="0.31 0.4900 0.018" material="steel"/>
|
| 32 |
+
<geom name="belt_skin" type="box" size="0.1000 1.2100 0.002" pos="0.31 0.4900 0.0480" material="belt" contype="0" conaffinity="0"/>
|
| 33 |
+
<geom name="diverter" type="box" size="0.1987 0.006 0.02" pos="0.3100 -0.4600 0.0720" euler="0 0 -1.0122" material="steel" friction="0.15 0.005 0.0001"/>
|
| 34 |
+
<geom name="datum_post" type="box" size="0.022 0.022 0.0240" pos="0.165 -0.01 0.0240" material="steel"/>
|
| 35 |
+
<geom name="datum_plate" type="box" size="0.020 0.020 0.001" pos="0.165 -0.01 0.0490" material="datum"/>
|
| 36 |
+
<geom name="datum_post_far" type="box" size="0.022 0.022 0.0240" pos="0.47 0.24 0.0240" material="steel"/>
|
| 37 |
+
<geom name="datum_plate_far" type="box" size="0.020 0.020 0.001" pos="0.47 0.24 0.0490" material="datum"/>
|
| 38 |
+
</body>
|
| 39 |
+
<body name="belt" pos="0.31 0.0000 0.045000000000000005">
|
| 40 |
+
<joint name="belt_drive" type="slide" axis="0 1 0" armature="20000" damping="0" frictionloss="0"/>
|
| 41 |
+
<geom name="belt_surface" type="box" size="0.0990 2.3000 0.005" group="3" rgba="0.2 0.4 0.74 0" friction="0.9 0.01 0.001" mass="5"/>
|
| 42 |
+
</body>
|
| 43 |
+
<body name="reject_tote" pos="0.4970 -0.52 0">
|
| 44 |
+
<geom name="tote_floor" type="box" size="0.08 0.22 0.002" pos="0 0 0.002" material="tote"/>
|
| 45 |
+
<geom name="tote_wall_far" type="box" size="0.004 0.22 0.015" pos="0.08 0 0.015" material="tote"/>
|
| 46 |
+
<geom name="tote_wall_up" type="box" size="0.08 0.004 0.015" pos="0 0.22 0.015" material="tote"/>
|
| 47 |
+
<geom name="tote_wall_down" type="box" size="0.08 0.004 0.015" pos="0 -0.22 0.015" material="tote"/>
|
| 48 |
+
</body>
|
| 49 |
+
<body name="box_tart" pos="0.075 0.265 0">
|
| 50 |
+
<geom name="box_tart_floor" type="box" size="0.0850 0.0850 0.0030" pos="0 0 0.0030" material="carton"/>
|
| 51 |
+
<geom name="box_tart_wall_n" type="box" size="0.0930 0.0040 0.0275" pos="0.0000 0.0890 0.0275" material="carton"/>
|
| 52 |
+
<geom name="box_tart_wall_s" type="box" size="0.0930 0.0040 0.0275" pos="0.0000 -0.0890 0.0275" material="carton"/>
|
| 53 |
+
<geom name="box_tart_wall_e" type="box" size="0.0040 0.0850 0.0275" pos="0.0890 0.0000 0.0275" material="carton"/>
|
| 54 |
+
<geom name="box_tart_wall_w" type="box" size="0.0040 0.0850 0.0275" pos="-0.0890 0.0000 0.0275" material="carton"/>
|
| 55 |
+
</body>
|
| 56 |
+
<body name="box_lemon" pos="0.075 -0.265 0">
|
| 57 |
+
<geom name="box_lemon_floor" type="box" size="0.0850 0.0850 0.0030" pos="0 0 0.0030" material="carton"/>
|
| 58 |
+
<geom name="box_lemon_wall_n" type="box" size="0.0930 0.0040 0.0275" pos="0.0000 0.0890 0.0275" material="carton"/>
|
| 59 |
+
<geom name="box_lemon_wall_s" type="box" size="0.0930 0.0040 0.0275" pos="0.0000 -0.0890 0.0275" material="carton"/>
|
| 60 |
+
<geom name="box_lemon_wall_e" type="box" size="0.0040 0.0850 0.0275" pos="0.0890 0.0000 0.0275" material="carton"/>
|
| 61 |
+
<geom name="box_lemon_wall_w" type="box" size="0.0040 0.0850 0.0275" pos="-0.0890 0.0000 0.0275" material="carton"/>
|
| 62 |
+
</body>
|
| 63 |
+
<body name="item_0" pos="-1.0 1.0 0.3" gravcomp="1">
|
| 64 |
+
<freejoint name="item_0_free"/>
|
| 65 |
+
<geom name="item_0_round" type="cylinder" size="0.023 0.011" mass="0.030" material="tart" friction="0.9 0.01 0.001" condim="4"/>
|
| 66 |
+
<geom name="item_0_bar" type="box" size="0.021 0.021 0.012" mass="0.035" material="lemon" friction="0.9 0.01 0.001" condim="4"/>
|
| 67 |
+
</body>
|
| 68 |
+
<body name="item_1" pos="-1.1 1.0 0.3" gravcomp="1">
|
| 69 |
+
<freejoint name="item_1_free"/>
|
| 70 |
+
<geom name="item_1_round" type="cylinder" size="0.023 0.011" mass="0.030" material="tart" friction="0.9 0.01 0.001" condim="4"/>
|
| 71 |
+
<geom name="item_1_bar" type="box" size="0.021 0.021 0.012" mass="0.035" material="lemon" friction="0.9 0.01 0.001" condim="4"/>
|
| 72 |
+
</body>
|
| 73 |
+
<body name="item_2" pos="-1.2 1.0 0.3" gravcomp="1">
|
| 74 |
+
<freejoint name="item_2_free"/>
|
| 75 |
+
<geom name="item_2_round" type="cylinder" size="0.023 0.011" mass="0.030" material="tart" friction="0.9 0.01 0.001" condim="4"/>
|
| 76 |
+
<geom name="item_2_bar" type="box" size="0.021 0.021 0.012" mass="0.035" material="lemon" friction="0.9 0.01 0.001" condim="4"/>
|
| 77 |
+
</body>
|
| 78 |
+
<body name="item_3" pos="-1.3 1.0 0.3" gravcomp="1">
|
| 79 |
+
<freejoint name="item_3_free"/>
|
| 80 |
+
<geom name="item_3_round" type="cylinder" size="0.023 0.011" mass="0.030" material="tart" friction="0.9 0.01 0.001" condim="4"/>
|
| 81 |
+
<geom name="item_3_bar" type="box" size="0.021 0.021 0.012" mass="0.035" material="lemon" friction="0.9 0.01 0.001" condim="4"/>
|
| 82 |
+
</body>
|
| 83 |
+
<body name="item_4" pos="-1.4 1.0 0.3" gravcomp="1">
|
| 84 |
+
<freejoint name="item_4_free"/>
|
| 85 |
+
<geom name="item_4_round" type="cylinder" size="0.023 0.011" mass="0.030" material="tart" friction="0.9 0.01 0.001" condim="4"/>
|
| 86 |
+
<geom name="item_4_bar" type="box" size="0.021 0.021 0.012" mass="0.035" material="lemon" friction="0.9 0.01 0.001" condim="4"/>
|
| 87 |
+
</body>
|
| 88 |
+
<body name="item_5" pos="-1.5 1.0 0.3" gravcomp="1">
|
| 89 |
+
<freejoint name="item_5_free"/>
|
| 90 |
+
<geom name="item_5_round" type="cylinder" size="0.023 0.011" mass="0.030" material="tart" friction="0.9 0.01 0.001" condim="4"/>
|
| 91 |
+
<geom name="item_5_bar" type="box" size="0.021 0.021 0.012" mass="0.035" material="lemon" friction="0.9 0.01 0.001" condim="4"/>
|
| 92 |
+
</body>
|
| 93 |
+
</worldbody>
|
| 94 |
+
<contact>
|
| 95 |
+
<exclude body1="belt" body2="belt_frame"/>
|
| 96 |
+
<exclude body1="belt" body2="world"/>
|
| 97 |
+
<exclude body1="belt" body2="box_tart"/>
|
| 98 |
+
<exclude body1="belt" body2="box_lemon"/>
|
| 99 |
+
<exclude body1="belt" body2="reject_tote"/>
|
| 100 |
+
</contact>
|
| 101 |
+
</mujoco>
|
tasks/belt-pick/environment/world/skills/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
tasks/belt-pick/environment/world/skills/SOURCE.md
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copied unchanged from github.com/google-deepmind/robotics-antigravity-plugin (plugins/robotics/skills),
|
| 2 |
+
commit 3dde33820355c70fe8d8e33e42707cdcb742ceb4 (2026-11-20). Copyright 2026 Google LLC, Apache License 2.0 (LICENSE).
|
| 3 |
+
Shipped into task containers at /app/skills/ so agents can use the same workflow (iteration, gauntlet, critic rubric,
|
| 4 |
+
motion planning, IK, perception).
|
tasks/belt-pick/environment/world/skills/blender-creation/SKILL.md
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: blender-creation
|
| 3 |
+
description: >-
|
| 4 |
+
Creates physically calibrated, articulated,
|
| 5 |
+
PBR-textured 3D MuJoCo assets (MJCF
|
| 6 |
+
model.xml, .mjz, mjSpec) from scratch
|
| 7 |
+
using headless Blender (bpy, bmesh,
|
| 8 |
+
blender_mesh_utils, asset_build_utils),
|
| 9 |
+
convex collision synthesis, 10-scenario
|
| 10 |
+
auditing, and Studio preview. Use only
|
| 11 |
+
when asked to create, model, or build a
|
| 12 |
+
3D MuJoCo object from a URL, image, or
|
| 13 |
+
text description, or when blender-creation
|
| 14 |
+
is named. Don't use for non-MuJoCo
|
| 15 |
+
Blender/Cycles/CAD modeling.
|
| 16 |
+
metadata:
|
| 17 |
+
publisher: google
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
# Authoring 3D MuJoCo Assets from Scratch in Blender (`bpy` / `bmesh` + PBR)
|
| 21 |
+
|
| 22 |
+
> [!IMPORTANT]
|
| 23 |
+
>
|
| 24 |
+
> **Companion to [`rules/mujoco_asset_standards.md`][asset-standards]**: Read
|
| 25 |
+
> [`rules/mujoco_asset_standards.md`][asset-standards] first for the mandatory
|
| 26 |
+
> MuJoCo coordinate frame (`UP_POSZ_FORWARD_POSX_RIGHT_NEGY`), SI unit rules,
|
| 27 |
+
> group separation (`group="2"` visual, `group="3"` collision, `group="4"`
|
| 28 |
+
> sites), and physics/audit requirements. This guide covers how to research,
|
| 29 |
+
> measure, model, sculpt, UV-unwrap, texture, bake, export, verify, and
|
| 30 |
+
> interactively preview new assets from scratch using headless Blender
|
| 31 |
+
> (`PYTHONDONTWRITEBYTECODE=1 "$BLENDER_BIN" -b -P ...`),
|
| 32 |
+
> [`scripts/blender_mesh_utils.py`](scripts/blender_mesh_utils.py) (`bmu`),
|
| 33 |
+
> [`scripts/asset_build_utils.py`](scripts/asset_build_utils.py) (`abu`),
|
| 34 |
+
> [`mujoco-audit/SKILL.md`](../mujoco-audit/SKILL.md),
|
| 35 |
+
> [`mujoco-showcase-shot/SKILL.md`](../mujoco-showcase-shot/SKILL.md)
|
| 36 |
+
> ([`render_showcase_shot.py`](../mujoco-showcase-shot/scripts/render_showcase_shot.py)),
|
| 37 |
+
> and [`mujoco-studio-sidecar/SKILL.md`](../mujoco-studio-sidecar/SKILL.md)
|
| 38 |
+
> so they look, behave, and inspect accurately in **MuJoCo's Filament PBR
|
| 39 |
+
> renderer** and **MuJoCo Studio**.
|
| 40 |
+
|
| 41 |
+
---
|
| 42 |
+
|
| 43 |
+
## 1. Entry Point, Subagent Orchestration, Local Blender Setup & Reference Intake
|
| 44 |
+
|
| 45 |
+
### 1.0 Invocation, Defaults & Subagent Orchestration
|
| 46 |
+
|
| 47 |
+
Users invoke this skill in natural language with a product URL, reference image(s), or text specifications:
|
| 48 |
+
|
| 49 |
+
> *"Build a 3D MuJoCo asset for these kitchen tongs: `<url>`"*
|
| 50 |
+
> *"Follow blender-creation to model the object in `<image/link>`"*
|
| 51 |
+
|
| 52 |
+
**Defaults & Optional Overrides**:
|
| 53 |
+
By default, the skill executes the full end-to-end pipeline: auto-detected articulations, intermediate diagnostic renders, 10-scenario dynamic physics simulation auditing (§7.3), and a 360° Filament turntable showcase video (§7.4). Users can optionally request overrides in plain English or bullet points:
|
| 54 |
+
- **`Fast` / `No Turntable`**: Skips Step 7.4 showcase video rendering (saves render time).
|
| 55 |
+
- **`Rigid-Only`**: Forces `0` joints, authoring the object as a single rigid body.
|
| 56 |
+
- **`Skip Physics Audit` / `Fast Audit`**: Skips the 10-scenario dynamic physics simulation suite in Step 7.3 (relying only on Step 7.1 static hygiene & collision alignment checks).
|
| 57 |
+
|
| 58 |
+
1. **If you are the top-level / parent conversation**:
|
| 59 |
+
- Spawn a `self` subagent (`Model: "inherit"`) via `invoke_subagent` to build and verify the asset, passing all user-specified instructions, URLs, and overrides, `Parent Conversation ID: <parent_conv_id>`, and the target asset output parent directory, and instructing the subagent to read this `blender-creation` skill, [`rules/mujoco_asset_standards.md`][asset-standards], [`mujoco-audit/SKILL.md`](../mujoco-audit/SKILL.md), and [`mujoco-showcase-shot/SKILL.md`](../mujoco-showcase-shot/SKILL.md). Do **not** instruct the subagent to write scratch/intake files inside the parent conversation's `brain/<parent_conv_id>/` directory (macOS Seatbelt sandboxing blocks cross-conversation `brain/` access with `PermissionError`); let the subagent use its own `<ArtifactDir>/scratch/` and return the finished asset and preview paths.
|
| 60 |
+
- **When the subagent finishes**: Follow **Step 7.6** ([`mujoco-studio-sidecar/SKILL.md`](../mujoco-studio-sidecar/SKILL.md)) in the top-level conversation to launch (or reuse) the MuJoCo Studio Web sidecar daemon (`studiod.py`) pointed at the finished asset directory (`--workspace_dir=<asset_dir>`) and verify `/_studio/status` (`"ok": true`, `"daemon_connected": true`). Launch `studiod.py` from the top-level conversation rather than inside the builder subagent so the background daemon is not reaped when the subagent exits. In your final response, first present the finished asset path, model summary (dimensions, mass, joints, visual/collision breakdown, audit status), side-by-side comparison, and turntable video (unless skipped via `Fast (No Turntable)`, briefly noting in a 1-line caption that the reel shows a full 360° textured visual spin followed by translucent physics collision hull inspection), and **place `[MuJoCo Studio](sidecar://robotics/mujoco_studio/)` (plus `http://127.0.0.1:<http_port>/` from `$SESSION_FILE` if the Node sidecar proxy is not active) as the very last item at the bottom of your response** so the interactive sidecar pill is never missed at the top.
|
| 61 |
+
|
| 62 |
+
2. **If you are already the spawned Main Builder Subagent**:
|
| 63 |
+
- Do **not** spawn a nested build subagent—execute **Sections 1.1 through 7.5** directly (you may still invoke the read-only `browser` subagent during Step 1.1 if a product URL requires client-side JS rendering). Keep all scratch/intake files in **this subagent's own** `<ArtifactDir>/scratch/` so sandboxed `run_command` steps have local read/write access without `PermissionError`. Do **not** run **Step 7.6** (`studiod.py`) inside the subagent; instead, return the finished `<asset_dir>` path, model summary, comparison images, and turntable video path to the parent conversation so the parent conversation launches `studiod.py` and presents the Studio link.
|
| 64 |
+
- **Ensure `uv` and Headless Blender (`4.2+`) Are Installed Locally (macOS & Linux)**:
|
| 65 |
+
```bash
|
| 66 |
+
uv --version
|
| 67 |
+
if [ -x "/Applications/Blender.app/Contents/MacOS/Blender" ]; then
|
| 68 |
+
BLENDER_BIN="/Applications/Blender.app/Contents/MacOS/Blender"
|
| 69 |
+
else
|
| 70 |
+
BLENDER_BIN="blender"
|
| 71 |
+
fi
|
| 72 |
+
"$BLENDER_BIN" --version || (sudo apt-get update && sudo apt-get install -y blender)
|
| 73 |
+
```
|
| 74 |
+
Run Blender scripts with `PYTHONDONTWRITEBYTECODE=1 "$BLENDER_BIN" -b -P <ArtifactDir>/scratch/build_asset.py` and add `<PLUGIN_DIR>/skills/blender-creation/scripts` to `sys.path` inside the Blender script to `import blender_mesh_utils as bmu`.
|
| 75 |
+
- **MuJoCo Compilation, Filament Showcase Renders & Reference Intake (`uv run`)**:
|
| 76 |
+
```bash
|
| 77 |
+
uv run --with mujoco --with numpy --with scipy --with trimesh --with Pillow \
|
| 78 |
+
python3 <ArtifactDir>/scratch/script.py
|
| 79 |
+
```
|
| 80 |
+
Inside your scratch script, add the plugin script directories (`<PLUGIN_DIR>/skills/blender-creation/scripts`, `<PLUGIN_DIR>/skills/mujoco-audit/scripts`, and `<PLUGIN_DIR>/skills/mujoco-showcase-shot/scripts`) to `sys.path` to import `asset_build_utils as abu`, `audit_scenarios`, and `render_showcase_shot`.
|
| 81 |
+
- **Scope & Workspace Hygiene**:
|
| 82 |
+
- Run `audit_scenarios` 10-scenario physics drop/tip/grasp simulations (**Step 7.3**) by default, verifying all scenarios pass (or remediate failing checks following [`mujoco-audit/SKILL.md`](../mujoco-audit/SKILL.md)). Only skip dynamic simulations if the user explicitly specifies `Skip Physics Audit` or `Fast Audit`. Do not generate a second `<asset_name>_mechanical/` bundle unless requested. Verify clean static `MjModel` compilation, zero-backface normals (`abu.render_blender_diagnostic_sheet`), collision alignment (`audit_scenarios.compute_collision_alignment_summary`), kinematic joint poses (`Articulations: Auto`), and all dynamic physics drop/tip/settle scenarios.
|
| 83 |
+
- Keep all scratch scripts, downloaded reference photos, intermediate meshes, diagnostic `.jpg`/`.png` sheets, `.blend` files, virtual environments (`.venv`), and caches in `<ArtifactDir>/scratch/`, `~/.venvs/`, and `~/.cache/mujoco_pbr_cache`. Only write final asset deliverables (`model.xml`, `meshes/*.obj`, `textures/*.png`) into the target asset directory, and never write `.pyc` / `__pycache__`, `.venv`, or `studiod` scaffold/runtime files into the asset directory.
|
| 84 |
+
- Honor knob overrides: `Articulations: Rigid-Only` -> `0` joints; `Depth: Fast (No Turntable)` -> skip Step 7.4; `Skip Physics Audit` / `Fast Audit` -> skip Step 7.3.
|
| 85 |
+
|
| 86 |
+
### 1.1 Intake, Reference Contact/Detail Sheets & Form Brief
|
| 87 |
+
|
| 88 |
+
1. **Product URL & Reference Intake (`<= 8` Image Reads)**:
|
| 89 |
+
- Never guess product identity, category, or dimensions from a URL path slug (e.g., `/Walnut-Elegant-Design-Coffee-Products/dp/...` may be a truncated SEO slug rather than a coffee table).
|
| 90 |
+
- **When a product URL is provided**:
|
| 91 |
+
1. Invoke the read-only `browser` subagent to navigate to `<product_url>` on behalf of the user. Inspect the live rendered page just as a human designer would:
|
| 92 |
+
- Extract the verified product title, materials, mechanism descriptions, and dimensional specs (`L × W × H` in `mm` and bare-product mass in `kg`, cross-checking retail `Item Weight` vs packaged shipping weight).
|
| 93 |
+
- Identify high-resolution product gallery / carousel image URLs.
|
| 94 |
+
2. **If access is blocked by an interactive CAPTCHA or security gate**: stop without attempting to circumvent the gate and ask the user for the product dimensions, specifications, or reference photos directly.
|
| 95 |
+
3. Download the collected high-resolution gallery images into `<ArtifactDir>/scratch/intake/ref_*.jpg` (e.g. using `curl` or a minimal inline download script).
|
| 96 |
+
- **When no URL is provided (text-only query)**: Look up bare-product `L x W x H` (`mm`) and mass (`kg`) via `search_web` (or invoke the `browser` subagent if `search_web` returns only bare redirect links without snippets). Cross-check retail `Item Weight` against dimensions and material density.
|
| 97 |
+
- **Composite Sheets (`<= 8` Image Reads)**: Never call `read_file` on dozens of individual frames. Stitch the downloaded `ref_*.jpg` photos and sub-feature crops into `ref_contact_sheet` and `ref_details_grid` via `abu.build_ref_contact_and_detail_sheets`, then inspect those composite sheets with `read_file`.
|
| 98 |
+
2. **Sample Photometric RGB Percentiles Directly from Reference Crops (`rgb_sample_boxes`)**:
|
| 99 |
+
- Do **not** invent `RGB` values from verbal category names (*"red plastic"*, *"black rubber"*, *"green plush"*). Pass `rgb_sample_boxes=[('main_shell', ref_path, (x0, y0, x1, y1)), ...]` to `abu.build_ref_contact_and_detail_sheets` to measure `[p25, p50, p75]` sRGB tuples directly from uniform interior surface patches (excluding specular hotspots and cast shadows).
|
| 100 |
+
3. **Write a `<= 25`-Line Form Brief & Named Parameter Block `P` (`<= 40` Named Dimensions)**:
|
| 101 |
+
- Before writing Blender `bmesh` code, write a concise **Form Brief** and define a named parameter dictionary `P = dict(...)` (`<= 40` named dimensions in `mm` / `m` and `deg` with provenance comments) rather than hard-coding hundreds of magic coordinate tuples:
|
| 102 |
+
- **Named primary surfaces & how they meet**: side silhouette facets/angles, plan-view taper, crown cross-section, negative space / open daylight gaps between parts, and flush vs. stepped junctions.
|
| 103 |
+
- **Left/right (`+Y` vs. `-Y`) and front/back (`+X` vs. `-X`) asymmetry**: explicitly note which levers, clips, buttons, labels, or ports appear on each side.
|
| 104 |
+
- **Material regions & parting lines**: e.g., two-shot overmold where rigid ABS forms the inner core and exposed flush rims while matte TPE forms the outer grip skin, or recessed branding pockets.
|
| 105 |
+
- **Mechanisms & travel**: moving sub-parts (hinged lids, sliders, clips, blades, buttons, knobs) with true physical pivot/axis and travel in `m` or `rad`.
|
| 106 |
+
|
| 107 |
+
---
|
| 108 |
+
|
| 109 |
+
## 2. Tool Reference & Target Renderer Rules
|
| 110 |
+
|
| 111 |
+
### 2.1 Quick Helper API Reference (`blender_mesh_utils`, `asset_build_utils`, `render_showcase_shot`)
|
| 112 |
+
|
| 113 |
+
- **`blender_mesh_utils as bmu`** *(inside headless Blender `"$BLENDER_BIN" -b -P`, from [`scripts/blender_mesh_utils.py`](scripts/blender_mesh_utils.py))*:
|
| 114 |
+
- `bmu.clear_scene() -> None`
|
| 115 |
+
- `bmu.assign_pbr_material(objects, name=None, *, base_color=None, base_color_srgb=(200, 200, 200), roughness=0.4, metallic=0.0, normal_bump_mm=0.0, bump_height_mm=0.0, bump_scale=250.0) -> bpy.types.Material`
|
| 116 |
+
- `bmu.skin_skeleton(name, nodes_xyzr, edges=None, *, subsurf_levels=2) -> obj`
|
| 117 |
+
- `bmu.metaball_sdf(name, elements, *, resolution=0.002) -> obj`
|
| 118 |
+
- `bmu.swept_tube(name, points_xyzr, *, bevel_resolution=6) -> obj`
|
| 119 |
+
- `bmu.voxel_smooth_union(name, objects, *, voxel_size=0.0015, smooth_iterations=6) -> obj`
|
| 120 |
+
- `bmu.apply_boolean_cutter(target_obj, cutter_obj, *, operation='DIFFERENCE', solver='MANIFOLD') -> obj`
|
| 121 |
+
- `bmu.smart_seam_unwrap(target_obj, *, angle_limit_deg=66.0, margin=0.005) -> obj`
|
| 122 |
+
- `bmu.smart_uv_project(objects, *, angle_limit_deg=66.0, island_margin=0.01, margin=None) -> list[obj]`
|
| 123 |
+
- `bmu.pack_shared_uv_atlas(objs, *, margin=0.005, rotate=True, align_minimal_bbox=True, match_3d_area=True) -> None`
|
| 124 |
+
- `bmu.finalize_and_export_obj(target_obj, out_obj_path, *, crease_deg=None, world_pos=None, body_pos=None, ensure_uvs=True) -> {'verts', 'quads', 'tris', 'earclipped_ngons'}`
|
| 125 |
+
- `bmu.export_convex_hull_col(source_obj_or_points, out_obj_path, *, clip_bounds_world_m=None, clip_bounds_m=None, max_verts=64, name=None, world_pos=(0,0,0), body_pos=None) -> col_obj`
|
| 126 |
+
- `bmu.bake_pbr_maps(out_dir, *, material_groups=None, resolution=1024, samples=8) -> {key: {'basecolor', 'roughness', 'metallic', 'normal'}}`
|
| 127 |
+
- **`asset_build_utils as abu`** *(inside `uv run` scripts, from [`scripts/asset_build_utils.py`](scripts/asset_build_utils.py))*:
|
| 128 |
+
- `abu.build_ref_contact_and_detail_sheets(ref_paths, detail_crops, out_contact_png, out_details_png, *, raw_crops_dir=None, rgb_sample_boxes=None, cols=3, cell_size=440, include_shadow_lift=False) -> dict`
|
| 129 |
+
- `abu.fetch_ambientcg_maps(asset_id, *, cache_dir=None, resolution='1K') -> {'color', 'roughness', 'normal_gl', 'metallic', 'ao', 'opacity', ...}`
|
| 130 |
+
- `abu.rasterize_uv_world_fields(obj_paths, canvas_size=1024, *, part_offsets=None) -> dict`
|
| 131 |
+
- `abu.dilate_uv_gutters(arr, valid_mask, *, max_dist_px=12) -> np.ndarray`
|
| 132 |
+
- `abu.triplanar_project_map(map_2d, xyz, world_normal, *, texels_per_meter=4000.0, sharpness=4.0) -> np.ndarray`
|
| 133 |
+
- `abu.height_to_normal_rgb(height_map, strength=3.5, *, smooth_sigma=0.0, valid_mask=None) -> (H,W,3) uint8`
|
| 134 |
+
- `abu.normal_rgb_from_3d_height_fn(height_fn, uv_world_fields, *, step_mm=0.15, strength=1.0) -> (H,W,3) uint8`
|
| 135 |
+
- `abu.fbm_noise_3d(xyz, *, base_freq=25.0, wavelength_mm=None, octaves=4, persistence=0.5, seed=42) -> (...,) float32`
|
| 136 |
+
- `abu.compute_volume_weighted_hull_masses(mesh_dir, col_names, total_mass_kg, *, density_weights=None) -> {col_name: mass_kg}`
|
| 137 |
+
- `abu.render_blender_diagnostic_sheet(blend_path, out_png, *, xml_path=None, part_pivots=None, panel_size=420) -> {'out_png', 'has_backfaces', 'backface_pixels_per_view'}`
|
| 138 |
+
- `abu.build_variant_bundles(base_asset_dir, parent_assets_dir, base_name, variants, render_variant_textures_fn) -> list[str]`
|
| 139 |
+
- **`render_showcase_shot`** *(inside `uv run` scripts, from [`../mujoco-showcase-shot/scripts/render_showcase_shot.py`](../mujoco-showcase-shot/scripts/render_showcase_shot.py))*:
|
| 140 |
+
- `render_side_by_side_comparison(asset_path, ref_specs, out_png, *, detail_crops_out_png=None, six_view_out_png=None, six_view_panel_size=420, six_view_qpos=None, fovy=35.0, white_bg=True, clay_only=False) -> {'comparison_png', 'detail_crops_png', 'six_view_png'}`
|
| 141 |
+
- `render_filament_still(asset_path, views, *, width=800, height=800, fovy=None, white_bg=False, show_plinth=False) -> list[np.ndarray]`
|
| 142 |
+
- `render_6view_inspection_sheet(asset_path, out_png, *, panel_size=420, qpos=None) -> out_png`
|
| 143 |
+
- `render_wireframe_and_uv_sheet(asset_path, out_png, *, panel_size=440) -> out_png`
|
| 144 |
+
- `render_showcase_shot_video(asset_path, output_mp4, width=960, height=720, fps=30, duration=8.0, articulation_cycles=2.0) -> dict`
|
| 145 |
+
|
| 146 |
+
---
|
| 147 |
+
|
| 148 |
+
### 2.2 Target Renderer: Optimize for MuJoCo Filament (Not Standalone Cycles)
|
| 149 |
+
|
| 150 |
+
1. **Get into MuJoCo Filament Early & Render Intermediate Diagnostics**:
|
| 151 |
+
- Do **not** build an entire asset blind and only render at the very end. After blocking out primary 3D geometry in Blender (saving `<ArtifactDir>/scratch/<asset_name>.blend` and exporting `.obj` meshes), immediately run **intermediate diagnostic renders**:
|
| 152 |
+
- `abu.render_blender_diagnostic_sheet(blend_path, out_png=..., xml_path=...)` to inspect 6-view clay/wireframe shading, backface orientation (`has_backfaces == False`), and joint pivots.
|
| 153 |
+
- `render_showcase_shot.render_side_by_side_comparison(..., clay_only=True)` to compare your untextured 3D form directly against the reference photos at matched camera angles before spending time on textures and decals.
|
| 154 |
+
2. **MuJoCo Filament Normal Handling (`model_resources.cc`) — Smooth Curves vs. Crisp Creases**:
|
| 155 |
+
- In MuJoCo's Filament backend (`FillMeshBuffer`), if the angle between a triangle's geometric `face_normal` and its exported vertex normal `mesh_normal` exceeds $\sim 36.87^\circ$ ($\cos\theta < 0.8$), Filament may fall back to the flat `face_normal` (`UseFaceNormal`).
|
| 156 |
+
- **For smooth curved surfaces, bevels & domes**:
|
| 157 |
+
1. Always call `bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])` on every closed mesh before setting smooth shading or exporting `.obj`.
|
| 158 |
+
2. Set `f.smooth = True` on smoothly curved/beveled faces and keep adjacent bevel/fillet step angles $\le 15^\circ\text{–}22^\circ$ so `dot(face_normal, vertex_normal) > 0.8`.
|
| 159 |
+
- **For crisp industrial-design creases, chamfers & faceted parts**:
|
| 160 |
+
1. Do **not** blindly set `f.smooth = True` across sharp ridges, flat-topped prismatic facets, or distinct chamfer bevels.
|
| 161 |
+
2. Use `bmu.finalize_and_export_obj(obj, out_obj_path, crease_deg=35.0, body_pos=...)` (which marks crease edges above `crease_deg` sharp and applies `WEIGHTED_NORMAL(keep_sharp=True)`) or keep flat facets `f.smooth = False` so Filament preserves crisp specular transitions.
|
| 162 |
+
|
| 163 |
+
---
|
| 164 |
+
|
| 165 |
+
## 3. Pure-Blender Geometry Authoring, Modular `bmu` Helpers & Topology Rules
|
| 166 |
+
|
| 167 |
+
### 3.1 Freedom of Geometry & Modular `blender_mesh_utils` (`bmu`) Builders
|
| 168 |
+
|
| 169 |
+
You have full freedom in Python (`bpy` / `bmesh` / `mathutils` / modifiers) plus the zero-magic builders in [`scripts/blender_mesh_utils.py`](scripts/blender_mesh_utils.py) (`bmu`) to construct whatever geometry faithfully captures each component:
|
| 170 |
+
|
| 171 |
+
- **Profile Lofting, Extrusion, Bevels & Boolean Split Shells (`bmesh` + `bmu.apply_boolean_cutter`)**:
|
| 172 |
+
- For faceted or contoured industrial housings (e.g., an ergonomic tool housing with shoulder chamfers, plan-view taper, and two-shot elastomer/ABS overmold parting lines), drive cross-sections from your named parameter dictionary `P`.
|
| 173 |
+
- Use `bmu.apply_boolean_cutter(target_obj, cutter_obj, operation='DIFFERENCE' | 'INTERSECT' | 'UNION')` (which safely runs Blender's `MANIFOLD` boolean solver with an automatic welded `EXACT` fallback) to carve recessed pockets, moat grooves, actuator slots, and flush two-shot material splits from a shared outer envelope.
|
| 174 |
+
- **Declarative Organic & Tubular Builders (`bmu`)**:
|
| 175 |
+
- `bmu.skin_skeleton(name, nodes_xyzr, edges=None, *, subsurf_levels=2)`: branching organic limbs, frames, or handles from `(x, y, z, r)` or `(x, y, z, (rx, ry))` skeleton graphs.
|
| 176 |
+
- `bmu.metaball_sdf(name, elements, *, resolution=0.002)`: analytical implicit SDF blends (`BALL`, `CAPSULE`, `ELLIPSOID`, `CUBE`, with `use_negative=True` for ergonomic thumb indents or cavities).
|
| 177 |
+
- `bmu.swept_tube(name, points_xyzr, *, bevel_resolution=6)`: 3D `NURBS` tubes, cords, straps, wire loops, or bent rods with per-point radius and end caps.
|
| 178 |
+
- `bmu.voxel_smooth_union(name, objects, *, voxel_size=0.0015, smooth_iterations=6)`: watertight voxel-remeshed fillets across intersecting sub-parts.
|
| 179 |
+
|
| 180 |
+
### 3.2 Kinematic Root Selection & Mesh Splitting by Link / Material Role
|
| 181 |
+
|
| 182 |
+
1. **Kinematic Root Body Selection**:
|
| 183 |
+
- Choose the **root `<body>`** to be the **primary stationary base or primary grasped housing** during normal operation, and make components that move relative to that housing the child `<body>` elements.
|
| 184 |
+
2. **Split into Separate Meshes by Articulation Link & Material Role**:
|
| 185 |
+
- Export separate `.obj` files in `meshes/` for each articulated `<body>` (link) and each distinct `<material>` within a body.
|
| 186 |
+
|
| 187 |
+
### 3.3 Sensible Polycount Budgets & `bmesh` Topology Rules
|
| 188 |
+
|
| 189 |
+
- **Polycount Budgets**:
|
| 190 |
+
- Simple flat/beveled component: $100\text{–}1,500\text{ tris}$.
|
| 191 |
+
- Contoured housing with rounded corners, fillets & cutouts: $1,500\text{–}6,500\text{ tris}$.
|
| 192 |
+
- Complete multi-part prop/appliance: **$5,000\text{–}20,000\text{ tris}$ total** across all visual meshes.
|
| 193 |
+
- **`bmesh` Topology Rules**:
|
| 194 |
+
1. **Subdivide straight edges before carving localized edge features** and add an inner rim loop so cutouts stay confined cleanly to the outer lip.
|
| 195 |
+
2. **Keep planar hole loops strictly inside the outer perimeter ($\ge 2\text{ mm}$ clearance)** before calling `bmesh.ops.triangle_fill`.
|
| 196 |
+
3. **Prevent coplanar Z-fighting between layered parts**: separate layered surfaces by $\ge 0.2\text{ mm}$ or cut an interior pocket.
|
| 197 |
+
4. **Uniform metric edge offsets**: inset perimeter bevels by a constant metric distance $d$ (in meters) along $X$ and $Y$ rather than radial fractions on elongated parts, and never pinch top/bottom rings into a zero-thickness knife-edge equator.
|
| 198 |
+
5. **Watertight thickness + `inertia="shell"` on thin visual meshes**: extrude thin plaques, labels, blades, and lenses to $\ge 1.5\text{–}3\text{ mm}$ watertight thickness and declare `<mesh name="..._vis" file="..._vis.obj" inertia="shell"/>` so `mjCMesh::Compile` never fails with `mesh volume is too small`.
|
| 199 |
+
|
| 200 |
+
---
|
| 201 |
+
|
| 202 |
+
## 4. Canonical MuJoCo Coordinate Frame, Camera Angles & `model.xml`
|
| 203 |
+
|
| 204 |
+
1. **World Coordinate Frame (`UP_POSZ_FORWARD_POSX_RIGHT_NEGY`, `1 unit = 1.0 m`)**:
|
| 205 |
+
- **`+Z`** Up (resting base at $z = 0.000\text{ m}$), **`+X`** Front, **`-X`** Back, **`+Y`** Left, **`-Y`** Right.
|
| 206 |
+
- Looking at **`+X` Front** toward `-X`, viewer-left is **`-Y`** and viewer-right is **`+Y`**. Looking at **`-Y` Right** toward `+Y`, viewer-left is **`-X`** and viewer-right is **`+X`**.
|
| 207 |
+
2. **MuJoCo `mjvCamera` Azimuth & Elevation Convention**:
|
| 208 |
+
- **`azimuth = 180°`**: Views **`Front (+X)`** | **`azimuth = 0°`**: Views **`Back (-X)`** | **`azimuth = 90°`**: Views **`Right (-Y)`** | **`azimuth = 270°`**: Views **`Left (+Y)`**.
|
| 209 |
+
- **`elevation < 0°`**: Camera above looking downward (`-25°..-45°` = tabletop 3/4 view; `-88°` = overhead `Top (+Z)` view).
|
| 210 |
+
3. **Articulated Child Bodies & Non-Destructive Identity-Axis Export (`bmu.finalize_and_export_obj`)**:
|
| 211 |
+
- Keep scene objects at their assembled world poses in `.blend`, and pass `body_pos=(px, py, pz)` to `bmu.finalize_and_export_obj(obj, out_obj_path, crease_deg=..., body_pos=(px, py, pz))` so `.obj` vertices export around each child body's local joint origin `(0, 0, 0)` with `forward_axis='Y', up_axis='Z', export_materials=False` without mutating live `.blend` positions.
|
| 212 |
+
4. **Canonical `model.xml` Skeleton** (`<asset_name>/model.xml`, no `scene.xml`, no `<option/>`, no root `<freejoint/>`, visual geoms in `group="2"` with `mass="0" density="0"`, physical mass on `group="3"` colliders):
|
| 213 |
+
|
| 214 |
+
```xml
|
| 215 |
+
<mujoco model="asset_name">
|
| 216 |
+
<compiler angle="radian" meshdir="meshes" texturedir="textures" autolimits="true"/>
|
| 217 |
+
|
| 218 |
+
<default>
|
| 219 |
+
<default class="visual">
|
| 220 |
+
<geom group="2" type="mesh" contype="0" conaffinity="0" density="0" mass="0"/>
|
| 221 |
+
</default>
|
| 222 |
+
<default class="collision">
|
| 223 |
+
<geom group="3" type="mesh" contype="1" conaffinity="1" condim="4"
|
| 224 |
+
friction="0.7 0.02 0.005" solref="0.004 1" margin="0"
|
| 225 |
+
rgba="0.25 0.75 0.45 0.45"/>
|
| 226 |
+
</default>
|
| 227 |
+
</default>
|
| 228 |
+
|
| 229 |
+
<asset>
|
| 230 |
+
<texture name="body_basecolor" type="2d" file="body_basecolor.png" colorspace="sRGB"/>
|
| 231 |
+
<texture name="body_roughness" type="2d" file="body_roughness.png" colorspace="linear"/>
|
| 232 |
+
<texture name="body_normal" type="2d" file="body_normal.png" colorspace="linear"/>
|
| 233 |
+
<texture name="body_metallic" type="2d" file="body_metallic.png" colorspace="linear"/>
|
| 234 |
+
|
| 235 |
+
<!-- Set scalar roughness="1.0" (and metallic="1.0") when wiring texture layers -->
|
| 236 |
+
<material name="body_mat" rgba="1 1 1 1" metallic="1.0" roughness="1.0">
|
| 237 |
+
<layer texture="body_basecolor" role="rgb"/>
|
| 238 |
+
<layer texture="body_roughness" role="roughness"/>
|
| 239 |
+
<layer texture="body_normal" role="normal"/>
|
| 240 |
+
<layer texture="body_metallic" role="metallic"/>
|
| 241 |
+
</material>
|
| 242 |
+
|
| 243 |
+
<mesh name="body_vis" file="body_vis.obj" inertia="shell"/>
|
| 244 |
+
<mesh name="body_hull_0_col" file="body_hull_0_col.obj" maxhullvert="64"/>
|
| 245 |
+
</asset>
|
| 246 |
+
|
| 247 |
+
<worldbody>
|
| 248 |
+
<body name="asset_name" pos="0 0 0" quat="1 0 0 0">
|
| 249 |
+
<geom name="body_vis" class="visual" mesh="body_vis" material="body_mat"/>
|
| 250 |
+
<geom name="body_hull_0_col" class="collision" mesh="body_hull_0_col" mass="0.250"/>
|
| 251 |
+
</body>
|
| 252 |
+
</worldbody>
|
| 253 |
+
</mujoco>
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
---
|
| 257 |
+
|
| 258 |
+
## 5. PBR Textures, Procedural Normal Maps & Cycles Baking
|
| 259 |
+
|
| 260 |
+
### 5.1 Cycles PBR Baking (`bmu.assign_pbr_material` + `bmu.bake_pbr_maps`) & 3D UV-World Field Synthesis
|
| 261 |
+
|
| 262 |
+
1. **Baking Procedural Materials in Blender (`bmu.assign_pbr_material` + `bmu.bake_pbr_maps`)**:
|
| 263 |
+
- Assign procedural PBR materials (`bmu.assign_pbr_material` or custom Blender `ShaderNodeTexNoise`/`ShaderNodeBump` node trees) and bake 4-channel PBR maps (`basecolor`, `roughness`, `metallic`, `normal`) via `bmu.bake_pbr_maps`:
|
| 264 |
+
```python
|
| 265 |
+
bmu.assign_pbr_material(
|
| 266 |
+
["housing_vis"], base_color_srgb=(200, 28, 34), roughness=0.32, bump_height_mm=0.08
|
| 267 |
+
)
|
| 268 |
+
bmu.bake_pbr_maps(f"{asset_dir}/textures", resolution=1024, samples=8)
|
| 269 |
+
```
|
| 270 |
+
2. **Fetching Real CC0 PBR Scans (`abu.fetch_ambientcg_maps`) & 3D UV-World Field Synthesis (`abu.rasterize_uv_world_fields`)**:
|
| 271 |
+
- Use `abu.fetch_ambientcg_maps(asset_id, resolution='1K')` to fetch real CC0 PBR texture maps (cached in `~/.cache/mujoco_pbr_cache`).
|
| 272 |
+
- For seam-free 3D procedural normal maps or triplanar projection across UV islands in `uv run`, rasterize the exported `.obj` UV layout with `fields = abu.rasterize_uv_world_fields(obj_path, canvas_size=1024)` and synthesize tangent-space normal maps via `abu.normal_rgb_from_3d_height_fn(height_fn, fields)` or `abu.height_to_normal_rgb(..., valid_mask=fields['valid_mask'])`.
|
| 273 |
+
- **Filament Scalar-vs-Texture Multiplication Rule**: Always set `roughness="1.0"` (and `metallic="1.0"` when wiring a metallic map) on `<material>` so `<layer role="roughness"/>` and `<layer role="metallic"/>` represent true physical values without double-multiplying.
|
| 274 |
+
3. **Outward-Normal Planar UV Rule for Procedural Legends (`PIL.ImageDraw`)**:
|
| 275 |
+
- When projecting planar UVs manually in `bmesh`, orient $u$ along the viewer's local rightward tangent $\hat{t}_{\text{right}} = \text{normalize}(\vec{n} \times \hat{z})$ using the face's outward normal $\vec{n}$ so opposing faces (`+Y` vs. `-Y`, `+X` vs. `-X`) are never horizontally mirrored.
|
| 276 |
+
|
| 277 |
+
---
|
| 278 |
+
|
| 279 |
+
## 6. Collision Hulls & Mass/Inertia (`bmu.export_convex_hull_col` & `coacd` Fallback)
|
| 280 |
+
|
| 281 |
+
1. **Collision Geometry Must Match the Function of the Asset**:
|
| 282 |
+
- The `group="3"` collision representation must faithfully preserve the functional affordances of the asset:
|
| 283 |
+
- **Open cavities & receptacles** (mugs, bowls, bins, trays, drawers) must remain open and unobstructed so smaller objects can be dropped or placed inside.
|
| 284 |
+
- **Through-holes & grasp loops** (scissors finger rings, kettlebell/mug handles, trigger guards) must remain open so fingers or hooks can pass through.
|
| 285 |
+
- **Stable resting bases & rolling contours**: Flat resting feet must sit flush at $z = 0.000\text{ m}$ without rocking on polyhedral facets, and cylindrical/spherical rolling surfaces must remain smooth and concentric.
|
| 286 |
+
- **Articulation clearances**: Colliders on parent and child links must not self-collide or jam across the full joint range.
|
| 287 |
+
- **Gap-free silhouette coverage (no needle penetration)**: Every visual surface must be backed by collision geometry so no ray/needle can pierce the visual mesh (`group="2"`) without intersecting a collider (`group="3"`).
|
| 288 |
+
2. **Prefer Hand-Authored Convex Hulls (`bmu.export_convex_hull_col`) & Analytic Primitives**:
|
| 289 |
+
- **Agents should prefer creating convex hulls and analytic primitives by hand** directly in the Blender script where exact part boundaries and functional splits are known:
|
| 290 |
+
- Do not approximate rounded housings or curved parts with blocky `<geom type="box"/>` primitives. Use `bmu.export_convex_hull_col(source_obj_or_points, out_obj_path, clip_bounds_world_m=(cmin, cmax), max_verts=64, body_pos=...)` to plane-clip (`bmesh.ops.bisect_plane`), downsample (`<= 64` vertices), validate 3D enclosed volume, and export tight convex hulls (`maxhullvert="64"`) directly from your visual meshes.
|
| 291 |
+
- **Overlap adjacent slices & ring segments at seams**: When splitting a part across multiple `clip_bounds_world_m` boxes or arranging wall/ring primitives around a cavity or loop, overlap adjacent bounds/segments by `1–2 mm` (or share exact cut planes before downsampling) so no open cracks or corner gaps remain between neighboring colliders.
|
| 292 |
+
- Use analytic primitives (`cylinder`, `capsule`, `sphere`, `box`) for genuinely geometric shafts, rods, wheels, and flat plates, or arrange ring segments around hollow cavities/loops.
|
| 293 |
+
- Use `abu.compute_volume_weighted_hull_masses(mesh_dir, col_names, total_mass_kg, density_weights=...)` in `uv run` to distribute physical mass across `group="3"` collision geoms proportionally to hull volume and material density.
|
| 294 |
+
3. **Fallback to `coacd` for Complex Concave Geometry**:
|
| 295 |
+
- If an asset's geometry is too complex to decompose by hand into plane-clipped hulls or primitives, **fall back to `coacd`** (the standard `coacd` package/CLI via `uv run --with coacd --with trimesh`) and **tune its parameters** (`threshold`, `max_convex_hull`, `preprocess_mode`, and `maxhullvert="64"`) so the decomposition matches the asset's function without plugging cavities or shattering simple walls into sliver hulls:
|
| 296 |
+
```python
|
| 297 |
+
# Run via: uv run --with coacd --with trimesh --with numpy python3 <ArtifactDir>/scratch/run_coacd.py
|
| 298 |
+
import coacd
|
| 299 |
+
import trimesh
|
| 300 |
+
|
| 301 |
+
mesh = trimesh.load("/path/to/asset/meshes/part_vis.obj", force="mesh")
|
| 302 |
+
coacd_mesh = coacd.Mesh(mesh.vertices, mesh.faces)
|
| 303 |
+
parts = coacd.run_coacd(
|
| 304 |
+
coacd_mesh,
|
| 305 |
+
threshold=0.05, # Tune (e.g. 0.02..0.08) to preserve cavities without over-shattering
|
| 306 |
+
max_convex_hull=16, # Cap hull count per link to match functional features
|
| 307 |
+
preprocess_mode="auto",
|
| 308 |
+
)
|
| 309 |
+
```
|
| 310 |
+
|
| 311 |
+
---
|
| 312 |
+
|
| 313 |
+
## 7. Intermediate Verification, Alignment Check, Audit, Turntable & Studio Preview
|
| 314 |
+
|
| 315 |
+
### 7.1 Static Hygiene, Collision Alignment & 2-Column Side-by-Side Comparison (`render_side_by_side_comparison`)
|
| 316 |
+
|
| 317 |
+
Combine static `MjModel` compilation, mesh/UV hygiene, collision alignment (`audit_scenarios.compute_collision_alignment_summary`), intermediate Blender backface diagnostics (`abu.render_blender_diagnostic_sheet`), and showcase comparison renders (`ref_vs_filament_comparison.jpg` + `render_details_grid.jpg` + `six_view_inspection_sheet.jpg`) into a **single `verify_and_render.py` invocation**:
|
| 318 |
+
|
| 319 |
+
```bash
|
| 320 |
+
uv run --with mujoco --with numpy --with scipy --with trimesh --with Pillow \
|
| 321 |
+
python3 <ArtifactDir>/scratch/verify_and_render.py
|
| 322 |
+
```
|
| 323 |
+
|
| 324 |
+
```python
|
| 325 |
+
import os
|
| 326 |
+
import sys
|
| 327 |
+
|
| 328 |
+
plugin_dir = os.environ.get("PLUGIN_DIR", "/path/to/plugins/robotics")
|
| 329 |
+
for sub in (
|
| 330 |
+
"skills/blender-creation/scripts",
|
| 331 |
+
"skills/mujoco-audit/scripts",
|
| 332 |
+
"skills/mujoco-showcase-shot/scripts",
|
| 333 |
+
):
|
| 334 |
+
p = os.path.join(plugin_dir, sub)
|
| 335 |
+
if p not in sys.path:
|
| 336 |
+
sys.path.insert(0, p)
|
| 337 |
+
|
| 338 |
+
import asset_build_utils
|
| 339 |
+
import audit_scenarios
|
| 340 |
+
import mujoco
|
| 341 |
+
import render_showcase_shot
|
| 342 |
+
|
| 343 |
+
xml_path = "/path/to/asset/model.xml"
|
| 344 |
+
blend_path = "/path/to/scratch/asset_name.blend"
|
| 345 |
+
scratch_dir = "/path/to/scratch"
|
| 346 |
+
|
| 347 |
+
if hasattr(audit_scenarios, "validate_static_and_mesh_hygiene"):
|
| 348 |
+
hygiene = audit_scenarios.validate_static_and_mesh_hygiene(xml_path)
|
| 349 |
+
assert hygiene["passed"], f"Hygiene errors: {hygiene['errors']}"
|
| 350 |
+
|
| 351 |
+
m = mujoco.MjModel.from_xml_path(xml_path)
|
| 352 |
+
d = mujoco.MjData(m)
|
| 353 |
+
mujoco.mj_forward(m, d)
|
| 354 |
+
align_res = audit_scenarios.compute_collision_alignment_summary(m, d)
|
| 355 |
+
assert align_res["status"] != "FAIL", f"Alignment failed: {align_res['issues']}"
|
| 356 |
+
if m.njnt > 0:
|
| 357 |
+
for _ in range(100):
|
| 358 |
+
mujoco.mj_step(m, d)
|
| 359 |
+
assert d.qacc.size == 0 or all(abs(float(x)) < 1e6 for x in d.qacc), "Unstable joint settle!"
|
| 360 |
+
mujoco.mj_resetData(m, d)
|
| 361 |
+
mujoco.mj_forward(m, d)
|
| 362 |
+
|
| 363 |
+
diag = asset_build_utils.render_blender_diagnostic_sheet(
|
| 364 |
+
blend_path=blend_path, out_png=f"{scratch_dir}/blender_diag_sheet.jpg", xml_path=xml_path
|
| 365 |
+
)
|
| 366 |
+
assert not diag["has_backfaces"], f"Flipped faces: {diag['backface_pixels_per_view']}"
|
| 367 |
+
|
| 368 |
+
ref_specs = [
|
| 369 |
+
{
|
| 370 |
+
"ref_path": f"{scratch_dir}/intake/ref_00.jpg",
|
| 371 |
+
"label": "View 1 (Hero View)",
|
| 372 |
+
"azimuth": 135.0,
|
| 373 |
+
"elevation": -25.0,
|
| 374 |
+
"white_bg": True,
|
| 375 |
+
"crop_boxes_norm": [("Primary Form & Surface", (0.25, 0.20, 0.75, 0.70))],
|
| 376 |
+
},
|
| 377 |
+
]
|
| 378 |
+
|
| 379 |
+
if "--clay" in sys.argv:
|
| 380 |
+
render_showcase_shot.render_side_by_side_comparison(
|
| 381 |
+
xml_path,
|
| 382 |
+
ref_specs=ref_specs,
|
| 383 |
+
out_png=f"{scratch_dir}/ref_vs_clay.jpg",
|
| 384 |
+
detail_crops_out_png=f"{scratch_dir}/clay_details_grid.jpg",
|
| 385 |
+
clay_only=True,
|
| 386 |
+
)
|
| 387 |
+
sys.exit(0)
|
| 388 |
+
|
| 389 |
+
render_showcase_shot.render_wireframe_and_uv_sheet(
|
| 390 |
+
xml_path, out_png=f"{scratch_dir}/wireframe_and_uv_sheet.jpg"
|
| 391 |
+
)
|
| 392 |
+
render_showcase_shot.render_side_by_side_comparison(
|
| 393 |
+
xml_path,
|
| 394 |
+
ref_specs=ref_specs,
|
| 395 |
+
out_png=f"{scratch_dir}/ref_vs_filament_comparison.jpg",
|
| 396 |
+
detail_crops_out_png=f"{scratch_dir}/render_details_grid.jpg",
|
| 397 |
+
six_view_out_png=f"{scratch_dir}/six_view_inspection_sheet.jpg",
|
| 398 |
+
)
|
| 399 |
+
```
|
| 400 |
+
|
| 401 |
+
### 7.2 Difference-Driven Self-Review (Iterative Intermediate & Final Critique)
|
| 402 |
+
|
| 403 |
+
- Inspect `blender_diag_sheet.jpg`, `ref_vs_clay.jpg` (during geometry blockout), `ref_vs_filament_comparison.jpg`, `render_details_grid.jpg`, and `six_view_inspection_sheet.jpg` directly with `read_file`.
|
| 404 |
+
- Before every geometry or material revision, explicitly list the **top 3 visual discrepancies** between the reference photo and the render:
|
| 405 |
+
1. **View** (e.g., `View 1 Right (-Y)` or `View 2 Front-Right 3/4`),
|
| 406 |
+
2. **Feature** (e.g., front-top chamfer slope, upper rim thickness, actuator button height),
|
| 407 |
+
3. **Estimated error in `mm` or `deg`** (e.g., upper rim is `~4 mm` too high; nose plan taper is `~3 mm` too wide),
|
| 408 |
+
4. **Owning key in `P` or material parameter** (e.g., `P["rim_z_frac"] = 0.72 -> 0.66`), then re-run your Blender script and `verify_and_render.py` to confirm the fix.
|
| 409 |
+
|
| 410 |
+
### 7.3 Programmatic Physics Scenario Audit (`audit_scenarios`)
|
| 411 |
+
|
| 412 |
+
By default (unless overridden by `Skip Physics Audit` / `Fast Audit`; see [`mujoco-audit/SKILL.md`](../mujoco-audit/SKILL.md) and [`audit_scenarios.py`](../mujoco-audit/scripts/audit_scenarios.py)), run the 10-scenario physical drop/tip/grasp simulation test suite:
|
| 413 |
+
|
| 414 |
+
```bash
|
| 415 |
+
uv run "$PLUGIN_DIR/skills/mujoco-audit/scripts/audit_scenarios.py" \
|
| 416 |
+
--xml_path=/path/to/asset/model.xml \
|
| 417 |
+
--out_dir=<ArtifactDir>/scratch/audit_out \
|
| 418 |
+
--label=<asset_name>
|
| 419 |
+
```
|
| 420 |
+
|
| 421 |
+
Verify that all scenarios pass. If a scenario fails (e.g., penetration, excessive bounce, or unstable resting contact), follow the engineering-judgment remediation rules in [`mujoco-audit/SKILL.md`](../mujoco-audit/SKILL.md) to adjust mass/inertial diagonal, contact friction, or collision geoms before finalizing the asset.
|
| 422 |
+
|
| 423 |
+
### 7.4 Final 360° Filament PBR Turntable Showcase (`render_showcase_shot`)
|
| 424 |
+
|
| 425 |
+
By default (unless overridden by `Fast (No Turntable)`; see [`mujoco-showcase-shot/SKILL.md`](../mujoco-showcase-shot/SKILL.md) and [`render_showcase_shot.py`](../mujoco-showcase-shot/scripts/render_showcase_shot.py)):
|
| 426 |
+
|
| 427 |
+
```bash
|
| 428 |
+
uv run "$PLUGIN_DIR/skills/mujoco-showcase-shot/scripts/render_showcase_shot.py" \
|
| 429 |
+
--asset=/path/to/asset/model.xml \
|
| 430 |
+
--output=<ArtifactDir>/showcase_shots/<asset_name>_turntable.mp4 \
|
| 431 |
+
--width=960 --height=720 --fps=30 --duration=8.0
|
| 432 |
+
```
|
| 433 |
+
|
| 434 |
+
### 7.5 Color/Finish Variants in Separate MJZ-Ready Directories (`build_variant_bundles`)
|
| 435 |
+
|
| 436 |
+
Every variant must be emitted into its own self-contained sibling directory (`<asset_name>_<variant>/model.xml` with its own `meshes/` and `textures/`—never `model_<variant>.xml` inside a shared folder):
|
| 437 |
+
|
| 438 |
+
```python
|
| 439 |
+
import os
|
| 440 |
+
import sys
|
| 441 |
+
|
| 442 |
+
skill_dir = os.environ.get("SKILL_DIR", "/path/to/skills/blender-creation")
|
| 443 |
+
sys.path.insert(0, os.path.join(skill_dir, "scripts"))
|
| 444 |
+
import asset_build_utils
|
| 445 |
+
|
| 446 |
+
variant_dirs = asset_build_utils.build_variant_bundles(
|
| 447 |
+
base_asset_dir=base_asset_dir,
|
| 448 |
+
parent_assets_dir=parent_assets_dir,
|
| 449 |
+
base_name=base_name,
|
| 450 |
+
variants={"<variant_name>": {...}},
|
| 451 |
+
render_variant_textures_fn=render_variant_textures,
|
| 452 |
+
)
|
| 453 |
+
```
|
| 454 |
+
|
| 455 |
+
### 7.6 Present the Asset in Interactive MuJoCo Studio (`mujoco-studio-sidecar`)
|
| 456 |
+
|
| 457 |
+
Once the asset bundle (`<asset_dir>/model.xml`, `meshes/*.obj`, `textures/*.png`) is complete and verified, present it loaded into an interactive **MuJoCo Studio** window following [`mujoco-studio-sidecar/SKILL.md`](../mujoco-studio-sidecar/SKILL.md) (and the bundled `mujoco-studio` skill):
|
| 458 |
+
|
| 459 |
+
1. **Install `mujoco.studio` (if not already present) without polluting
|
| 460 |
+
`<asset_dir>`**:
|
| 461 |
+
- Check whether `python -c "import mujoco.studio, mujoco_studio_wasm"`
|
| 462 |
+
succeeds in your active environment; if not, install `mujoco>=4.0.1` from
|
| 463 |
+
PyPI (`pip install --upgrade "mujoco>=4.0.1"` or
|
| 464 |
+
`uv pip install --upgrade "mujoco>=4.0.1"`) into an existing workspace
|
| 465 |
+
`.venv` or an external venv such as `~/.venvs/mujoco-studio` — **never**
|
| 466 |
+
create a `.venv` inside `<asset_dir>`.
|
| 467 |
+
2. **Reuse an active session or launch `studiod.py` for `<asset_dir>`**:
|
| 468 |
+
- Inspect `${TMPDIR:-/tmp}/mujoco_studio_session_$(id -u).json` first to see if a daemon is already running. When `<asset_dir>/model.xml` already exists, `studiod.py --workspace_dir=<asset_dir>` automatically detects `model.xml`, skips creating any starter Python scaffold files inside `<asset_dir>`, and writes its runtime files (`status.json`, `latest_snapshot.json`) to an out-of-workspace runtime directory:
|
| 469 |
+
|
| 470 |
+
```bash
|
| 471 |
+
SESSION_DIR="${TMPDIR:-/tmp}"
|
| 472 |
+
SESSION_FILE="${SESSION_DIR%/}/mujoco_studio_session_$(id -u).json"
|
| 473 |
+
SIDECAR_FILE="${SESSION_DIR%/}/mujoco_studio_sidecar_$(id -u).json"
|
| 474 |
+
```
|
| 475 |
+
|
| 476 |
+
- Check whether the Antigravity Node sidecar proxy (`main.mjs`) is active
|
| 477 |
+
(`$PLUGIN_DATA/sidecar.json`,
|
| 478 |
+
`$ANTIGRAVITY_EXECUTABLE_DATA_DIR/sidecar.json`, or `$SIDECAR_FILE`). If no
|
| 479 |
+
sidecar discovery file exists (for example, on Antigravity clients where
|
| 480 |
+
`enable-ui-sidecars` is disabled), add `--open_browser` so `studiod.py`
|
| 481 |
+
also opens the local WebViewer tab automatically.
|
| 482 |
+
- Launch [`studiod.py`](../mujoco-studio-sidecar/scripts/studiod.py) in the background (`IsDaemon: true`, and `BypassSandbox: true` if running inside a sandboxed shell so loopback IPC is accessible) from the **top-level / parent conversation**:
|
| 483 |
+
|
| 484 |
+
```bash
|
| 485 |
+
~/.venvs/mujoco-studio/bin/python "$PLUGIN_DIR/skills/mujoco-studio-sidecar/scripts/studiod.py" \
|
| 486 |
+
--workspace_dir=<asset_dir>
|
| 487 |
+
```
|
| 488 |
+
|
| 489 |
+
- If you created multiple variants in Step 7.5, point `--workspace_dir` at the primary asset (or pass `--scene_file=...` / restart `--workspace_dir=<variant_dir>` when switching to inspect a specific variant).
|
| 490 |
+
3. **Verify daemon connection & hot-reload**:
|
| 491 |
+
- Read `control_port` and `http_port` from `$SESSION_FILE` and query `curl --noproxy '*' -s http://127.0.0.1:<control_port>/_studio/status` to confirm `"ok": true` and `"daemon_connected": true` (note: `"daemon_connected"` and `"http_port"` are reported by `/_studio/status` and `$SESSION_FILE`, while `status_file` on disk records `"ok"` and scene load status).
|
| 492 |
+
- If you refine `model.xml`, `meshes/*.obj`, or `textures/*.png` after launching, MuJoCo Studio automatically watches and hot-reloads the model in place — re-check `/_studio/status` or `status_file` after edits to confirm reload succeeded without errors.
|
| 493 |
+
- If the user wants custom interactive controls or a live drop/manipulate testbench alongside the asset, keep `<asset_dir>/model.xml` pure and load it via `mujoco.MjSpec.from_file("<asset_dir>/model.xml")` (`spec.worldbody.add_body(...).add_freejoint()` + `self.handle.set_model(spec, watch=[...])`) in a separate Studio workspace outside `<asset_dir>`.
|
| 494 |
+
4. **Surface the interactive link(s) at the very end of the final response**:
|
| 495 |
+
- **Placement requirement**: Put `[MuJoCo Studio](sidecar://robotics/mujoco_studio/)` (and any fallback `[MuJoCo Studio Web](http://127.0.0.1:<http_port>/)` link) as the **very last thing at the end of your final response** — **after** the finished asset path, model summary, side-by-side comparison images, and turntable video. Never place the `sidecar://` link at the top or middle of the response, where the rendered pill is easy to overlook.
|
| 496 |
+
- Always include `[MuJoCo Studio](sidecar://robotics/mujoco_studio/)` (do not suppress it even if the host client does not auto-open `sidecar://` panes).
|
| 497 |
+
- If no active Node sidecar discovery file is present (so the sidecar aux-pane proxy is not running on the user's client), also include the direct local WebViewer URL `[MuJoCo Studio Web](http://127.0.0.1:<http_port>/)` (using `http_port` from `$SESSION_FILE` / `/_studio/status`) right alongside it at the end so the user can open the interactive 3D viewer in one click.
|
| 498 |
+
|
| 499 |
+
[asset-standards]: ../../rules/mujoco_asset_standards.md
|
tasks/belt-pick/environment/world/skills/blender-creation/scripts/asset_build_utils.py
ADDED
|
@@ -0,0 +1,1496 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# https://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# requires-python = ">=3.10"
|
| 17 |
+
# dependencies = [
|
| 18 |
+
# "mujoco>=3.2.0",
|
| 19 |
+
# "numpy>=1.24.0",
|
| 20 |
+
# "Pillow>=10.0.0",
|
| 21 |
+
# "scipy>=1.10.0",
|
| 22 |
+
# "trimesh>=4.0.0",
|
| 23 |
+
# ]
|
| 24 |
+
# ///
|
| 25 |
+
|
| 26 |
+
"""Zero-magic reference intake, 3D UV/normal math, CC0 scan fetch, and MJCF helpers.
|
| 27 |
+
|
| 28 |
+
Provides deterministic utilities for reference intake, 3D UV/normal synthesis,
|
| 29 |
+
and intermediate Blender diagnostics:
|
| 30 |
+
- `build_ref_contact_and_detail_sheets`: True un-lifted sRGB reference contact
|
| 31 |
+
sheets and 1:1 raw crops.
|
| 32 |
+
- `fetch_ambientcg_maps`: Fetches and caches CC0 scanned PBR material maps from
|
| 33 |
+
AmbientCG into `~/.cache/mujoco_pbr_cache` as `uint8` arrays.
|
| 34 |
+
- `rasterize_uv_world_fields`, `normal_rgb_from_3d_height_fn`,
|
| 35 |
+
`height_to_normal_rgb`, `fbm_noise_3d`, `triplanar_project_map`,
|
| 36 |
+
`dilate_uv_gutters`: Orthonormal per-texel 3D `(X, Y, Z, tangent_u, tangent_v,
|
| 37 |
+
normal)` UV rasterization (supporting positive and negative `.obj` face
|
| 38 |
+
indices) and seam-free 3D normal-map synthesis.
|
| 39 |
+
- `compute_volume_weighted_hull_masses` & `build_variant_bundles`: Convex-hull
|
| 40 |
+
volume mass allocation and XML-preserving multi-variant asset bundling.
|
| 41 |
+
- `render_blender_diagnostic_sheet`: Non-destructive 2x4 Blender Workbench
|
| 42 |
+
cavity + `Raw` `0.5 * N + 0.5` world-normal / backface sheet.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
from __future__ import annotations
|
| 46 |
+
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
sys.dont_write_bytecode = True
|
| 50 |
+
|
| 51 |
+
from collections.abc import Callable, Mapping, Sequence # pylint: disable=g-import-not-at-top
|
| 52 |
+
import io # pylint: disable=g-import-not-at-top
|
| 53 |
+
import json # pylint: disable=g-import-not-at-top
|
| 54 |
+
import math # pylint: disable=g-import-not-at-top
|
| 55 |
+
import os # pylint: disable=g-import-not-at-top
|
| 56 |
+
import re # pylint: disable=g-import-not-at-top
|
| 57 |
+
import shutil # pylint: disable=g-import-not-at-top
|
| 58 |
+
import subprocess # pylint: disable=g-import-not-at-top
|
| 59 |
+
import tempfile # pylint: disable=g-import-not-at-top
|
| 60 |
+
from typing import Any # pylint: disable=g-import-not-at-top
|
| 61 |
+
import urllib.request # pylint: disable=g-import-not-at-top
|
| 62 |
+
import xml.etree.ElementTree as ET # pylint: disable=g-import-not-at-top
|
| 63 |
+
import zipfile # pylint: disable=g-import-not-at-top
|
| 64 |
+
|
| 65 |
+
import numpy as np # pylint: disable=g-import-not-at-top
|
| 66 |
+
from PIL import Image # pylint: disable=g-import-not-at-top
|
| 67 |
+
from PIL import ImageDraw # pylint: disable=g-import-not-at-top
|
| 68 |
+
from PIL import ImageFilter # pylint: disable=g-import-not-at-top
|
| 69 |
+
from PIL import ImageFont # pylint: disable=g-import-not-at-top
|
| 70 |
+
|
| 71 |
+
# Register short (`asset_build_utils`) module name so callers share a single
|
| 72 |
+
# loaded module instance regardless of import path.
|
| 73 |
+
_THIS_MOD = sys.modules.get(__name__)
|
| 74 |
+
if _THIS_MOD is not None:
|
| 75 |
+
sys.modules.setdefault("asset_build_utils", _THIS_MOD)
|
| 76 |
+
|
| 77 |
+
_NDIMAGE_MOD: Any = None
|
| 78 |
+
_SPATIAL_MOD: Any = None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _get_ndimage() -> Any:
|
| 82 |
+
"""Lazily imports `scipy.ndimage` on first use (~0.15s faster 2D sheet intake)."""
|
| 83 |
+
global _NDIMAGE_MOD # pylint: disable=global-statement
|
| 84 |
+
if _NDIMAGE_MOD is None:
|
| 85 |
+
from scipy import ndimage as _ndi # pylint: disable=g-import-not-at-top
|
| 86 |
+
|
| 87 |
+
_NDIMAGE_MOD = _ndi
|
| 88 |
+
return _NDIMAGE_MOD
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _get_spatial() -> Any:
|
| 92 |
+
"""Lazily imports `scipy.spatial` on first use."""
|
| 93 |
+
global _SPATIAL_MOD # pylint: disable=global-statement
|
| 94 |
+
if _SPATIAL_MOD is None:
|
| 95 |
+
from scipy import spatial as _sp # pylint: disable=g-import-not-at-top
|
| 96 |
+
|
| 97 |
+
_SPATIAL_MOD = _sp
|
| 98 |
+
return _SPATIAL_MOD
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def __getattr__(name: str) -> Any:
|
| 102 |
+
if name == "ndimage":
|
| 103 |
+
return _get_ndimage()
|
| 104 |
+
if name == "spatial":
|
| 105 |
+
return _get_spatial()
|
| 106 |
+
if name == "mujoco":
|
| 107 |
+
try:
|
| 108 |
+
import mujoco as _mj # pylint: disable=g-import-not-at-top
|
| 109 |
+
|
| 110 |
+
return _mj
|
| 111 |
+
except ImportError:
|
| 112 |
+
return None
|
| 113 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _load_label_font(
|
| 117 |
+
size: int = 13,
|
| 118 |
+
) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
|
| 119 |
+
"""Loads a readable TrueType label font or falls back to default."""
|
| 120 |
+
for font_path in (
|
| 121 |
+
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf",
|
| 122 |
+
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
| 123 |
+
"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
|
| 124 |
+
):
|
| 125 |
+
if os.path.exists(font_path):
|
| 126 |
+
try:
|
| 127 |
+
return ImageFont.truetype(font_path, size=size)
|
| 128 |
+
except OSError:
|
| 129 |
+
pass
|
| 130 |
+
return ImageFont.load_default()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _save_inspection_image(
|
| 134 |
+
sheet: Image.Image,
|
| 135 |
+
out_path: str,
|
| 136 |
+
*,
|
| 137 |
+
max_long_edge: int | None = None,
|
| 138 |
+
jpeg_quality: int = 92,
|
| 139 |
+
) -> None:
|
| 140 |
+
"""Saves an inspection sheet at 1:1 caller resolution (unless `max_long_edge` is set)."""
|
| 141 |
+
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
| 142 |
+
w, h = sheet.size
|
| 143 |
+
if max_long_edge is not None and max(w, h) > max_long_edge:
|
| 144 |
+
scale = float(max_long_edge) / float(max(w, h))
|
| 145 |
+
sheet = sheet.resize(
|
| 146 |
+
(max(1, int(round(w * scale))), max(1, int(round(h * scale)))),
|
| 147 |
+
Image.Resampling.LANCZOS,
|
| 148 |
+
)
|
| 149 |
+
if out_path.lower().endswith((".jpg", ".jpeg")):
|
| 150 |
+
sheet.convert("RGB").save(
|
| 151 |
+
out_path,
|
| 152 |
+
quality=int(jpeg_quality),
|
| 153 |
+
subsampling=0,
|
| 154 |
+
optimize=True,
|
| 155 |
+
)
|
| 156 |
+
else:
|
| 157 |
+
sheet.save(out_path, optimize=True)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def height_to_normal_rgb(
|
| 161 |
+
height_map: np.ndarray,
|
| 162 |
+
strength: float = 3.5,
|
| 163 |
+
*,
|
| 164 |
+
smooth_sigma: float = 0.0,
|
| 165 |
+
valid_mask: np.ndarray | None = None,
|
| 166 |
+
) -> np.ndarray:
|
| 167 |
+
"""Converts a 2D height map into an 8-bit OpenGL tangent-space normal map.
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
height_map: 2D float array of surface elevation values.
|
| 171 |
+
strength: Gradient scale factor controlling normal-map relief intensity.
|
| 172 |
+
smooth_sigma: Optional Gaussian smoothing sigma in pixels applied before
|
| 173 |
+
gradient differentiation (`0.0` default preserves fine intentional grain
|
| 174 |
+
and crisp micro-relief without blurring).
|
| 175 |
+
valid_mask: Optional `(H, W)` boolean UV-island mask. When provided, dilates
|
| 176 |
+
valid island heights into empty UV gutters before smoothing and gradient
|
| 177 |
+
differentiation so `0.0` gutter backgrounds do not create artificial seam
|
| 178 |
+
cliffs.
|
| 179 |
+
|
| 180 |
+
Returns:
|
| 181 |
+
`(H, W, 3)` `uint8` RGB array with flat normal encoded as `(128, 128, 255)`.
|
| 182 |
+
"""
|
| 183 |
+
height_f32 = np.asarray(height_map, dtype=np.float32)
|
| 184 |
+
if valid_mask is not None:
|
| 185 |
+
height_f32 = dilate_uv_gutters(height_f32, valid_mask, max_dist_px=12)
|
| 186 |
+
if smooth_sigma > 0.0:
|
| 187 |
+
height_f32 = _get_ndimage().gaussian_filter(
|
| 188 |
+
height_f32, sigma=float(smooth_sigma), mode="wrap"
|
| 189 |
+
)
|
| 190 |
+
grad_y, grad_x = np.gradient(height_f32)
|
| 191 |
+
norm_x = -grad_x * float(strength)
|
| 192 |
+
norm_y = grad_y * float(strength)
|
| 193 |
+
norm_z = np.ones_like(height_f32)
|
| 194 |
+
inv_len = 1.0 / np.maximum(
|
| 195 |
+
np.sqrt(norm_x * norm_x + norm_y * norm_y + norm_z * norm_z), 1e-8
|
| 196 |
+
)
|
| 197 |
+
rgb = np.stack(
|
| 198 |
+
[
|
| 199 |
+
(norm_x * inv_len * 0.5 + 0.5) * 255.0,
|
| 200 |
+
(norm_y * inv_len * 0.5 + 0.5) * 255.0,
|
| 201 |
+
(norm_z * inv_len * 0.5 + 0.5) * 255.0,
|
| 202 |
+
],
|
| 203 |
+
axis=-1,
|
| 204 |
+
)
|
| 205 |
+
return np.clip(np.round(rgb), 0, 255).astype(np.uint8)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _parse_obj_vertices(obj_path: str) -> np.ndarray:
|
| 209 |
+
"""Parses 3D vertex coordinates (`v x y z`) from a Wavefront `.obj` file."""
|
| 210 |
+
verts: list[list[float]] = []
|
| 211 |
+
with open(obj_path, "r", encoding="utf-8") as obj_file:
|
| 212 |
+
for raw_line in obj_file:
|
| 213 |
+
line = raw_line.split("#", 1)[0].strip()
|
| 214 |
+
if not line:
|
| 215 |
+
continue
|
| 216 |
+
parts = line.split()
|
| 217 |
+
if parts[0] == "v" and len(parts) >= 4:
|
| 218 |
+
verts.append([float(parts[1]), float(parts[2]), float(parts[3])])
|
| 219 |
+
if not verts:
|
| 220 |
+
return np.zeros((0, 3), dtype=np.float64)
|
| 221 |
+
return np.asarray(verts, dtype=np.float64)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def compute_volume_weighted_hull_masses(
|
| 225 |
+
mesh_dir: str,
|
| 226 |
+
col_names: Sequence[str],
|
| 227 |
+
total_mass_kg: float,
|
| 228 |
+
*,
|
| 229 |
+
density_weights: Mapping[str, float] | None = None,
|
| 230 |
+
) -> dict[str, float]:
|
| 231 |
+
"""Computes volume- (and optional material-density-) weighted hull masses.
|
| 232 |
+
|
| 233 |
+
Args:
|
| 234 |
+
mesh_dir: Directory containing the collision `.obj` files.
|
| 235 |
+
col_names: Sequence of collision mesh names (with or without `.obj` suffix).
|
| 236 |
+
total_mass_kg: Target total mass in kilograms across all listed hulls.
|
| 237 |
+
density_weights: Optional mapping from hull name (or stem without `.obj`) to
|
| 238 |
+
positive relative material density multiplier (`1.0` default per hull).
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
Dict mapping each entry in `col_names` to its assigned mass in kilograms.
|
| 242 |
+
"""
|
| 243 |
+
weighted_vols: dict[str, float] = {}
|
| 244 |
+
for name in col_names:
|
| 245 |
+
fname = name if name.endswith(".obj") else f"{name}.obj"
|
| 246 |
+
stem = fname[:-4] if fname.endswith(".obj") else fname
|
| 247 |
+
obj_path = os.path.join(mesh_dir, fname)
|
| 248 |
+
verts = _parse_obj_vertices(obj_path)
|
| 249 |
+
vol = 1e-9
|
| 250 |
+
if len(verts) >= 4:
|
| 251 |
+
sp = _get_spatial()
|
| 252 |
+
try:
|
| 253 |
+
hull = sp.ConvexHull(verts)
|
| 254 |
+
vol = max(float(hull.volume), 1e-9)
|
| 255 |
+
except sp.QhullError:
|
| 256 |
+
span = np.ptp(verts, axis=0)
|
| 257 |
+
vol = max(float(np.prod(np.maximum(span, 1e-4))), 1e-9)
|
| 258 |
+
d_mult = 1.0
|
| 259 |
+
if density_weights:
|
| 260 |
+
if name in density_weights:
|
| 261 |
+
d_mult = max(float(density_weights[name]), 1e-6)
|
| 262 |
+
elif stem in density_weights:
|
| 263 |
+
d_mult = max(float(density_weights[stem]), 1e-6)
|
| 264 |
+
weighted_vols[name] = vol * d_mult
|
| 265 |
+
|
| 266 |
+
total_wvol = sum(weighted_vols.values())
|
| 267 |
+
if total_wvol <= 0.0:
|
| 268 |
+
even_mass = float(total_mass_kg) / max(len(col_names), 1)
|
| 269 |
+
return {name: round(even_mass, 6) for name in col_names}
|
| 270 |
+
|
| 271 |
+
return {
|
| 272 |
+
name: float(total_mass_kg) * (wvol / total_wvol)
|
| 273 |
+
for name, wvol in weighted_vols.items()
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def build_variant_bundles(
|
| 278 |
+
base_asset_dir: str,
|
| 279 |
+
parent_assets_dir: str,
|
| 280 |
+
base_name: str,
|
| 281 |
+
variants: Mapping[str, Mapping[str, Any]],
|
| 282 |
+
render_variant_textures_fn: Callable[[str, Mapping[str, Any]], None],
|
| 283 |
+
) -> list[str]:
|
| 284 |
+
"""Emits a self-contained `<base_name>_<variant>/` directory for each variant.
|
| 285 |
+
|
| 286 |
+
Skips redundant `.obj`/`.stl` file copies when the destination
|
| 287 |
+
file already exists with matching byte size and modification time.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
base_asset_dir: Path to the primary `<base_name>/` asset directory.
|
| 291 |
+
parent_assets_dir: Parent `assets/` directory where sibling variants live.
|
| 292 |
+
base_name: Base asset name.
|
| 293 |
+
variants: Mapping from variant suffix to a palette dict.
|
| 294 |
+
render_variant_textures_fn: Callback `fn(v_textures_dir, palette)` that
|
| 295 |
+
writes the variant's PNG textures into `v_textures_dir`.
|
| 296 |
+
|
| 297 |
+
Returns:
|
| 298 |
+
List of created variant directory paths.
|
| 299 |
+
"""
|
| 300 |
+
base_xml = os.path.join(base_asset_dir, "model.xml")
|
| 301 |
+
base_meshes = os.path.join(base_asset_dir, "meshes")
|
| 302 |
+
out_dirs: list[str] = []
|
| 303 |
+
|
| 304 |
+
for variant_key, palette in variants.items():
|
| 305 |
+
variant_name = f"{base_name}_{variant_key}"
|
| 306 |
+
v_dir = os.path.join(parent_assets_dir, variant_name)
|
| 307 |
+
v_meshes = os.path.join(v_dir, "meshes")
|
| 308 |
+
v_textures = os.path.join(v_dir, "textures")
|
| 309 |
+
os.makedirs(v_meshes, exist_ok=True)
|
| 310 |
+
os.makedirs(v_textures, exist_ok=True)
|
| 311 |
+
|
| 312 |
+
if os.path.abspath(base_meshes) != os.path.abspath(v_meshes):
|
| 313 |
+
for fname in os.listdir(base_meshes):
|
| 314 |
+
if fname.endswith(".obj") or fname.endswith(".stl"):
|
| 315 |
+
src_p = os.path.join(base_meshes, fname)
|
| 316 |
+
dst_p = os.path.join(v_meshes, fname)
|
| 317 |
+
need_copy = True
|
| 318 |
+
if os.path.exists(dst_p):
|
| 319 |
+
if os.path.getsize(src_p) == os.path.getsize(
|
| 320 |
+
dst_p
|
| 321 |
+
) and os.path.getmtime(src_p) <= os.path.getmtime(dst_p):
|
| 322 |
+
need_copy = False
|
| 323 |
+
if need_copy:
|
| 324 |
+
shutil.copy2(src_p, dst_p)
|
| 325 |
+
|
| 326 |
+
render_variant_textures_fn(v_textures, palette)
|
| 327 |
+
|
| 328 |
+
tree = ET.parse(base_xml)
|
| 329 |
+
root = tree.getroot()
|
| 330 |
+
root.set("model", variant_name)
|
| 331 |
+
worldbody = root.find("worldbody")
|
| 332 |
+
if worldbody is not None:
|
| 333 |
+
first_body = worldbody.find("body")
|
| 334 |
+
if first_body is not None:
|
| 335 |
+
first_body.set("name", variant_name)
|
| 336 |
+
|
| 337 |
+
v_xml = os.path.join(v_dir, "model.xml")
|
| 338 |
+
ET.indent(tree, space=" ")
|
| 339 |
+
tree.write(v_xml, encoding="unicode", xml_declaration=False)
|
| 340 |
+
with open(v_xml, "a", encoding="utf-8") as xml_file:
|
| 341 |
+
xml_file.write("\n")
|
| 342 |
+
out_dirs.append(v_dir)
|
| 343 |
+
|
| 344 |
+
return out_dirs
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def _resolve_box_to_px(
|
| 348 |
+
box: Sequence[float],
|
| 349 |
+
width: int,
|
| 350 |
+
height: int,
|
| 351 |
+
*,
|
| 352 |
+
min_span_px: float = 1.0,
|
| 353 |
+
) -> tuple[float, float, float, float]:
|
| 354 |
+
"""Resolves a pixel `(> 1.5)` or normalized `[0..1]` `(x0, y0, x1, y1)` box to pixels."""
|
| 355 |
+
b0, b1, b2, b3 = [float(c) for c in box]
|
| 356 |
+
if max(abs(b0), abs(b1), abs(b2), abs(b3)) > 1.5:
|
| 357 |
+
raw_x0, raw_y0, raw_x1, raw_y1 = b0, b1, b2, b3
|
| 358 |
+
else:
|
| 359 |
+
raw_x0, raw_y0 = b0 * float(width), b1 * float(height)
|
| 360 |
+
raw_x1, raw_y1 = b2 * float(width), b3 * float(height)
|
| 361 |
+
xa, xb = min(raw_x0, raw_x1), max(raw_x0, raw_x1)
|
| 362 |
+
ya, yb = min(raw_y0, raw_y1), max(raw_y0, raw_y1)
|
| 363 |
+
span_x = min(float(min_span_px), float(max(width, 1)))
|
| 364 |
+
span_y = min(float(min_span_px), float(max(height, 1)))
|
| 365 |
+
ox0 = max(0.0, min(float(width) - span_x, xa))
|
| 366 |
+
oy0 = max(0.0, min(float(height) - span_y, ya))
|
| 367 |
+
ox1 = max(ox0 + span_x, min(float(width), xb))
|
| 368 |
+
oy1 = max(oy0 + span_y, min(float(height), yb))
|
| 369 |
+
return (ox0, oy0, ox1, oy1)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def build_ref_contact_and_detail_sheets(
|
| 373 |
+
ref_paths: Sequence[
|
| 374 |
+
str
|
| 375 |
+
| tuple[str, str]
|
| 376 |
+
| tuple[str, str, tuple[float, float, float, float]]
|
| 377 |
+
],
|
| 378 |
+
detail_crops: Sequence[tuple[Any, ...]],
|
| 379 |
+
out_contact_png: str,
|
| 380 |
+
out_details_png: str,
|
| 381 |
+
*,
|
| 382 |
+
raw_crops_dir: str | None = None,
|
| 383 |
+
rgb_sample_boxes: (
|
| 384 |
+
Mapping[str, tuple[str, tuple[float, float, float, float]]]
|
| 385 |
+
| Sequence[tuple[str, str, tuple[float, float, float, float]]]
|
| 386 |
+
| None
|
| 387 |
+
) = None,
|
| 388 |
+
cols: int = 3,
|
| 389 |
+
cell_size: int = 440,
|
| 390 |
+
include_shadow_lift: bool = False,
|
| 391 |
+
) -> dict[str, Any]:
|
| 392 |
+
"""Generates `ref_contact_sheet`, true-sRGB `ref_details_grid`, and optional 1:1 `raw_crops_dir`.
|
| 393 |
+
|
| 394 |
+
Outputs true un-lifted sRGB detail crops on `out_details_png` by default
|
| 395 |
+
(`include_shadow_lift=False`) so shadow contrast inside recessed pockets and
|
| 396 |
+
grooves is never washed out.
|
| 397 |
+
|
| 398 |
+
Args:
|
| 399 |
+
ref_paths: Sequence of reference image paths (`str`) or `(label, img_path)`
|
| 400 |
+
tuples to tile into the contact sheet.
|
| 401 |
+
detail_crops: Sequence of `(label, img_path, (u0, v0, u1, v1))` normalized
|
| 402 |
+
`[0..1]` or source-pixel crops to tile into `out_details_png`.
|
| 403 |
+
out_contact_png: Output path for the overview contact sheet.
|
| 404 |
+
out_details_png: Output path for the detail crop grid.
|
| 405 |
+
raw_crops_dir: Optional directory where each `detail_crops` box is also
|
| 406 |
+
saved at 1:1 native source resolution (zero resize, zero tone-curve
|
| 407 |
+
filtering).
|
| 408 |
+
rgb_sample_boxes: Optional mapping `name -> (img_path, (u0, v0, u1, v1))` or
|
| 409 |
+
sequence of `(name, img_path, (u0, v0, u1, v1))` tuples for sampling `[25,
|
| 410 |
+
50, 75]` RGB percentiles.
|
| 411 |
+
cols: Number of grid columns per sheet.
|
| 412 |
+
cell_size: Pixel width and height of each cell.
|
| 413 |
+
include_shadow_lift: If True, also emits `[SHADOW-LIFT]` companion tiles for
|
| 414 |
+
dark crops (`False` default preserves true un-lifted sRGB only).
|
| 415 |
+
|
| 416 |
+
Returns:
|
| 417 |
+
Dict with `"contact_png"`, `"details_png"`, `"raw_crop_paths"`, and
|
| 418 |
+
`"rgb_percentiles"`.
|
| 419 |
+
"""
|
| 420 |
+
font = _load_label_font(13)
|
| 421 |
+
pad = 8
|
| 422 |
+
hdr_h = 26
|
| 423 |
+
|
| 424 |
+
def _render_grid(
|
| 425 |
+
items: Sequence[tuple[str, Image.Image]], out_path: str
|
| 426 |
+
) -> None:
|
| 427 |
+
if not items:
|
| 428 |
+
return
|
| 429 |
+
n_cols = min(cols, len(items))
|
| 430 |
+
n_rows = (len(items) + n_cols - 1) // n_cols
|
| 431 |
+
sheet_w = n_cols * cell_size + (n_cols + 1) * pad
|
| 432 |
+
sheet_h = n_rows * (cell_size + hdr_h) + (n_rows + 1) * pad
|
| 433 |
+
sheet = Image.new("RGB", (sheet_w, sheet_h), (18, 22, 30))
|
| 434 |
+
draw = ImageDraw.Draw(sheet)
|
| 435 |
+
for idx, (label, img) in enumerate(items):
|
| 436 |
+
row_i = idx // n_cols
|
| 437 |
+
col_i = idx % n_cols
|
| 438 |
+
x0 = pad + col_i * (cell_size + pad)
|
| 439 |
+
y0 = pad + row_i * (cell_size + hdr_h + pad)
|
| 440 |
+
draw.rectangle([x0, y0, x0 + cell_size, y0 + hdr_h], fill=(32, 48, 68))
|
| 441 |
+
draw.text((x0 + 8, y0 + 5), label[:48], fill=(242, 246, 252), font=font)
|
| 442 |
+
iw, ih = img.size
|
| 443 |
+
scale = min(cell_size / max(iw, 1), cell_size / max(ih, 1))
|
| 444 |
+
nw = max(1, int(round(iw * scale)))
|
| 445 |
+
nh = max(1, int(round(ih * scale)))
|
| 446 |
+
resized = img.resize((nw, nh), Image.Resampling.LANCZOS)
|
| 447 |
+
cell_bg = Image.new("RGB", (cell_size, cell_size), (245, 245, 247))
|
| 448 |
+
cell_bg.paste(resized, ((cell_size - nw) // 2, (cell_size - nh) // 2))
|
| 449 |
+
sheet.paste(cell_bg, (x0, y0 + hdr_h))
|
| 450 |
+
_save_inspection_image(sheet, out_path)
|
| 451 |
+
|
| 452 |
+
contact_items: list[tuple[str, Image.Image]] = []
|
| 453 |
+
contact_meta: list[dict[str, Any]] = []
|
| 454 |
+
for idx, entry in enumerate(ref_paths):
|
| 455 |
+
crop_norm = None
|
| 456 |
+
if isinstance(entry, (tuple, list)) and len(entry) == 3:
|
| 457 |
+
lbl, ref_p, crop_norm = str(entry[0]), str(entry[1]), entry[2]
|
| 458 |
+
elif isinstance(entry, (tuple, list)) and len(entry) == 2:
|
| 459 |
+
first, second = str(entry[0]), str(entry[1])
|
| 460 |
+
if os.path.exists(second):
|
| 461 |
+
lbl, ref_p = first, second
|
| 462 |
+
else:
|
| 463 |
+
ref_p, lbl = first, second
|
| 464 |
+
else:
|
| 465 |
+
ref_p = str(entry)
|
| 466 |
+
lbl = f"[{idx}] {os.path.basename(ref_p)}"
|
| 467 |
+
if os.path.exists(ref_p):
|
| 468 |
+
raw_im = Image.open(ref_p)
|
| 469 |
+
im = raw_im.convert("RGB")
|
| 470 |
+
orig_w, orig_h = im.width, im.height
|
| 471 |
+
box_px = None
|
| 472 |
+
if crop_norm is not None and len(crop_norm) == 4:
|
| 473 |
+
ox0, oy0, ox1, oy1 = _resolve_box_to_px(
|
| 474 |
+
crop_norm, orig_w, orig_h, min_span_px=8.0
|
| 475 |
+
)
|
| 476 |
+
x0 = max(0, min(orig_w - 1, int(round(ox0))))
|
| 477 |
+
y0 = max(0, min(orig_h - 1, int(round(oy0))))
|
| 478 |
+
x1 = min(orig_w, max(x0 + 1, int(round(ox1))))
|
| 479 |
+
y1 = min(orig_h, max(y0 + 1, int(round(oy1))))
|
| 480 |
+
im = im.crop((x0, y0, x1, y1))
|
| 481 |
+
box_px = [x0, y0, x1, y1]
|
| 482 |
+
contact_items.append((f"{lbl} ({orig_w}x{orig_h})", im))
|
| 483 |
+
contact_meta.append({
|
| 484 |
+
"label": lbl,
|
| 485 |
+
"path": os.path.abspath(ref_p),
|
| 486 |
+
"image_size_px": [orig_w, orig_h],
|
| 487 |
+
"has_explicit_box": box_px is not None,
|
| 488 |
+
"obj_bbox_px": box_px,
|
| 489 |
+
})
|
| 490 |
+
_render_grid(contact_items, out_contact_png)
|
| 491 |
+
|
| 492 |
+
detail_items: list[tuple[str, Image.Image]] = []
|
| 493 |
+
raw_crop_paths: list[str] = []
|
| 494 |
+
if raw_crops_dir:
|
| 495 |
+
os.makedirs(raw_crops_dir, exist_ok=True)
|
| 496 |
+
for idx, crop_entry in enumerate(detail_crops):
|
| 497 |
+
a, b, (u0, v0, u1, v1) = crop_entry[0], crop_entry[1], crop_entry[2]
|
| 498 |
+
if os.path.exists(str(b)):
|
| 499 |
+
lbl, img_p = str(a), str(b)
|
| 500 |
+
else:
|
| 501 |
+
img_p, lbl = str(a), str(b)
|
| 502 |
+
if os.path.exists(img_p):
|
| 503 |
+
im = Image.open(img_p).convert("RGB")
|
| 504 |
+
iw, ih = im.size
|
| 505 |
+
x0, y0, x1, y1 = _resolve_box_to_px(
|
| 506 |
+
(u0, v0, u1, v1), iw, ih, min_span_px=1.0
|
| 507 |
+
)
|
| 508 |
+
slug_chars = [ch.lower() if ch.isalnum() else "_" for ch in lbl]
|
| 509 |
+
slug = "_".join(s for s in "".join(slug_chars).split("_") if s)
|
| 510 |
+
slug = re.sub(r"^(\d+_)+", "", slug)[:42]
|
| 511 |
+
if raw_crops_dir:
|
| 512 |
+
rx0 = max(0, min(iw - 1, int(round(x0))))
|
| 513 |
+
ry0 = max(0, min(ih - 1, int(round(y0))))
|
| 514 |
+
rx1 = max(rx0 + 1, min(iw, int(round(x1))))
|
| 515 |
+
ry1 = max(ry0 + 1, min(ih, int(round(y1))))
|
| 516 |
+
raw_out = os.path.join(
|
| 517 |
+
raw_crops_dir, f"{idx + 1:02d}_{slug or 'crop'}.jpg"
|
| 518 |
+
)
|
| 519 |
+
im.crop((rx0, ry0, rx1, ry1)).save(
|
| 520 |
+
raw_out, quality=94, subsampling=0, optimize=True
|
| 521 |
+
)
|
| 522 |
+
raw_crop_paths.append(raw_out)
|
| 523 |
+
cx, cy = 0.5 * (x0 + x1), 0.5 * (y0 + y1)
|
| 524 |
+
side = min(max(abs(x1 - x0), abs(y1 - y0), 16.0), float(min(iw, ih)))
|
| 525 |
+
sx0 = float(np.clip(cx - 0.5 * side, 0.0, max(0.0, iw - side)))
|
| 526 |
+
sy0 = float(np.clip(cy - 0.5 * side, 0.0, max(0.0, ih - side)))
|
| 527 |
+
iside = max(1, int(round(side)))
|
| 528 |
+
ix0, iy0 = int(round(sx0)), int(round(sy0))
|
| 529 |
+
box = (ix0, iy0, min(iw, ix0 + iside), min(ih, iy0 + iside))
|
| 530 |
+
crop_im = im.crop(box).resize(
|
| 531 |
+
(cell_size, cell_size), Image.Resampling.LANCZOS
|
| 532 |
+
)
|
| 533 |
+
detail_items.append((f"#{idx + 1}: {lbl}", crop_im))
|
| 534 |
+
|
| 535 |
+
if include_shadow_lift:
|
| 536 |
+
crop_arr = np.asarray(crop_im, dtype=np.float32)
|
| 537 |
+
luma = (
|
| 538 |
+
0.299 * crop_arr[..., 0]
|
| 539 |
+
+ 0.587 * crop_arr[..., 1]
|
| 540 |
+
+ 0.114 * crop_arr[..., 2]
|
| 541 |
+
)
|
| 542 |
+
p10, p22, p50, p90 = np.percentile(luma, [10, 22, 50, 90])
|
| 543 |
+
if p22 < 100.0 or p50 < 105.0 or (p90 - p10) < 95.0:
|
| 544 |
+
arr01 = np.clip(crop_arr / 255.0, 0.0, 1.0)
|
| 545 |
+
v_max = np.max(arr01, axis=-1, keepdims=True)
|
| 546 |
+
lifted = np.clip(arr01 * (1.26 / (v_max + 0.26)), 0.0, 1.0)
|
| 547 |
+
enh_im = Image.fromarray(
|
| 548 |
+
np.round(lifted * 255.0).astype(np.uint8), mode="RGB"
|
| 549 |
+
)
|
| 550 |
+
detail_items.append((f"#{idx + 1}b: {lbl} [SHADOW-LIFT]", enh_im))
|
| 551 |
+
_render_grid(detail_items, out_details_png)
|
| 552 |
+
|
| 553 |
+
rgb_stats: dict[str, dict[str, tuple[int, int, int]]] = {}
|
| 554 |
+
if rgb_sample_boxes:
|
| 555 |
+
if isinstance(rgb_sample_boxes, Mapping):
|
| 556 |
+
sample_iter = [(k, v[0], v[1]) for k, v in rgb_sample_boxes.items()]
|
| 557 |
+
else:
|
| 558 |
+
sample_iter = list(rgb_sample_boxes)
|
| 559 |
+
for mat_name, img_p, (u0, v0, u1, v1) in sample_iter:
|
| 560 |
+
if os.path.exists(img_p):
|
| 561 |
+
arr = np.asarray(Image.open(img_p).convert("RGB"), dtype=np.float32)
|
| 562 |
+
ih, iw = arr.shape[:2]
|
| 563 |
+
ox0, oy0, ox1, oy1 = _resolve_box_to_px(
|
| 564 |
+
(u0, v0, u1, v1), iw, ih, min_span_px=1.0
|
| 565 |
+
)
|
| 566 |
+
ix0 = max(0, min(iw - 1, int(round(ox0))))
|
| 567 |
+
iy0 = max(0, min(ih - 1, int(round(oy0))))
|
| 568 |
+
ix1 = max(ix0 + 1, min(iw, int(round(ox1))))
|
| 569 |
+
iy1 = max(iy0 + 1, min(ih, int(round(oy1))))
|
| 570 |
+
patch = arr[iy0:iy1, ix0:ix1]
|
| 571 |
+
if patch.size > 0:
|
| 572 |
+
p25, p50, p75 = np.percentile(patch, [25, 50, 75], axis=(0, 1))
|
| 573 |
+
rgb_stats[str(mat_name)] = {
|
| 574 |
+
"p25": (
|
| 575 |
+
int(round(p25[0])),
|
| 576 |
+
int(round(p25[1])),
|
| 577 |
+
int(round(p25[2])),
|
| 578 |
+
),
|
| 579 |
+
"p50": (
|
| 580 |
+
int(round(p50[0])),
|
| 581 |
+
int(round(p50[1])),
|
| 582 |
+
int(round(p50[2])),
|
| 583 |
+
),
|
| 584 |
+
"p75": (
|
| 585 |
+
int(round(p75[0])),
|
| 586 |
+
int(round(p75[1])),
|
| 587 |
+
int(round(p75[2])),
|
| 588 |
+
),
|
| 589 |
+
}
|
| 590 |
+
print(
|
| 591 |
+
f"[RGB Sample] {mat_name}: p25={rgb_stats[str(mat_name)]['p25']},"
|
| 592 |
+
f" p50={rgb_stats[str(mat_name)]['p50']},"
|
| 593 |
+
f" p75={rgb_stats[str(mat_name)]['p75']}"
|
| 594 |
+
)
|
| 595 |
+
result: dict[str, Any] = {
|
| 596 |
+
"contact_png": out_contact_png,
|
| 597 |
+
"details_png": out_details_png,
|
| 598 |
+
"raw_crop_paths": raw_crop_paths,
|
| 599 |
+
"rgb_percentiles": rgb_stats,
|
| 600 |
+
}
|
| 601 |
+
result.update(rgb_stats)
|
| 602 |
+
return result
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
_BLENDER_DIAG_SCRIPT = """
|
| 606 |
+
import sys
|
| 607 |
+
sys.dont_write_bytecode = True
|
| 608 |
+
|
| 609 |
+
import json, math, os
|
| 610 |
+
import bpy, mathutils
|
| 611 |
+
|
| 612 |
+
cfg = json.loads(sys.argv[-1])
|
| 613 |
+
out_dir = cfg["tmp_dir"]
|
| 614 |
+
res = int(cfg.get("panel_size", 420))
|
| 615 |
+
|
| 616 |
+
vis_objs = []
|
| 617 |
+
for obj in list(bpy.data.objects):
|
| 618 |
+
if obj.type != "MESH":
|
| 619 |
+
obj.hide_render = True
|
| 620 |
+
continue
|
| 621 |
+
low_name = obj.name.lower()
|
| 622 |
+
is_col = (
|
| 623 |
+
low_name.endswith("_col")
|
| 624 |
+
or "_col_" in low_name
|
| 625 |
+
or "_hull_" in low_name
|
| 626 |
+
or low_name.endswith("_hull")
|
| 627 |
+
) and not low_name.endswith("_vis") and "_vis_" not in low_name
|
| 628 |
+
if is_col:
|
| 629 |
+
obj.hide_render = True
|
| 630 |
+
continue
|
| 631 |
+
obj.hide_render = False
|
| 632 |
+
vis_objs.append(obj)
|
| 633 |
+
|
| 634 |
+
bpy.context.view_layer.update()
|
| 635 |
+
bmin = mathutils.Vector((1e9, 1e9, 1e9))
|
| 636 |
+
bmax = mathutils.Vector((-1e9, -1e9, -1e9))
|
| 637 |
+
for obj in vis_objs:
|
| 638 |
+
for corner in obj.bound_box:
|
| 639 |
+
wc = obj.matrix_world @ mathutils.Vector(corner)
|
| 640 |
+
for i in range(3):
|
| 641 |
+
bmin[i] = min(bmin[i], wc[i])
|
| 642 |
+
bmax[i] = max(bmax[i], wc[i])
|
| 643 |
+
if bmin[0] > bmax[0]:
|
| 644 |
+
bmin = mathutils.Vector((-0.05, -0.05, 0.0))
|
| 645 |
+
bmax = mathutils.Vector((0.05, 0.05, 0.10))
|
| 646 |
+
|
| 647 |
+
center = 0.5 * (bmin + bmax)
|
| 648 |
+
span = max((bmax - bmin).length, 1e-3)
|
| 649 |
+
half_span = 0.5 * span
|
| 650 |
+
|
| 651 |
+
cam_data = bpy.data.cameras.new("_DiagCam")
|
| 652 |
+
cam_data.lens = 50.0
|
| 653 |
+
fov = max(float(cam_data.angle), 0.1)
|
| 654 |
+
dist = (half_span / math.tan(0.5 * fov)) * 1.18 + 0.5 * span
|
| 655 |
+
cam_data.clip_start = max(1e-4, min(0.001, dist * 0.01))
|
| 656 |
+
cam_data.clip_end = max(100.0, dist * 10.0)
|
| 657 |
+
cam_obj = bpy.data.objects.new("_DiagCam", cam_data)
|
| 658 |
+
bpy.context.scene.collection.objects.link(cam_obj)
|
| 659 |
+
bpy.context.scene.camera = cam_obj
|
| 660 |
+
|
| 661 |
+
scene = bpy.context.scene
|
| 662 |
+
scene.render.resolution_x = res
|
| 663 |
+
scene.render.resolution_y = res
|
| 664 |
+
scene.render.resolution_percentage = 100
|
| 665 |
+
scene.render.image_settings.file_format = "PNG"
|
| 666 |
+
scene.render.film_transparent = True
|
| 667 |
+
|
| 668 |
+
views = [
|
| 669 |
+
("front", 0.0, 12.0),
|
| 670 |
+
("right", -90.0, 12.0),
|
| 671 |
+
("top", -90.0, 88.0),
|
| 672 |
+
("hero_iso", -52.0, 26.0),
|
| 673 |
+
]
|
| 674 |
+
|
| 675 |
+
def place_cam(az_deg, el_deg):
|
| 676 |
+
az = math.radians(az_deg)
|
| 677 |
+
el = math.radians(el_deg)
|
| 678 |
+
pos = center + mathutils.Vector((
|
| 679 |
+
dist * math.cos(el) * math.cos(az),
|
| 680 |
+
dist * math.cos(el) * math.sin(az),
|
| 681 |
+
dist * math.sin(el),
|
| 682 |
+
))
|
| 683 |
+
cam_obj.location = pos
|
| 684 |
+
direction = center - pos
|
| 685 |
+
cam_obj.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
|
| 686 |
+
|
| 687 |
+
# Row 1: BLENDER_WORKBENCH with Per-Object Colors + Ridge/Valley Cavity Shading
|
| 688 |
+
_OBJ_PALETTE = [
|
| 689 |
+
(0.84, 0.76, 0.68, 1.0),
|
| 690 |
+
(0.64, 0.76, 0.86, 1.0),
|
| 691 |
+
(0.72, 0.84, 0.72, 1.0),
|
| 692 |
+
(0.86, 0.70, 0.74, 1.0),
|
| 693 |
+
(0.82, 0.80, 0.62, 1.0),
|
| 694 |
+
(0.74, 0.72, 0.86, 1.0),
|
| 695 |
+
]
|
| 696 |
+
for idx_obj, obj in enumerate(vis_objs):
|
| 697 |
+
obj.color = _OBJ_PALETTE[idx_obj % len(_OBJ_PALETTE)]
|
| 698 |
+
|
| 699 |
+
scene.render.engine = "BLENDER_WORKBENCH"
|
| 700 |
+
scene.view_settings.view_transform = "Standard"
|
| 701 |
+
scene.view_settings.look = "None"
|
| 702 |
+
scene.display.shading.light = "MATCAP"
|
| 703 |
+
scene.display.shading.color_type = "OBJECT"
|
| 704 |
+
scene.display.shading.show_cavity = True
|
| 705 |
+
scene.display.shading.cavity_type = "BOTH"
|
| 706 |
+
scene.display.shading.cavity_ridge_factor = 1.6
|
| 707 |
+
scene.display.shading.cavity_valley_factor = 1.6
|
| 708 |
+
scene.display.shading.show_object_outline = True
|
| 709 |
+
|
| 710 |
+
for vname, az, el in views:
|
| 711 |
+
place_cam(az, el)
|
| 712 |
+
scene.render.filepath = os.path.join(out_dir, f"wb_{vname}.png")
|
| 713 |
+
bpy.ops.render.render(write_still=True)
|
| 714 |
+
|
| 715 |
+
# Row 2: CYCLES 1-Sample True Raw World Normal RGB (`0.5 * N + 0.5`) + Red Backfacing
|
| 716 |
+
scene.render.engine = "CYCLES"
|
| 717 |
+
scene.cycles.device = "CPU"
|
| 718 |
+
scene.cycles.samples = 1
|
| 719 |
+
scene.cycles.use_denoising = False
|
| 720 |
+
scene.view_settings.view_transform = "Raw"
|
| 721 |
+
scene.view_settings.look = "None"
|
| 722 |
+
|
| 723 |
+
mat = bpy.data.materials.new("_DiagNormalFaceMat")
|
| 724 |
+
if mat.node_tree is None:
|
| 725 |
+
mat.use_nodes = True
|
| 726 |
+
nt = mat.node_tree
|
| 727 |
+
nt.nodes.clear()
|
| 728 |
+
n_out = nt.nodes.new("ShaderNodeOutputMaterial")
|
| 729 |
+
n_em = nt.nodes.new("ShaderNodeEmission")
|
| 730 |
+
n_geo = nt.nodes.new("ShaderNodeNewGeometry")
|
| 731 |
+
n_vec = nt.nodes.new("ShaderNodeVectorMath")
|
| 732 |
+
n_vec.operation = "MULTIPLY_ADD"
|
| 733 |
+
n_vec.inputs[1].default_value = (0.5, 0.5, 0.5)
|
| 734 |
+
n_vec.inputs[2].default_value = (0.5, 0.5, 0.5)
|
| 735 |
+
n_mix = nt.nodes.new("ShaderNodeMix")
|
| 736 |
+
n_mix.data_type = "RGBA"
|
| 737 |
+
n_mix.inputs["B"].default_value = (1.0, 0.039, 0.059, 1.0)
|
| 738 |
+
nt.links.new(n_geo.outputs["Normal"], n_vec.inputs[0])
|
| 739 |
+
nt.links.new(n_vec.outputs["Vector"], n_mix.inputs["A"])
|
| 740 |
+
nt.links.new(n_geo.outputs["Backfacing"], n_mix.inputs["Factor"])
|
| 741 |
+
nt.links.new(n_mix.outputs["Result"], n_em.inputs["Color"])
|
| 742 |
+
nt.links.new(n_em.outputs["Emission"], n_out.inputs["Surface"])
|
| 743 |
+
|
| 744 |
+
for obj in vis_objs:
|
| 745 |
+
obj.data.materials.clear()
|
| 746 |
+
obj.data.materials.append(mat)
|
| 747 |
+
|
| 748 |
+
for vname, az, el in views:
|
| 749 |
+
place_cam(az, el)
|
| 750 |
+
scene.render.filepath = os.path.join(out_dir, f"nm_{vname}.png")
|
| 751 |
+
bpy.ops.render.render(write_still=True)
|
| 752 |
+
"""
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
def render_blender_diagnostic_sheet(
|
| 756 |
+
blend_path: str,
|
| 757 |
+
out_png: str,
|
| 758 |
+
*,
|
| 759 |
+
xml_path: str | None = None,
|
| 760 |
+
part_pivots: Mapping[str, tuple[float, float, float]] | None = None,
|
| 761 |
+
panel_size: int = 420,
|
| 762 |
+
) -> dict[str, Any]:
|
| 763 |
+
"""Renders a non-destructive 2x4 Blender Workbench Cavity + Raw Normal/Backface sheet.
|
| 764 |
+
|
| 765 |
+
Row 1 renders `BLENDER_WORKBENCH` (`show_cavity=True`) ridge/valley cavity
|
| 766 |
+
shading across 4 views (`Front +X`, `Right -Y`, `Top +Z`, `3/4 Hero Iso`).
|
| 767 |
+
Row 2 renders 1-sample `CYCLES` under `view_transform = 'Raw'` encoding true
|
| 768 |
+
`0.5 * N + 0.5` world normals, with flipped backfaces (`Backfacing == 1`)
|
| 769 |
+
highlighted in Bright Neon Red (`#FF0A0F`). Never mutates `obj.location`.
|
| 770 |
+
|
| 771 |
+
Args:
|
| 772 |
+
blend_path: Path to the saved `.blend` file.
|
| 773 |
+
out_png: Output composite PNG path.
|
| 774 |
+
xml_path: Unused compatibility argument (scene transforms in `blend_path`
|
| 775 |
+
are rendered directly without mutating `obj.location`).
|
| 776 |
+
part_pivots: Unused compatibility argument (scene transforms in `blend_path`
|
| 777 |
+
are rendered directly without mutating `obj.location`).
|
| 778 |
+
panel_size: Pixel width and height of each panel cell.
|
| 779 |
+
|
| 780 |
+
Returns:
|
| 781 |
+
Dict with `"out_png"`, `"backface_pixels_per_view"`,
|
| 782 |
+
`"backface_pixel_counts"` per view, and `"has_backfaces"` boolean flag.
|
| 783 |
+
"""
|
| 784 |
+
del xml_path, part_pivots
|
| 785 |
+
views_meta = [
|
| 786 |
+
("front", "FRONT (+X)"),
|
| 787 |
+
("right", "RIGHT (-Y)"),
|
| 788 |
+
("top", "TOP (+Z)"),
|
| 789 |
+
("hero_iso", "3/4 HERO ISO"),
|
| 790 |
+
]
|
| 791 |
+
with tempfile.TemporaryDirectory(prefix="blender_diag_") as tmp_dir:
|
| 792 |
+
script_p = os.path.join(tmp_dir, "_run_diag.py")
|
| 793 |
+
with open(script_p, "w", encoding="utf-8") as sf:
|
| 794 |
+
sf.write(_BLENDER_DIAG_SCRIPT)
|
| 795 |
+
payload = json.dumps({
|
| 796 |
+
"tmp_dir": tmp_dir,
|
| 797 |
+
"panel_size": panel_size,
|
| 798 |
+
})
|
| 799 |
+
env = dict(os.environ)
|
| 800 |
+
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
| 801 |
+
blender_bin = (
|
| 802 |
+
os.environ.get("MUJOCO_BLENDER_BIN")
|
| 803 |
+
or shutil.which("blender")
|
| 804 |
+
or (
|
| 805 |
+
"/Applications/Blender.app/Contents/MacOS/Blender"
|
| 806 |
+
if os.path.exists(
|
| 807 |
+
"/Applications/Blender.app/Contents/MacOS/Blender"
|
| 808 |
+
)
|
| 809 |
+
else "/usr/bin/blender"
|
| 810 |
+
)
|
| 811 |
+
)
|
| 812 |
+
proc = subprocess.run(
|
| 813 |
+
[blender_bin, "-b", blend_path, "-P", script_p, "--", payload],
|
| 814 |
+
check=False,
|
| 815 |
+
env=env,
|
| 816 |
+
capture_output=True,
|
| 817 |
+
text=True,
|
| 818 |
+
)
|
| 819 |
+
if proc.returncode != 0:
|
| 820 |
+
err_tail = (proc.stderr or proc.stdout or "")[-2000:]
|
| 821 |
+
raise RuntimeError(
|
| 822 |
+
f"Blender diagnostic render failed (exit {proc.returncode}) via "
|
| 823 |
+
f"{blender_bin!r}:\n{err_tail}"
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
font = _load_label_font(12)
|
| 827 |
+
pad = 8
|
| 828 |
+
hdr_h = 26
|
| 829 |
+
sheet_w = 4 * panel_size + 5 * pad
|
| 830 |
+
sheet_h = 2 * (panel_size + hdr_h) + 3 * pad
|
| 831 |
+
sheet = Image.new("RGB", (sheet_w, sheet_h), (14, 18, 24))
|
| 832 |
+
draw = ImageDraw.Draw(sheet)
|
| 833 |
+
|
| 834 |
+
backface_counts: dict[str, int] = {}
|
| 835 |
+
for col_i, (vkey, vlabel) in enumerate(views_meta):
|
| 836 |
+
x0 = pad + col_i * (panel_size + pad)
|
| 837 |
+
y0 = pad
|
| 838 |
+
draw.rectangle([x0, y0, x0 + panel_size, y0 + hdr_h], fill=(32, 48, 68))
|
| 839 |
+
draw.text(
|
| 840 |
+
(x0 + 8, y0 + 5),
|
| 841 |
+
f"WORKBENCH CAVITY: {vlabel}",
|
| 842 |
+
fill=(242, 246, 252),
|
| 843 |
+
font=font,
|
| 844 |
+
)
|
| 845 |
+
wb_p = os.path.join(tmp_dir, f"wb_{vkey}.png")
|
| 846 |
+
if os.path.exists(wb_p):
|
| 847 |
+
wb_rgba = Image.open(wb_p).convert("RGBA")
|
| 848 |
+
bg = Image.new("RGBA", wb_rgba.size, (34, 39, 46, 255))
|
| 849 |
+
comp = Image.alpha_composite(bg, wb_rgba).convert("RGB")
|
| 850 |
+
sheet.paste(comp, (x0, y0 + hdr_h))
|
| 851 |
+
|
| 852 |
+
y1 = pad + (panel_size + hdr_h + pad)
|
| 853 |
+
nm_p = os.path.join(tmp_dir, f"nm_{vkey}.png")
|
| 854 |
+
bf_px = 0
|
| 855 |
+
if os.path.exists(nm_p):
|
| 856 |
+
nm_rgba = Image.open(nm_p).convert("RGBA")
|
| 857 |
+
arr = np.asarray(nm_rgba, dtype=np.int32)
|
| 858 |
+
# Unit normal sphere satisfiesnx^2 + ny^2 + nz^2 = 1, so `0.5 * N + 0.5`
|
| 859 |
+
# with R > 210 mathematically has max(G, B) >= 59; `< 45` isolates `#FF0A0F`.
|
| 860 |
+
red_mask = (
|
| 861 |
+
(arr[..., 3] > 200)
|
| 862 |
+
& (arr[..., 0] > 210)
|
| 863 |
+
& (arr[..., 1] < 45)
|
| 864 |
+
& (arr[..., 2] < 45)
|
| 865 |
+
)
|
| 866 |
+
bf_px = int(np.sum(red_mask))
|
| 867 |
+
backface_counts[vkey] = bf_px
|
| 868 |
+
bg_nm = Image.new("RGBA", nm_rgba.size, (18, 22, 28, 255))
|
| 869 |
+
comp_nm = Image.alpha_composite(bg_nm, nm_rgba).convert("RGB")
|
| 870 |
+
sheet.paste(comp_nm, (x0, y1 + hdr_h))
|
| 871 |
+
|
| 872 |
+
hdr_col = (145, 28, 38) if bf_px > 12 else (42, 34, 64)
|
| 873 |
+
draw.rectangle([x0, y1, x0 + panel_size, y1 + hdr_h], fill=hdr_col)
|
| 874 |
+
bf_tag = f" [BACKFACE RED={bf_px}px!]" if bf_px > 12 else " [OK: 0 Red]"
|
| 875 |
+
draw.text(
|
| 876 |
+
(x0 + 8, y1 + 5),
|
| 877 |
+
f"NORMAL RGB + BACKFACE: {vlabel}{bf_tag}",
|
| 878 |
+
fill=(242, 246, 252),
|
| 879 |
+
font=font,
|
| 880 |
+
)
|
| 881 |
+
|
| 882 |
+
_save_inspection_image(sheet, out_png)
|
| 883 |
+
total_bf = sum(backface_counts.values())
|
| 884 |
+
has_bf = any(v > 12 for v in backface_counts.values())
|
| 885 |
+
if has_bf:
|
| 886 |
+
print(
|
| 887 |
+
"[BLENDER DIAG WARNING] Detected BRIGHT RED backfacing/flipped faces "
|
| 888 |
+
f"in {out_png}: {backface_counts}! Call bmesh.ops.recalc_face_normals "
|
| 889 |
+
"and fix any folded non-convex polygon caps."
|
| 890 |
+
)
|
| 891 |
+
else:
|
| 892 |
+
print(f"[BLENDER DIAG OK] Saved {out_png} (0 flipped backfaces detected).")
|
| 893 |
+
return {
|
| 894 |
+
"out_png": out_png,
|
| 895 |
+
"backface_pixel_counts": backface_counts,
|
| 896 |
+
"backface_pixels_per_view": backface_counts,
|
| 897 |
+
"total_backface_pixels": total_bf,
|
| 898 |
+
"has_backfaces": has_bf,
|
| 899 |
+
}
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
def _to_uint8_image_array(raw_bytes: bytes, want_rgb: bool) -> np.ndarray:
|
| 903 |
+
"""Decodes 8-bit or 16-bit PNG/JPG bytes into a normalized `uint8` array."""
|
| 904 |
+
with Image.open(io.BytesIO(raw_bytes)) as img:
|
| 905 |
+
if want_rgb:
|
| 906 |
+
if img.mode in ("I", "I;16", "I;16B", "I;16L", "F"):
|
| 907 |
+
arr = np.asarray(img, dtype=np.float32)
|
| 908 |
+
scale = 257.0 if arr.max() > 255.0 else 1.0
|
| 909 |
+
u8 = np.clip(np.round(arr / scale), 0, 255).astype(np.uint8)
|
| 910 |
+
return np.stack([u8, u8, u8], axis=-1)
|
| 911 |
+
rgb_im = img.convert("RGB")
|
| 912 |
+
return np.asarray(rgb_im, dtype=np.uint8)
|
| 913 |
+
|
| 914 |
+
if img.mode in ("I", "I;16", "I;16B", "I;16L"):
|
| 915 |
+
arr = np.asarray(img, dtype=np.float32)
|
| 916 |
+
return np.clip(np.round(arr / 257.0), 0, 255).astype(np.uint8)
|
| 917 |
+
if img.mode == "F":
|
| 918 |
+
arr = np.asarray(img, dtype=np.float32)
|
| 919 |
+
scale = 255.0 if arr.max() <= 1.05 else 1.0
|
| 920 |
+
return np.clip(np.round(arr * scale), 0, 255).astype(np.uint8)
|
| 921 |
+
return np.asarray(img.convert("L"), dtype=np.uint8)
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
def fetch_ambientcg_maps(
|
| 925 |
+
asset_id: str,
|
| 926 |
+
*,
|
| 927 |
+
cache_dir: str | None = None,
|
| 928 |
+
resolution: str = "1K",
|
| 929 |
+
) -> dict[str, np.ndarray]:
|
| 930 |
+
"""Fetches and caches CC0 AmbientCG PBR, imperfection, and decal maps.
|
| 931 |
+
|
| 932 |
+
Args:
|
| 933 |
+
asset_id: AmbientCG asset identifier (e.g. `"Rubber004"`, `"Metal009"`).
|
| 934 |
+
cache_dir: Local directory for caching extracted 8-bit PNGs. If `None`, uses
|
| 935 |
+
`~/.cache/mujoco_pbr_cache`.
|
| 936 |
+
resolution: Preferred resolution prefix (`"1K"` default, or `"2K"`).
|
| 937 |
+
|
| 938 |
+
Returns:
|
| 939 |
+
Dict mapping available channel keys (`"color"`, `"roughness"`,
|
| 940 |
+
`"normal_gl"`, `"opacity"`, `"metallic"`, `"ao"`, `"displacement"`) to
|
| 941 |
+
`uint8` numpy arrays (`(H, W, 3)` for RGB/normal, `(H, W)` for scalar maps).
|
| 942 |
+
"""
|
| 943 |
+
cache_root = os.path.abspath(
|
| 944 |
+
cache_dir or os.path.expanduser("~/.cache/mujoco_pbr_cache")
|
| 945 |
+
)
|
| 946 |
+
pack_dir = os.path.join(cache_root, f"{asset_id}_{resolution}")
|
| 947 |
+
manifest_path = os.path.join(pack_dir, "_manifest.json")
|
| 948 |
+
|
| 949 |
+
if os.path.isfile(manifest_path):
|
| 950 |
+
with open(manifest_path, "r", encoding="utf-8") as mf:
|
| 951 |
+
manifest = json.load(mf)
|
| 952 |
+
out_cached: dict[str, np.ndarray] = {}
|
| 953 |
+
for ch_key, rel_file in manifest.items():
|
| 954 |
+
img_p = os.path.join(pack_dir, rel_file)
|
| 955 |
+
if os.path.isfile(img_p):
|
| 956 |
+
want_rgb = ch_key in ("color", "normal_gl")
|
| 957 |
+
with Image.open(img_p) as im:
|
| 958 |
+
out_cached[ch_key] = np.asarray(
|
| 959 |
+
im.convert("RGB" if want_rgb else "L"), dtype=np.uint8
|
| 960 |
+
)
|
| 961 |
+
if out_cached:
|
| 962 |
+
return out_cached
|
| 963 |
+
|
| 964 |
+
api_url = (
|
| 965 |
+
f"https://ambientcg.com/api/v2/full_json?id={asset_id}"
|
| 966 |
+
"&include=downloadData"
|
| 967 |
+
)
|
| 968 |
+
req = urllib.request.Request(
|
| 969 |
+
api_url, headers={"User-Agent": "mujoco-asset-builder/1.0"}
|
| 970 |
+
)
|
| 971 |
+
with urllib.request.urlopen(req, timeout=25) as resp:
|
| 972 |
+
payload = json.loads(resp.read().decode("utf-8"))
|
| 973 |
+
|
| 974 |
+
found = payload.get("foundAssets", [])
|
| 975 |
+
if not found:
|
| 976 |
+
raise ValueError(f"AmbientCG asset {asset_id!r} not found")
|
| 977 |
+
dl_folders = (
|
| 978 |
+
found[0]
|
| 979 |
+
.get("downloadFolders", {})
|
| 980 |
+
.get("default", {})
|
| 981 |
+
.get("downloadFiletypeCategories", {})
|
| 982 |
+
)
|
| 983 |
+
zip_downloads = dl_folders.get("zip", {}).get("downloads", [])
|
| 984 |
+
by_attr = {
|
| 985 |
+
d.get("attribute", ""): d.get("downloadLink", "") for d in zip_downloads
|
| 986 |
+
}
|
| 987 |
+
|
| 988 |
+
chosen_url = ""
|
| 989 |
+
for cand in (
|
| 990 |
+
f"{resolution}-PNG",
|
| 991 |
+
f"{resolution}-JPG",
|
| 992 |
+
"1K-PNG",
|
| 993 |
+
"1K-JPG",
|
| 994 |
+
"2K-PNG",
|
| 995 |
+
"2K-JPG",
|
| 996 |
+
):
|
| 997 |
+
if by_attr.get(cand):
|
| 998 |
+
chosen_url = by_attr[cand]
|
| 999 |
+
break
|
| 1000 |
+
if not chosen_url and zip_downloads:
|
| 1001 |
+
chosen_url = zip_downloads[0].get("downloadLink", "")
|
| 1002 |
+
if not chosen_url:
|
| 1003 |
+
raise RuntimeError(f"No zip download URL found for AmbientCG {asset_id!r}")
|
| 1004 |
+
|
| 1005 |
+
zip_req = urllib.request.Request(
|
| 1006 |
+
chosen_url, headers={"User-Agent": "mujoco-asset-builder/1.0"}
|
| 1007 |
+
)
|
| 1008 |
+
with urllib.request.urlopen(zip_req, timeout=45) as zresp:
|
| 1009 |
+
zip_bytes = zresp.read()
|
| 1010 |
+
|
| 1011 |
+
channel_suffixes = (
|
| 1012 |
+
("color", ("_color.", "_albedo.")),
|
| 1013 |
+
("roughness", ("_roughness.",)),
|
| 1014 |
+
("normal_gl", ("_normalgl.",)),
|
| 1015 |
+
("opacity", ("_opacity.", "_mask.")),
|
| 1016 |
+
("metallic", ("_metalness.", "_metallic.")),
|
| 1017 |
+
("ao", ("_ambientocclusion.", "_ao.")),
|
| 1018 |
+
("displacement", ("_displacement.", "_height.")),
|
| 1019 |
+
)
|
| 1020 |
+
|
| 1021 |
+
os.makedirs(pack_dir, exist_ok=True)
|
| 1022 |
+
extracted: dict[str, np.ndarray] = {}
|
| 1023 |
+
manifest_out: dict[str, str] = {}
|
| 1024 |
+
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
|
| 1025 |
+
for member in zf.namelist():
|
| 1026 |
+
low = member.lower()
|
| 1027 |
+
if not low.endswith((".png", ".jpg", ".jpeg")):
|
| 1028 |
+
continue
|
| 1029 |
+
for ch_key, suffixes in channel_suffixes:
|
| 1030 |
+
if any(sfx in low for sfx in suffixes) and ch_key not in extracted:
|
| 1031 |
+
raw = zf.read(member)
|
| 1032 |
+
want_rgb = ch_key in ("color", "normal_gl")
|
| 1033 |
+
arr_u8 = _to_uint8_image_array(raw, want_rgb=want_rgb)
|
| 1034 |
+
extracted[ch_key] = arr_u8
|
| 1035 |
+
out_name = f"{ch_key}.png"
|
| 1036 |
+
Image.fromarray(arr_u8).save(os.path.join(pack_dir, out_name))
|
| 1037 |
+
manifest_out[ch_key] = out_name
|
| 1038 |
+
if ch_key == "color" and "opacity" not in extracted:
|
| 1039 |
+
with Image.open(io.BytesIO(raw)) as cim:
|
| 1040 |
+
if "A" in cim.getbands():
|
| 1041 |
+
alpha_arr = np.asarray(cim.getchannel("A"), dtype=np.uint8)
|
| 1042 |
+
if alpha_arr.min() < 250:
|
| 1043 |
+
extracted["opacity"] = alpha_arr
|
| 1044 |
+
Image.fromarray(alpha_arr).save(
|
| 1045 |
+
os.path.join(pack_dir, "opacity.png")
|
| 1046 |
+
)
|
| 1047 |
+
manifest_out["opacity"] = "opacity.png"
|
| 1048 |
+
|
| 1049 |
+
with open(manifest_path, "w", encoding="utf-8") as mf:
|
| 1050 |
+
json.dump(manifest_out, mf, indent=2)
|
| 1051 |
+
return extracted
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
def dilate_uv_gutters(
|
| 1055 |
+
arr: np.ndarray,
|
| 1056 |
+
valid_mask: np.ndarray,
|
| 1057 |
+
*,
|
| 1058 |
+
max_dist_px: int = 12,
|
| 1059 |
+
) -> np.ndarray:
|
| 1060 |
+
"""Dilates valid UV island values into adjacent empty gutter margins via EDT.
|
| 1061 |
+
|
| 1062 |
+
Args:
|
| 1063 |
+
arr: `(H, W)` or `(H, W, C)` array to dilate.
|
| 1064 |
+
valid_mask: `(H, W)` boolean mask where `True` marks inside-island texels.
|
| 1065 |
+
max_dist_px: Maximum dilation radius in pixels (`12` default).
|
| 1066 |
+
|
| 1067 |
+
Returns:
|
| 1068 |
+
Copy of `arr` with gutter pixels within `max_dist_px` filled from nearest
|
| 1069 |
+
valid island texel.
|
| 1070 |
+
"""
|
| 1071 |
+
mask = np.asarray(valid_mask, dtype=bool)
|
| 1072 |
+
if not np.any(mask) or np.all(mask):
|
| 1073 |
+
return np.array(arr, copy=True)
|
| 1074 |
+
dists, nearest_idx = _get_ndimage().distance_transform_edt(
|
| 1075 |
+
~mask, return_distances=True, return_indices=True
|
| 1076 |
+
)
|
| 1077 |
+
out = np.array(arr, copy=True)
|
| 1078 |
+
fill = (~mask) & (dists <= float(max_dist_px))
|
| 1079 |
+
out[fill] = arr[nearest_idx[0][fill], nearest_idx[1][fill]]
|
| 1080 |
+
return out
|
| 1081 |
+
|
| 1082 |
+
|
| 1083 |
+
def _resolve_obj_index(tok_part: str, current_pool_len: int) -> int:
|
| 1084 |
+
"""Resolves a positive (`1`-based) or negative (relative) Wavefront `.obj` index."""
|
| 1085 |
+
if not tok_part:
|
| 1086 |
+
return -1
|
| 1087 |
+
raw_i = int(tok_part)
|
| 1088 |
+
if raw_i > 0:
|
| 1089 |
+
return raw_i - 1
|
| 1090 |
+
if raw_i < 0:
|
| 1091 |
+
return current_pool_len + raw_i
|
| 1092 |
+
return -1
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
def rasterize_uv_world_fields(
|
| 1096 |
+
obj_paths: str | Sequence[str],
|
| 1097 |
+
canvas_size: tuple[int, int] | int = 1024,
|
| 1098 |
+
*,
|
| 1099 |
+
part_offsets: Mapping[str, tuple[float, float, float]] | None = None,
|
| 1100 |
+
) -> dict[str, Any]:
|
| 1101 |
+
"""Rasterizes per-texel 3D world `(X, Y, Z)` and orthonormal `(tangent_u, tangent_v, normal)` in UV space.
|
| 1102 |
+
|
| 1103 |
+
Args:
|
| 1104 |
+
obj_paths: Single `.obj` path or sequence of `.obj` paths sharing a UV map.
|
| 1105 |
+
canvas_size: Target `(width, height)` or square `size` in pixels.
|
| 1106 |
+
part_offsets: Optional mapping from mesh stem or filename to `(px, py, pz)`
|
| 1107 |
+
world body offset.
|
| 1108 |
+
|
| 1109 |
+
Returns:
|
| 1110 |
+
Dict with `"xyz"` (`(H, W, 3)` float32), `"normal"` (`(H, W, 3)` float32),
|
| 1111 |
+
`"tangent_u"` (`(H, W, 3)` float32), `"tangent_v"` (`(H, W, 3)` float32),
|
| 1112 |
+
`"mm_per_texel"` (`(H, W)` float32), `"valid_mask"` (`(H, W)` bool),
|
| 1113 |
+
`"part_id"` (`(H, W)` int32), and `"part_masks"` (`dict[str, np.ndarray]`).
|
| 1114 |
+
"""
|
| 1115 |
+
if isinstance(canvas_size, int):
|
| 1116 |
+
width, height = int(canvas_size), int(canvas_size)
|
| 1117 |
+
else:
|
| 1118 |
+
width, height = int(canvas_size[0]), int(canvas_size[1])
|
| 1119 |
+
|
| 1120 |
+
paths = [obj_paths] if isinstance(obj_paths, str) else list(obj_paths)
|
| 1121 |
+
xyz_buf = np.zeros((height, width, 3), dtype=np.float32)
|
| 1122 |
+
nrm_buf = np.zeros((height, width, 3), dtype=np.float32)
|
| 1123 |
+
nrm_buf[..., 2] = 1.0
|
| 1124 |
+
tu_buf = np.zeros((height, width, 3), dtype=np.float32)
|
| 1125 |
+
tu_buf[..., 0] = 1.0
|
| 1126 |
+
tv_buf = np.zeros((height, width, 3), dtype=np.float32)
|
| 1127 |
+
tv_buf[..., 1] = 1.0
|
| 1128 |
+
mm_px_buf = np.ones((height, width), dtype=np.float32)
|
| 1129 |
+
valid = np.zeros((height, width), dtype=bool)
|
| 1130 |
+
part_id_buf = np.full((height, width), -1, dtype=np.int32)
|
| 1131 |
+
part_stems: list[str] = []
|
| 1132 |
+
|
| 1133 |
+
for obj_p in paths:
|
| 1134 |
+
if not os.path.isfile(obj_p):
|
| 1135 |
+
continue
|
| 1136 |
+
stem = os.path.splitext(os.path.basename(obj_p))[0]
|
| 1137 |
+
p_idx = len(part_stems)
|
| 1138 |
+
part_stems.append(stem)
|
| 1139 |
+
offset = np.zeros(3, dtype=np.float32)
|
| 1140 |
+
if part_offsets:
|
| 1141 |
+
if stem in part_offsets:
|
| 1142 |
+
offset = np.asarray(part_offsets[stem], dtype=np.float32)
|
| 1143 |
+
elif os.path.basename(obj_p) in part_offsets:
|
| 1144 |
+
offset = np.asarray(
|
| 1145 |
+
part_offsets[os.path.basename(obj_p)], dtype=np.float32
|
| 1146 |
+
)
|
| 1147 |
+
|
| 1148 |
+
verts: list[list[float]] = []
|
| 1149 |
+
uvs: list[list[float]] = []
|
| 1150 |
+
norms: list[list[float]] = []
|
| 1151 |
+
tris: list[
|
| 1152 |
+
tuple[
|
| 1153 |
+
tuple[int, int, int],
|
| 1154 |
+
tuple[int, int, int],
|
| 1155 |
+
tuple[int, int, int],
|
| 1156 |
+
]
|
| 1157 |
+
] = []
|
| 1158 |
+
|
| 1159 |
+
with open(obj_p, "r", encoding="utf-8", errors="ignore") as f:
|
| 1160 |
+
for raw_line in f:
|
| 1161 |
+
line = raw_line.split("#", 1)[0].strip()
|
| 1162 |
+
if not line:
|
| 1163 |
+
continue
|
| 1164 |
+
sp = line.split()
|
| 1165 |
+
cmd = sp[0]
|
| 1166 |
+
if cmd == "v" and len(sp) >= 4:
|
| 1167 |
+
verts.append([float(sp[1]), float(sp[2]), float(sp[3])])
|
| 1168 |
+
elif cmd == "vt" and len(sp) >= 3:
|
| 1169 |
+
uvs.append([float(sp[1]), float(sp[2])])
|
| 1170 |
+
elif cmd == "vn" and len(sp) >= 4:
|
| 1171 |
+
norms.append([float(sp[1]), float(sp[2]), float(sp[3])])
|
| 1172 |
+
elif cmd == "f":
|
| 1173 |
+
tokens = sp[1:]
|
| 1174 |
+
if len(tokens) < 3:
|
| 1175 |
+
continue
|
| 1176 |
+
corner_idx: list[tuple[int, int, int]] = []
|
| 1177 |
+
n_v_cur, n_vt_cur, n_vn_cur = len(verts), len(uvs), len(norms)
|
| 1178 |
+
for tok in tokens:
|
| 1179 |
+
inds = tok.split("/")
|
| 1180 |
+
vi = _resolve_obj_index(inds[0], n_v_cur)
|
| 1181 |
+
ti = _resolve_obj_index(inds[1], n_vt_cur) if len(inds) > 1 else -1
|
| 1182 |
+
ni = _resolve_obj_index(inds[2], n_vn_cur) if len(inds) > 2 else -1
|
| 1183 |
+
corner_idx.append((vi, ti, ni))
|
| 1184 |
+
for k in range(1, len(corner_idx) - 1):
|
| 1185 |
+
tris.append((corner_idx[0], corner_idx[k], corner_idx[k + 1]))
|
| 1186 |
+
|
| 1187 |
+
if not verts or not uvs:
|
| 1188 |
+
continue
|
| 1189 |
+
v_arr = np.asarray(verts, dtype=np.float32) + offset[None, :]
|
| 1190 |
+
uv_arr = np.asarray(uvs, dtype=np.float32)
|
| 1191 |
+
n_arr = (
|
| 1192 |
+
np.asarray(norms, dtype=np.float32)
|
| 1193 |
+
if norms
|
| 1194 |
+
else np.zeros((0, 3), dtype=np.float32)
|
| 1195 |
+
)
|
| 1196 |
+
num_v, num_uv, num_n = len(v_arr), len(uv_arr), len(n_arr)
|
| 1197 |
+
|
| 1198 |
+
for c0, c1, c2 in tris:
|
| 1199 |
+
if not (
|
| 1200 |
+
0 <= c0[0] < num_v and 0 <= c1[0] < num_v and 0 <= c2[0] < num_v
|
| 1201 |
+
) or not (
|
| 1202 |
+
0 <= c0[1] < num_uv and 0 <= c1[1] < num_uv and 0 <= c2[1] < num_uv
|
| 1203 |
+
):
|
| 1204 |
+
continue
|
| 1205 |
+
uv0, uv1, uv2 = uv_arr[c0[1]], uv_arr[c1[1]], uv_arr[c2[1]]
|
| 1206 |
+
x0, y0 = uv0[0] * (width - 1), (1.0 - uv0[1]) * (height - 1)
|
| 1207 |
+
x1, y1 = uv1[0] * (width - 1), (1.0 - uv1[1]) * (height - 1)
|
| 1208 |
+
x2, y2 = uv2[0] * (width - 1), (1.0 - uv2[1]) * (height - 1)
|
| 1209 |
+
|
| 1210 |
+
ix0 = max(0, int(np.floor(min(x0, x1, x2))))
|
| 1211 |
+
ix1 = min(width - 1, int(np.ceil(max(x0, x1, x2))))
|
| 1212 |
+
iy0 = max(0, int(np.floor(min(y0, y1, y2))))
|
| 1213 |
+
iy1 = min(height - 1, int(np.ceil(max(y0, y1, y2))))
|
| 1214 |
+
if ix0 > ix1 or iy0 > iy1:
|
| 1215 |
+
continue
|
| 1216 |
+
|
| 1217 |
+
denom = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2)
|
| 1218 |
+
if abs(denom) < 1e-8:
|
| 1219 |
+
continue
|
| 1220 |
+
inv_den = 1.0 / denom
|
| 1221 |
+
|
| 1222 |
+
gx = np.arange(ix0, ix1 + 1, dtype=np.float32)[None, :]
|
| 1223 |
+
gy = np.arange(iy0, iy1 + 1, dtype=np.float32)[:, None]
|
| 1224 |
+
w0 = ((y1 - y2) * (gx - x2) + (x2 - x1) * (gy - y2)) * inv_den
|
| 1225 |
+
w1 = ((y2 - y0) * (gx - x2) + (x0 - x2) * (gy - y2)) * inv_den
|
| 1226 |
+
w2 = 1.0 - w0 - w1
|
| 1227 |
+
inside = (w0 >= -1e-4) & (w1 >= -1e-4) & (w2 >= -1e-4)
|
| 1228 |
+
if not np.any(inside):
|
| 1229 |
+
continue
|
| 1230 |
+
|
| 1231 |
+
p0, p1, p2 = v_arr[c0[0]], v_arr[c1[0]], v_arr[c2[0]]
|
| 1232 |
+
p_interp = w0[..., None] * p0 + w1[..., None] * p1 + w2[..., None] * p2
|
| 1233 |
+
if (
|
| 1234 |
+
num_n > 0
|
| 1235 |
+
and 0 <= c0[2] < num_n
|
| 1236 |
+
and 0 <= c1[2] < num_n
|
| 1237 |
+
and 0 <= c2[2] < num_n
|
| 1238 |
+
):
|
| 1239 |
+
vn0, vn1, vn2 = n_arr[c0[2]], n_arr[c1[2]], n_arr[c2[2]]
|
| 1240 |
+
n_interp = (
|
| 1241 |
+
w0[..., None] * vn0 + w1[..., None] * vn1 + w2[..., None] * vn2
|
| 1242 |
+
)
|
| 1243 |
+
else:
|
| 1244 |
+
fn = np.cross(p1 - p0, p2 - p0)
|
| 1245 |
+
fn_norm = fn / max(float(np.linalg.norm(fn)), 1e-8)
|
| 1246 |
+
n_interp = np.broadcast_to(fn_norm, p_interp.shape)
|
| 1247 |
+
|
| 1248 |
+
n_len = np.maximum(np.linalg.norm(n_interp, axis=-1, keepdims=True), 1e-8)
|
| 1249 |
+
n_unit = n_interp / n_len
|
| 1250 |
+
|
| 1251 |
+
dx1, dy1 = x1 - x0, y1 - y0
|
| 1252 |
+
dx2, dy2 = x2 - x0, y2 - y0
|
| 1253 |
+
det_xy = dx1 * dy2 - dx2 * dy1
|
| 1254 |
+
if abs(det_xy) > 1e-8:
|
| 1255 |
+
inv_det_xy = 1.0 / det_xy
|
| 1256 |
+
dp1, dp2 = p1 - p0, p2 - p0
|
| 1257 |
+
dp_dx = (dy2 * dp1 - dy1 * dp2) * inv_det_xy
|
| 1258 |
+
dp_dy = (-dx2 * dp1 + dx1 * dp2) * inv_det_xy
|
| 1259 |
+
len_dx = float(np.linalg.norm(dp_dx))
|
| 1260 |
+
len_dy = float(np.linalg.norm(dp_dy))
|
| 1261 |
+
tri_mm_per_px = float(np.sqrt(max(len_dx * len_dy, 1e-18)) * 1000.0)
|
| 1262 |
+
tu_raw = dp_dx / max(len_dx, 1e-8)
|
| 1263 |
+
tv_raw = -dp_dy / max(len_dy, 1e-8)
|
| 1264 |
+
else:
|
| 1265 |
+
tri_mm_per_px = 1.0
|
| 1266 |
+
tu_raw = np.array([1.0, 0.0, 0.0], dtype=np.float32)
|
| 1267 |
+
tv_raw = np.array([0.0, 1.0, 0.0], dtype=np.float32)
|
| 1268 |
+
|
| 1269 |
+
tu_proj = tu_raw[None, None, :] - (
|
| 1270 |
+
np.sum(tu_raw[None, None, :] * n_unit, axis=-1, keepdims=True)
|
| 1271 |
+
* n_unit
|
| 1272 |
+
)
|
| 1273 |
+
tu_len = np.linalg.norm(tu_proj, axis=-1, keepdims=True)
|
| 1274 |
+
if np.any(tu_len < 1e-6):
|
| 1275 |
+
ref_axis = np.where(
|
| 1276 |
+
np.abs(n_unit[..., 2:3]) < 0.9,
|
| 1277 |
+
np.array([0.0, 0.0, 1.0], dtype=np.float32),
|
| 1278 |
+
np.array([1.0, 0.0, 0.0], dtype=np.float32),
|
| 1279 |
+
)
|
| 1280 |
+
tu_fb = np.cross(ref_axis, n_unit)
|
| 1281 |
+
tu_proj = np.where(tu_len >= 1e-6, tu_proj, tu_fb)
|
| 1282 |
+
tu_len = np.linalg.norm(tu_proj, axis=-1, keepdims=True)
|
| 1283 |
+
tu_unit = tu_proj / np.maximum(tu_len, 1e-8)
|
| 1284 |
+
|
| 1285 |
+
ortho_v = np.cross(n_unit, tu_unit)
|
| 1286 |
+
ortho_v /= np.maximum(
|
| 1287 |
+
np.linalg.norm(ortho_v, axis=-1, keepdims=True), 1e-8
|
| 1288 |
+
)
|
| 1289 |
+
handedness = np.where(
|
| 1290 |
+
np.sum(tv_raw[None, None, :] * ortho_v, axis=-1, keepdims=True) < 0.0,
|
| 1291 |
+
np.float32(-1.0),
|
| 1292 |
+
np.float32(1.0),
|
| 1293 |
+
)
|
| 1294 |
+
tv_unit = ortho_v * handedness
|
| 1295 |
+
|
| 1296 |
+
xyz_buf[iy0 : iy1 + 1, ix0 : ix1 + 1][inside] = p_interp[inside]
|
| 1297 |
+
nrm_buf[iy0 : iy1 + 1, ix0 : ix1 + 1][inside] = n_unit[inside]
|
| 1298 |
+
tu_buf[iy0 : iy1 + 1, ix0 : ix1 + 1][inside] = tu_unit[inside]
|
| 1299 |
+
tv_buf[iy0 : iy1 + 1, ix0 : ix1 + 1][inside] = tv_unit[inside]
|
| 1300 |
+
mm_px_buf[iy0 : iy1 + 1, ix0 : ix1 + 1][inside] = tri_mm_per_px
|
| 1301 |
+
valid[iy0 : iy1 + 1, ix0 : ix1 + 1][inside] = True
|
| 1302 |
+
part_id_buf[iy0 : iy1 + 1, ix0 : ix1 + 1][inside] = p_idx
|
| 1303 |
+
|
| 1304 |
+
xyz_dil = dilate_uv_gutters(xyz_buf, valid, max_dist_px=12)
|
| 1305 |
+
nrm_dil = dilate_uv_gutters(nrm_buf, valid, max_dist_px=12)
|
| 1306 |
+
tu_dil = dilate_uv_gutters(tu_buf, valid, max_dist_px=12)
|
| 1307 |
+
tv_dil = dilate_uv_gutters(tv_buf, valid, max_dist_px=12)
|
| 1308 |
+
mm_dil = dilate_uv_gutters(mm_px_buf, valid, max_dist_px=12)
|
| 1309 |
+
part_id_dil = dilate_uv_gutters(part_id_buf, valid, max_dist_px=12)
|
| 1310 |
+
part_masks = {
|
| 1311 |
+
stem: part_id_dil == p_idx for p_idx, stem in enumerate(part_stems)
|
| 1312 |
+
}
|
| 1313 |
+
return {
|
| 1314 |
+
"xyz": xyz_dil,
|
| 1315 |
+
"normal": nrm_dil,
|
| 1316 |
+
"tangent_u": tu_dil,
|
| 1317 |
+
"tangent_v": tv_dil,
|
| 1318 |
+
"mm_per_texel": mm_dil,
|
| 1319 |
+
"valid_mask": valid,
|
| 1320 |
+
"part_id": part_id_dil,
|
| 1321 |
+
"part_masks": part_masks,
|
| 1322 |
+
}
|
| 1323 |
+
|
| 1324 |
+
|
| 1325 |
+
_IN_3D_HEIGHT_DIFF = False
|
| 1326 |
+
|
| 1327 |
+
|
| 1328 |
+
def normal_rgb_from_3d_height_fn(
|
| 1329 |
+
height_fn: Any,
|
| 1330 |
+
uv_world_fields: Mapping[str, Any],
|
| 1331 |
+
*,
|
| 1332 |
+
step_mm: float = 0.15,
|
| 1333 |
+
strength: float = 1.0,
|
| 1334 |
+
) -> np.ndarray:
|
| 1335 |
+
"""Evaluates a 3D height function into an OpenGL tangent-space normal map.
|
| 1336 |
+
|
| 1337 |
+
Differentiates `height_fn(xyz)` directly in 3D along the local orthonormal UV
|
| 1338 |
+
surface tangents (`tangent_u`, `tangent_v` from `rasterize_uv_world_fields`),
|
| 1339 |
+
avoiding 2D UV-island gutter cliffs, seam discontinuities, and UV stretch.
|
| 1340 |
+
|
| 1341 |
+
Args:
|
| 1342 |
+
height_fn: Callable `fn(pts_m: np.ndarray) -> np.ndarray` mapping `(..., 3)`
|
| 1343 |
+
3D coordinates in meters to scalar surface elevation (when elevation is in
|
| 1344 |
+
`mm`, `strength=1.0` corresponds to exact 1:1 geometric slope `dh_mm /
|
| 1345 |
+
ds_mm`).
|
| 1346 |
+
uv_world_fields: Dict returned by `rasterize_uv_world_fields`.
|
| 1347 |
+
step_mm: Central finite-difference step along the surface tangent in `mm`.
|
| 1348 |
+
strength: Slope multiplier controlling normal-map relief intensity.
|
| 1349 |
+
|
| 1350 |
+
Returns:
|
| 1351 |
+
`(H, W, 3)` `uint8` OpenGL tangent-space normal map (`(128, 128, 255)`
|
| 1352 |
+
flat).
|
| 1353 |
+
"""
|
| 1354 |
+
global _IN_3D_HEIGHT_DIFF
|
| 1355 |
+
xyz = np.asarray(uv_world_fields["xyz"], dtype=np.float32)
|
| 1356 |
+
tu = np.asarray(uv_world_fields["tangent_u"], dtype=np.float32)
|
| 1357 |
+
tv = np.asarray(uv_world_fields["tangent_v"], dtype=np.float32)
|
| 1358 |
+
step_v = max(float(step_mm), 1e-4)
|
| 1359 |
+
step_m = np.float32(step_v * 1e-3)
|
| 1360 |
+
inv_2s = np.float32(1.0 / (2.0 * step_v))
|
| 1361 |
+
|
| 1362 |
+
prev_diff = _IN_3D_HEIGHT_DIFF
|
| 1363 |
+
_IN_3D_HEIGHT_DIFF = True
|
| 1364 |
+
try:
|
| 1365 |
+
dh_du = (
|
| 1366 |
+
np.asarray(height_fn(xyz + step_m * tu), dtype=np.float32)
|
| 1367 |
+
- np.asarray(height_fn(xyz - step_m * tu), dtype=np.float32)
|
| 1368 |
+
) * inv_2s
|
| 1369 |
+
dh_dv = (
|
| 1370 |
+
np.asarray(height_fn(xyz + step_m * tv), dtype=np.float32)
|
| 1371 |
+
- np.asarray(height_fn(xyz - step_m * tv), dtype=np.float32)
|
| 1372 |
+
) * inv_2s
|
| 1373 |
+
finally:
|
| 1374 |
+
_IN_3D_HEIGHT_DIFF = prev_diff
|
| 1375 |
+
|
| 1376 |
+
norm_x = -dh_du * float(strength)
|
| 1377 |
+
norm_y = -dh_dv * float(strength)
|
| 1378 |
+
norm_z = np.ones_like(dh_du, dtype=np.float32)
|
| 1379 |
+
inv_len = 1.0 / np.maximum(
|
| 1380 |
+
np.sqrt(norm_x * norm_x + norm_y * norm_y + norm_z * norm_z), 1e-8
|
| 1381 |
+
)
|
| 1382 |
+
rgb = np.stack(
|
| 1383 |
+
[
|
| 1384 |
+
(norm_x * inv_len * 0.5 + 0.5) * 255.0,
|
| 1385 |
+
(norm_y * inv_len * 0.5 + 0.5) * 255.0,
|
| 1386 |
+
(norm_z * inv_len * 0.5 + 0.5) * 255.0,
|
| 1387 |
+
],
|
| 1388 |
+
axis=-1,
|
| 1389 |
+
)
|
| 1390 |
+
vm = uv_world_fields.get("valid_mask")
|
| 1391 |
+
if vm is not None:
|
| 1392 |
+
rgb = dilate_uv_gutters(rgb, vm, max_dist_px=12)
|
| 1393 |
+
return np.clip(np.round(rgb), 0, 255).astype(np.uint8)
|
| 1394 |
+
|
| 1395 |
+
|
| 1396 |
+
def fbm_noise_3d(
|
| 1397 |
+
xyz: np.ndarray,
|
| 1398 |
+
*,
|
| 1399 |
+
base_freq: float = 25.0,
|
| 1400 |
+
wavelength_mm: float | None = None,
|
| 1401 |
+
octaves: int = 4,
|
| 1402 |
+
persistence: float = 0.5,
|
| 1403 |
+
seed: int = 42,
|
| 1404 |
+
) -> np.ndarray:
|
| 1405 |
+
"""Evaluates seam-free 3D fractional Brownian motion on `(..., 3)` XYZ in meters."""
|
| 1406 |
+
rng = np.random.default_rng(seed)
|
| 1407 |
+
pts = np.asarray(xyz, dtype=np.float32)
|
| 1408 |
+
total = np.zeros(pts.shape[:-1], dtype=np.float32)
|
| 1409 |
+
amp = 1.0
|
| 1410 |
+
amp_sum = 0.0
|
| 1411 |
+
freq = (
|
| 1412 |
+
472.0 / max(float(wavelength_mm), 1e-4)
|
| 1413 |
+
if wavelength_mm is not None
|
| 1414 |
+
else float(base_freq)
|
| 1415 |
+
)
|
| 1416 |
+
grid_n = 64
|
| 1417 |
+
|
| 1418 |
+
ndi = _get_ndimage()
|
| 1419 |
+
for oct_i in range(max(1, int(octaves))):
|
| 1420 |
+
lattice = rng.uniform(-1.0, 1.0, (grid_n, grid_n, grid_n)).astype(
|
| 1421 |
+
np.float32
|
| 1422 |
+
)
|
| 1423 |
+
lattice = ndi.gaussian_filter(lattice, sigma=0.85, mode="wrap")
|
| 1424 |
+
shift = np.array(
|
| 1425 |
+
[11.3 * oct_i, -7.9 * oct_i, 5.7 * oct_i], dtype=np.float32
|
| 1426 |
+
)
|
| 1427 |
+
coords = (pts * freq + shift) * (grid_n / 8.0)
|
| 1428 |
+
flat_c = coords.reshape(-1, 3).T
|
| 1429 |
+
sampled = ndi.map_coordinates(
|
| 1430 |
+
lattice, flat_c, order=1, mode="wrap"
|
| 1431 |
+
).reshape(pts.shape[:-1])
|
| 1432 |
+
total += amp * sampled
|
| 1433 |
+
amp_sum += amp
|
| 1434 |
+
amp *= float(persistence)
|
| 1435 |
+
freq *= 2.03
|
| 1436 |
+
|
| 1437 |
+
normed = total / max(amp_sum * 0.45, 1e-6)
|
| 1438 |
+
return np.clip(normed, -1.0, 1.0)
|
| 1439 |
+
|
| 1440 |
+
|
| 1441 |
+
def triplanar_project_map(
|
| 1442 |
+
map_2d: np.ndarray,
|
| 1443 |
+
xyz: np.ndarray,
|
| 1444 |
+
world_normal: np.ndarray,
|
| 1445 |
+
*,
|
| 1446 |
+
texels_per_meter: float = 4000.0,
|
| 1447 |
+
sharpness: float = 4.0,
|
| 1448 |
+
preserve_float: bool = False,
|
| 1449 |
+
) -> np.ndarray:
|
| 1450 |
+
"""Projects any 2D grayscale or RGB map onto 3D `(X, Y, Z)` without UV seams."""
|
| 1451 |
+
src = np.asarray(map_2d, dtype=np.float32)
|
| 1452 |
+
mh, mw = src.shape[:2]
|
| 1453 |
+
pts = np.asarray(xyz, dtype=np.float32) * float(texels_per_meter)
|
| 1454 |
+
nrm = np.abs(np.asarray(world_normal, dtype=np.float32))
|
| 1455 |
+
weights = np.power(np.maximum(nrm, 1e-4), float(sharpness))
|
| 1456 |
+
weights /= np.maximum(np.sum(weights, axis=-1, keepdims=True), 1e-6)
|
| 1457 |
+
|
| 1458 |
+
def _sample_plane(u_px: np.ndarray, v_px: np.ndarray) -> np.ndarray:
|
| 1459 |
+
u_fl = np.floor(u_px)
|
| 1460 |
+
v_fl = np.floor(v_px)
|
| 1461 |
+
fu = (u_px - u_fl).astype(np.float32)
|
| 1462 |
+
fv = (v_px - v_fl).astype(np.float32)
|
| 1463 |
+
ix0 = np.mod(u_fl.astype(np.int32), mw)
|
| 1464 |
+
iy0 = np.mod(v_fl.astype(np.int32), mh)
|
| 1465 |
+
ix1 = (ix0 + 1) % mw
|
| 1466 |
+
iy1 = (iy0 + 1) % mh
|
| 1467 |
+
s00 = src[iy0, ix0]
|
| 1468 |
+
s10 = src[iy0, ix1]
|
| 1469 |
+
s01 = src[iy1, ix0]
|
| 1470 |
+
s11 = src[iy1, ix1]
|
| 1471 |
+
if src.ndim == 3:
|
| 1472 |
+
fu = fu[..., None]
|
| 1473 |
+
fv = fv[..., None]
|
| 1474 |
+
top = s00 * (1.0 - fu) + s10 * fu
|
| 1475 |
+
bot = s01 * (1.0 - fu) + s11 * fu
|
| 1476 |
+
return top * (1.0 - fv) + bot * fv
|
| 1477 |
+
|
| 1478 |
+
proj_x = _sample_plane(pts[..., 1], -pts[..., 2])
|
| 1479 |
+
proj_y = _sample_plane(pts[..., 0], -pts[..., 2])
|
| 1480 |
+
proj_z = _sample_plane(pts[..., 0], -pts[..., 1])
|
| 1481 |
+
|
| 1482 |
+
if src.ndim == 3:
|
| 1483 |
+
blended = (
|
| 1484 |
+
weights[..., 0:1] * proj_x
|
| 1485 |
+
+ weights[..., 1:2] * proj_y
|
| 1486 |
+
+ weights[..., 2:3] * proj_z
|
| 1487 |
+
)
|
| 1488 |
+
else:
|
| 1489 |
+
blended = (
|
| 1490 |
+
weights[..., 0] * proj_x
|
| 1491 |
+
+ weights[..., 1] * proj_y
|
| 1492 |
+
+ weights[..., 2] * proj_z
|
| 1493 |
+
)
|
| 1494 |
+
if map_2d.dtype == np.uint8 and not preserve_float and not _IN_3D_HEIGHT_DIFF:
|
| 1495 |
+
return np.clip(np.round(blended), 0, 255).astype(np.uint8)
|
| 1496 |
+
return blended
|
tasks/belt-pick/environment/world/skills/blender-creation/scripts/blender_mesh_utils.py
ADDED
|
@@ -0,0 +1,1847 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# https://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Zero-magic Blender mesh I/O, declarative organic builders, UV pack, hull clipping, and Cycles PBR baking.
|
| 16 |
+
|
| 17 |
+
Runs inside headless Blender (`PYTHONDONTWRITEBYTECODE=1 blender -b -P`).
|
| 18 |
+
|
| 19 |
+
Core functions:
|
| 20 |
+
- `clear_scene`: Removes all objects and orphan data blocks and configures SI
|
| 21 |
+
metric units (`1.0 m`).
|
| 22 |
+
- `skin_skeleton`, `metaball_sdf`, `swept_tube`, `voxel_smooth_union`,
|
| 23 |
+
`apply_boolean_cutter`: Declarative low-DOF organic and boolean-cutter
|
| 24 |
+
builders.
|
| 25 |
+
- `smart_seam_unwrap`, `smart_uv_project` & `pack_shared_uv_atlas`: Native
|
| 26 |
+
Blender C++ conformal / smart UV unwrapping and multi-object
|
| 27 |
+
`bpy.ops.uv.pack_islands` `[0, 1]^2` packing.
|
| 28 |
+
- `finalize_and_export_obj`: Non-destructively exports a body-local `.obj` via
|
| 29 |
+
Blender's C++ `bpy.ops.wm.obj_export` (`forward_axis='Y', up_axis='Z'`).
|
| 30 |
+
- `export_convex_hull_col`: Builds plane-clipped (`bmesh.ops.bisect_plane`),
|
| 31 |
+
body-local convex collision hulls (`<= max_verts`, default `64`) from single
|
| 32 |
+
or multi-object meshes/curves or 3D point clouds with strict volume checks.
|
| 33 |
+
- `bake_pbr_maps`: Bakes multi-material / multi-object `Principled BSDF` graphs
|
| 34 |
+
under `Raw` color management (`basecolor` in sRGB; `roughness`, `metallic`,
|
| 35 |
+
`normal` in linear `Non-Color`).
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import os
|
| 41 |
+
import sys
|
| 42 |
+
|
| 43 |
+
sys.dont_write_bytecode = True
|
| 44 |
+
|
| 45 |
+
import array # pylint: disable=g-import-not-at-top
|
| 46 |
+
from collections.abc import Mapping, Sequence # pylint: disable=g-import-not-at-top
|
| 47 |
+
import hashlib # pylint: disable=g-import-not-at-top
|
| 48 |
+
import math # pylint: disable=g-import-not-at-top
|
| 49 |
+
from typing import Any # pylint: disable=g-import-not-at-top
|
| 50 |
+
|
| 51 |
+
import bmesh # pylint: disable=import-error,g-import-not-at-top
|
| 52 |
+
import bpy # pylint: disable=import-error,g-import-not-at-top
|
| 53 |
+
import mathutils # pylint: disable=import-error,g-import-not-at-top
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def clear_scene() -> None:
|
| 57 |
+
"""Clears all scene objects, meshes, materials, images, curves, cameras, and lights."""
|
| 58 |
+
try:
|
| 59 |
+
if bpy.context.active_object and bpy.context.active_object.mode != 'OBJECT':
|
| 60 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 61 |
+
except RuntimeError:
|
| 62 |
+
pass
|
| 63 |
+
|
| 64 |
+
for obj in list(bpy.data.objects):
|
| 65 |
+
bpy.data.objects.remove(obj, do_unlink=True)
|
| 66 |
+
|
| 67 |
+
for block_coll in (
|
| 68 |
+
bpy.data.meshes,
|
| 69 |
+
bpy.data.materials,
|
| 70 |
+
bpy.data.images,
|
| 71 |
+
bpy.data.curves,
|
| 72 |
+
bpy.data.cameras,
|
| 73 |
+
bpy.data.lights,
|
| 74 |
+
):
|
| 75 |
+
for block in list(block_coll):
|
| 76 |
+
block_coll.remove(block)
|
| 77 |
+
|
| 78 |
+
scene = bpy.context.scene
|
| 79 |
+
scene.unit_settings.system = 'METRIC'
|
| 80 |
+
scene.unit_settings.scale_length = 1.0
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _select_only(target_obj: bpy.types.Object) -> None:
|
| 84 |
+
"""Selects exclusively `target_obj` and sets it as the active scene object."""
|
| 85 |
+
for obj in bpy.data.objects:
|
| 86 |
+
if obj.select_get():
|
| 87 |
+
obj.select_set(False)
|
| 88 |
+
target_obj.select_set(True)
|
| 89 |
+
bpy.context.view_layer.objects.active = target_obj
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _resolve_object_list(raw_objs: Any) -> list[bpy.types.Object]:
|
| 93 |
+
"""Resolves a single `Object`/`str` or sequence of `Object`/`str` into `Object`s."""
|
| 94 |
+
if raw_objs is None:
|
| 95 |
+
return []
|
| 96 |
+
if isinstance(raw_objs, (bpy.types.Object, str)):
|
| 97 |
+
items: Sequence[Any] = [raw_objs]
|
| 98 |
+
else:
|
| 99 |
+
items = list(raw_objs)
|
| 100 |
+
resolved: list[bpy.types.Object] = []
|
| 101 |
+
seen: set[bpy.types.Object] = set()
|
| 102 |
+
for item in items:
|
| 103 |
+
if item is None:
|
| 104 |
+
continue
|
| 105 |
+
if isinstance(item, str):
|
| 106 |
+
obj = (
|
| 107 |
+
bpy.data.objects.get(item)
|
| 108 |
+
or bpy.data.objects.get(f'{item}_vis')
|
| 109 |
+
or bpy.data.objects.get(f'{item}_cutter')
|
| 110 |
+
or (
|
| 111 |
+
bpy.data.objects.get(item[:-4]) if item.endswith('_vis') else None
|
| 112 |
+
)
|
| 113 |
+
or bpy.data.objects[item]
|
| 114 |
+
)
|
| 115 |
+
elif isinstance(item, bpy.types.Object):
|
| 116 |
+
obj = item
|
| 117 |
+
else:
|
| 118 |
+
raise TypeError(
|
| 119 |
+
'Expected bpy.types.Object or str object name, got '
|
| 120 |
+
f'{type(item).__name__}'
|
| 121 |
+
)
|
| 122 |
+
if obj not in seen:
|
| 123 |
+
seen.add(obj)
|
| 124 |
+
resolved.append(obj)
|
| 125 |
+
return resolved
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _compute_corner_normals_hash(mesh_data: bpy.types.Mesh) -> str:
|
| 129 |
+
"""Computes a fast deterministic checksum over `mesh_data.corner_normals`."""
|
| 130 |
+
n_loops = len(mesh_data.loops)
|
| 131 |
+
if n_loops == 0:
|
| 132 |
+
return 'empty'
|
| 133 |
+
buf = array.array('f', [0.0] * (n_loops * 3))
|
| 134 |
+
mesh_data.corner_normals.foreach_get('vector', buf)
|
| 135 |
+
quant = array.array('i', (int(round(float(x) * 10000.0)) for x in buf))
|
| 136 |
+
return hashlib.blake2b(quant.tobytes(), digest_size=16).hexdigest()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _apply_weighted_normals(
|
| 140 |
+
target_obj: bpy.types.Object,
|
| 141 |
+
*,
|
| 142 |
+
force_smooth: bool = False,
|
| 143 |
+
) -> None:
|
| 144 |
+
"""Applies `WEIGHTED_NORMAL(keep_sharp=True)` without altering scene selection."""
|
| 145 |
+
mesh_data = target_obj.data
|
| 146 |
+
if len(mesh_data.polygons) == 0:
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
if force_smooth:
|
| 150 |
+
if hasattr(mesh_data, 'shade_smooth'):
|
| 151 |
+
mesh_data.shade_smooth()
|
| 152 |
+
else:
|
| 153 |
+
for poly in mesh_data.polygons:
|
| 154 |
+
poly.use_smooth = True
|
| 155 |
+
else:
|
| 156 |
+
has_smooth = any(poly.use_smooth for poly in mesh_data.polygons)
|
| 157 |
+
has_sharp = any(edge.use_edge_sharp for edge in mesh_data.edges)
|
| 158 |
+
if not has_smooth and not has_sharp:
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
prev_active = bpy.context.view_layer.objects.active
|
| 162 |
+
prev_selected = [o for o in bpy.data.objects if o.select_get()]
|
| 163 |
+
prev_hide_vp = bool(target_obj.hide_viewport)
|
| 164 |
+
target_obj.hide_viewport = False
|
| 165 |
+
|
| 166 |
+
try:
|
| 167 |
+
if bpy.context.active_object and bpy.context.active_object.mode != 'OBJECT':
|
| 168 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 169 |
+
_select_only(target_obj)
|
| 170 |
+
|
| 171 |
+
if getattr(mesh_data, 'has_custom_normals', False):
|
| 172 |
+
try:
|
| 173 |
+
with bpy.context.temp_override(
|
| 174 |
+
object=target_obj, active_object=target_obj
|
| 175 |
+
):
|
| 176 |
+
bpy.ops.mesh.customdata_custom_splitnormals_clear()
|
| 177 |
+
except RuntimeError:
|
| 178 |
+
cn_attr = mesh_data.attributes.get('custom_normal')
|
| 179 |
+
if cn_attr is not None:
|
| 180 |
+
mesh_data.attributes.remove(cn_attr)
|
| 181 |
+
|
| 182 |
+
wn_mod = target_obj.modifiers.new(
|
| 183 |
+
name='_WeightedNormal', type='WEIGHTED_NORMAL'
|
| 184 |
+
)
|
| 185 |
+
wn_mod.weight = 100
|
| 186 |
+
wn_mod.keep_sharp = True
|
| 187 |
+
applied = False
|
| 188 |
+
try:
|
| 189 |
+
with bpy.context.temp_override(
|
| 190 |
+
object=target_obj, active_object=target_obj
|
| 191 |
+
):
|
| 192 |
+
bpy.ops.object.modifier_apply(modifier=wn_mod.name)
|
| 193 |
+
applied = True
|
| 194 |
+
except RuntimeError:
|
| 195 |
+
if wn_mod.name in target_obj.modifiers:
|
| 196 |
+
target_obj.modifiers.remove(wn_mod)
|
| 197 |
+
mesh_data.update()
|
| 198 |
+
if '_wn_managed_normals' in target_obj:
|
| 199 |
+
del target_obj['_wn_managed_normals']
|
| 200 |
+
if applied:
|
| 201 |
+
target_obj['_wn_norm_hash'] = _compute_corner_normals_hash(mesh_data)
|
| 202 |
+
finally:
|
| 203 |
+
target_obj.hide_viewport = prev_hide_vp
|
| 204 |
+
for obj in bpy.data.objects:
|
| 205 |
+
want_sel = obj in prev_selected
|
| 206 |
+
if obj.select_get() != want_sel:
|
| 207 |
+
obj.select_set(want_sel)
|
| 208 |
+
if prev_active is not None and prev_active.name in bpy.data.objects:
|
| 209 |
+
bpy.context.view_layer.objects.active = prev_active
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _apply_boolean_modifier_safe(
|
| 213 |
+
target_obj: bpy.types.Object,
|
| 214 |
+
operand_obj: bpy.types.Object,
|
| 215 |
+
operation: str = 'DIFFERENCE',
|
| 216 |
+
) -> None:
|
| 217 |
+
"""Applies a Blender `BOOLEAN` modifier (`MANIFOLD` with welded `EXACT` fallback)."""
|
| 218 |
+
prev_active = bpy.context.view_layer.objects.active
|
| 219 |
+
prev_selected = [o for o in bpy.data.objects if o.select_get()]
|
| 220 |
+
tmp_operand: bpy.types.Object | None = None
|
| 221 |
+
tmp_mesh: bpy.types.Mesh | None = None
|
| 222 |
+
try:
|
| 223 |
+
if bpy.context.active_object and bpy.context.active_object.mode != 'OBJECT':
|
| 224 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 225 |
+
_select_only(target_obj)
|
| 226 |
+
|
| 227 |
+
mod = target_obj.modifiers.new(name='_BoolOp', type='BOOLEAN')
|
| 228 |
+
mod.operation = operation
|
| 229 |
+
mod.solver = 'MANIFOLD'
|
| 230 |
+
mod.object = operand_obj
|
| 231 |
+
try:
|
| 232 |
+
bpy.ops.object.modifier_apply(modifier=mod.name)
|
| 233 |
+
except RuntimeError:
|
| 234 |
+
pass
|
| 235 |
+
|
| 236 |
+
if mod.name in target_obj.modifiers:
|
| 237 |
+
# Fallback for Blender builds compiled without WITH_MANIFOLD: weld operand
|
| 238 |
+
# copy so split glTF UV vertices form a closed watertight solid for EXACT.
|
| 239 |
+
tmp_mesh = operand_obj.data.copy()
|
| 240 |
+
bm = bmesh.new()
|
| 241 |
+
bm.from_mesh(tmp_mesh)
|
| 242 |
+
bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=1e-6)
|
| 243 |
+
bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
|
| 244 |
+
bm.to_mesh(tmp_mesh)
|
| 245 |
+
bm.free()
|
| 246 |
+
tmp_mesh.update()
|
| 247 |
+
tmp_operand = bpy.data.objects.new('_tmp_bool_operand', tmp_mesh)
|
| 248 |
+
bpy.context.scene.collection.objects.link(tmp_operand)
|
| 249 |
+
tmp_operand.matrix_world = operand_obj.matrix_world.copy()
|
| 250 |
+
mod.solver = 'EXACT'
|
| 251 |
+
if hasattr(mod, 'use_self'):
|
| 252 |
+
mod.use_self = True
|
| 253 |
+
mod.object = tmp_operand
|
| 254 |
+
_select_only(target_obj)
|
| 255 |
+
bpy.ops.object.modifier_apply(modifier=mod.name)
|
| 256 |
+
target_obj.data.update()
|
| 257 |
+
finally:
|
| 258 |
+
if tmp_operand is not None and tmp_operand.name in bpy.data.objects:
|
| 259 |
+
bpy.data.objects.remove(tmp_operand, do_unlink=True)
|
| 260 |
+
if tmp_mesh is not None and tmp_mesh.users == 0:
|
| 261 |
+
bpy.data.meshes.remove(tmp_mesh)
|
| 262 |
+
for obj in bpy.data.objects:
|
| 263 |
+
want_sel = obj in prev_selected
|
| 264 |
+
if obj.select_get() != want_sel:
|
| 265 |
+
obj.select_set(want_sel)
|
| 266 |
+
if prev_active is not None and prev_active.name in bpy.data.objects:
|
| 267 |
+
bpy.context.view_layer.objects.active = prev_active
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def skin_skeleton(
|
| 271 |
+
name: str,
|
| 272 |
+
nodes_xyzr: Sequence[Sequence[Any]],
|
| 273 |
+
edges: Sequence[Any] | None = None,
|
| 274 |
+
*,
|
| 275 |
+
radii: Sequence[Any] | float | None = None,
|
| 276 |
+
subsurf_levels: int = 2,
|
| 277 |
+
subdiv: int | None = None,
|
| 278 |
+
) -> bpy.types.Object:
|
| 279 |
+
"""Builds a watertight organic mesh from a skeleton graph via `SKIN` + `SUBSURF`.
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
name: Scene object name.
|
| 283 |
+
nodes_xyzr: Sequence of `(x, y, z, r)`, `(x, y, z, (rx, ry))`, or `(x, y,
|
| 284 |
+
z)` in meters.
|
| 285 |
+
edges: Sequence of `(u_idx, v_idx)` vertex index pairs (defaults to
|
| 286 |
+
sequential chain), or per-node radii if called as `skin_skeleton(name,
|
| 287 |
+
nodes_xyz, radii)`.
|
| 288 |
+
radii: Optional explicit per-node radii (or uniform float radius).
|
| 289 |
+
subsurf_levels: Subdivision surface level (`2` default).
|
| 290 |
+
subdiv: Alias for `subsurf_levels`.
|
| 291 |
+
"""
|
| 292 |
+
if subdiv is not None:
|
| 293 |
+
subsurf_levels = int(subdiv)
|
| 294 |
+
old = bpy.data.objects.get(name)
|
| 295 |
+
if old is not None:
|
| 296 |
+
bpy.data.objects.remove(old, do_unlink=True)
|
| 297 |
+
|
| 298 |
+
# Detect if the 3rd positional arg `edges` was actually passed as `radii`
|
| 299 |
+
if (
|
| 300 |
+
edges is not None
|
| 301 |
+
and radii is None
|
| 302 |
+
and len(edges) == len(nodes_xyzr)
|
| 303 |
+
and all(len(n) == 3 for n in nodes_xyzr)
|
| 304 |
+
and (
|
| 305 |
+
not hasattr(edges[0], '__len__')
|
| 306 |
+
or any(isinstance(x, float) for x in edges[0])
|
| 307 |
+
)
|
| 308 |
+
):
|
| 309 |
+
radii = edges
|
| 310 |
+
edges = None
|
| 311 |
+
|
| 312 |
+
verts = [(float(n[0]), float(n[1]), float(n[2])) for n in nodes_xyzr]
|
| 313 |
+
if edges is None:
|
| 314 |
+
edge_pairs = [(i, i + 1) for i in range(max(0, len(verts) - 1))]
|
| 315 |
+
else:
|
| 316 |
+
edge_pairs = [(int(a), int(b)) for a, b in edges]
|
| 317 |
+
mesh = bpy.data.meshes.new(name)
|
| 318 |
+
mesh.from_pydata(verts, edge_pairs, [])
|
| 319 |
+
mesh.update()
|
| 320 |
+
|
| 321 |
+
obj = bpy.data.objects.new(name, mesh)
|
| 322 |
+
bpy.context.scene.collection.objects.link(obj)
|
| 323 |
+
skin_mod = obj.modifiers.new(name='Skin', type='SKIN')
|
| 324 |
+
skin_mod.use_smooth_shade = True
|
| 325 |
+
|
| 326 |
+
for idx, n in enumerate(nodes_xyzr):
|
| 327 |
+
if radii is not None:
|
| 328 |
+
r_val = radii[idx] if hasattr(radii, '__len__') else radii
|
| 329 |
+
else:
|
| 330 |
+
r_val = n[3] if len(n) > 3 else 0.01
|
| 331 |
+
if hasattr(r_val, '__len__'):
|
| 332 |
+
rx, ry = float(r_val[0]), float(r_val[1])
|
| 333 |
+
else:
|
| 334 |
+
rx = ry = float(r_val)
|
| 335 |
+
obj.data.skin_vertices[0].data[idx].radius = (max(rx, 1e-5), max(ry, 1e-5))
|
| 336 |
+
if nodes_xyzr:
|
| 337 |
+
obj.data.skin_vertices[0].data[0].use_root = True
|
| 338 |
+
|
| 339 |
+
sub_mod = obj.modifiers.new(name='Subsurf', type='SUBSURF')
|
| 340 |
+
sub_mod.levels = max(0, int(subsurf_levels))
|
| 341 |
+
sub_mod.render_levels = max(0, int(subsurf_levels))
|
| 342 |
+
|
| 343 |
+
_select_only(obj)
|
| 344 |
+
bpy.ops.object.modifier_apply(modifier=skin_mod.name)
|
| 345 |
+
if sub_mod.levels > 0:
|
| 346 |
+
bpy.ops.object.modifier_apply(modifier=sub_mod.name)
|
| 347 |
+
else:
|
| 348 |
+
obj.modifiers.remove(sub_mod)
|
| 349 |
+
if hasattr(obj.data, 'shade_smooth'):
|
| 350 |
+
obj.data.shade_smooth()
|
| 351 |
+
obj.data.update()
|
| 352 |
+
return obj
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def metaball_sdf(
|
| 356 |
+
name: str,
|
| 357 |
+
elements: Sequence[Mapping[str, Any]],
|
| 358 |
+
*,
|
| 359 |
+
threshold: float = 0.6,
|
| 360 |
+
resolution: float = 0.002,
|
| 361 |
+
) -> bpy.types.Object:
|
| 362 |
+
"""Evaluates analytical implicit SDF primitives (`BALL`, `CAPSULE`, `ELLIPSOID`, `CUBE`) and converts to mesh.
|
| 363 |
+
|
| 364 |
+
Each dict in `elements` supports:
|
| 365 |
+
- `'type'`: `'BALL'` (default), `'CAPSULE'`, `'ELLIPSOID'`, `'CUBE'`,
|
| 366 |
+
`'PLANE'`
|
| 367 |
+
- `'co'` or `'pos'`: `(x, y, z)` in meters
|
| 368 |
+
- `'radius'`: float radius in meters
|
| 369 |
+
- `'size'` or `'size_xyz'`: `(sx, sy, sz)` for `CAPSULE`/`ELLIPSOID`/`CUBE`
|
| 370 |
+
- `'stiffness'`: float blend stiffness (`2.0` default)
|
| 371 |
+
- `'use_negative'`: bool (`True` for thumb indents / subtractive cavities)
|
| 372 |
+
"""
|
| 373 |
+
old = bpy.data.objects.get(name)
|
| 374 |
+
if old is not None:
|
| 375 |
+
bpy.data.objects.remove(old, do_unlink=True)
|
| 376 |
+
|
| 377 |
+
mball = bpy.data.metaballs.new(name)
|
| 378 |
+
mball.threshold = max(0.01, float(threshold))
|
| 379 |
+
mball.resolution = max(0.0005, float(resolution))
|
| 380 |
+
mball.render_resolution = mball.resolution
|
| 381 |
+
|
| 382 |
+
for spec in elements:
|
| 383 |
+
etype = str(spec.get('type', 'BALL')).upper()
|
| 384 |
+
el = mball.elements.new(type=etype)
|
| 385 |
+
co = spec.get('co', spec.get('pos', (0.0, 0.0, 0.0)))
|
| 386 |
+
el.co = (float(co[0]), float(co[1]), float(co[2]))
|
| 387 |
+
el.radius = float(spec.get('radius', 0.01))
|
| 388 |
+
if 'stiffness' in spec:
|
| 389 |
+
el.stiffness = float(spec['stiffness'])
|
| 390 |
+
el.use_negative = bool(spec.get('use_negative', False))
|
| 391 |
+
sz = spec.get('size', spec.get('size_xyz'))
|
| 392 |
+
if sz is not None:
|
| 393 |
+
if hasattr(sz, '__len__'):
|
| 394 |
+
el.size_x = float(sz[0])
|
| 395 |
+
if len(sz) > 1:
|
| 396 |
+
el.size_y = float(sz[1])
|
| 397 |
+
if len(sz) > 2:
|
| 398 |
+
el.size_z = float(sz[2])
|
| 399 |
+
else:
|
| 400 |
+
el.size_x = float(sz)
|
| 401 |
+
|
| 402 |
+
m_obj = bpy.data.objects.new(name, mball)
|
| 403 |
+
bpy.context.scene.collection.objects.link(m_obj)
|
| 404 |
+
bpy.context.view_layer.update()
|
| 405 |
+
_select_only(m_obj)
|
| 406 |
+
bpy.ops.object.convert(target='MESH')
|
| 407 |
+
out_obj = bpy.context.active_object
|
| 408 |
+
out_obj.name = name
|
| 409 |
+
out_obj.data.name = name
|
| 410 |
+
if hasattr(out_obj.data, 'shade_smooth'):
|
| 411 |
+
out_obj.data.shade_smooth()
|
| 412 |
+
out_obj.data.update()
|
| 413 |
+
return out_obj
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def swept_tube(
|
| 417 |
+
name: str,
|
| 418 |
+
points_xyzr: Sequence[Sequence[float]],
|
| 419 |
+
radius_or_profile: float | Sequence[float] | None = None,
|
| 420 |
+
*,
|
| 421 |
+
bevel_resolution: int = 6,
|
| 422 |
+
) -> bpy.types.Object:
|
| 423 |
+
"""Builds a 3D `NURBS` curve tube with per-point radius, end caps, and `WELD` modifier."""
|
| 424 |
+
old = bpy.data.objects.get(name)
|
| 425 |
+
if old is not None:
|
| 426 |
+
bpy.data.objects.remove(old, do_unlink=True)
|
| 427 |
+
|
| 428 |
+
curve = bpy.data.curves.new(name, type='CURVE')
|
| 429 |
+
curve.dimensions = '3D'
|
| 430 |
+
curve.bevel_depth = 1.0
|
| 431 |
+
curve.bevel_resolution = max(2, int(bevel_resolution))
|
| 432 |
+
curve.use_fill_caps = True
|
| 433 |
+
|
| 434 |
+
spline = curve.splines.new('NURBS')
|
| 435 |
+
spline.points.add(len(points_xyzr) - 1)
|
| 436 |
+
for idx, pt in enumerate(points_xyzr):
|
| 437 |
+
spline.points[idx].co = (float(pt[0]), float(pt[1]), float(pt[2]), 1.0)
|
| 438 |
+
if len(pt) > 3:
|
| 439 |
+
r_pt = float(pt[3])
|
| 440 |
+
elif radius_or_profile is not None:
|
| 441 |
+
if hasattr(radius_or_profile, '__len__'):
|
| 442 |
+
r_pt = float(radius_or_profile[min(idx, len(radius_or_profile) - 1)])
|
| 443 |
+
else:
|
| 444 |
+
r_pt = float(radius_or_profile)
|
| 445 |
+
else:
|
| 446 |
+
r_pt = 0.005
|
| 447 |
+
spline.points[idx].radius = r_pt
|
| 448 |
+
spline.use_endpoint_u = True
|
| 449 |
+
spline.order_u = min(4, len(points_xyzr))
|
| 450 |
+
|
| 451 |
+
c_obj = bpy.data.objects.new(name, curve)
|
| 452 |
+
bpy.context.scene.collection.objects.link(c_obj)
|
| 453 |
+
bpy.context.view_layer.update()
|
| 454 |
+
_select_only(c_obj)
|
| 455 |
+
bpy.ops.object.convert(target='MESH')
|
| 456 |
+
out_obj = bpy.context.active_object
|
| 457 |
+
out_obj.name = name
|
| 458 |
+
out_obj.data.name = name
|
| 459 |
+
w_mod = out_obj.modifiers.new(name='Weld', type='WELD')
|
| 460 |
+
w_mod.merge_threshold = 1e-5
|
| 461 |
+
bpy.ops.object.modifier_apply(modifier=w_mod.name)
|
| 462 |
+
if hasattr(out_obj.data, 'shade_smooth'):
|
| 463 |
+
out_obj.data.shade_smooth()
|
| 464 |
+
out_obj.data.update()
|
| 465 |
+
return out_obj
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def voxel_smooth_union(
|
| 469 |
+
name: str,
|
| 470 |
+
objects: Sequence[bpy.types.Object | str],
|
| 471 |
+
*,
|
| 472 |
+
voxel_size: float = 0.0015,
|
| 473 |
+
adaptivity: float = 0.0,
|
| 474 |
+
smooth_iterations: int = 6,
|
| 475 |
+
smooth_iters: int | None = None,
|
| 476 |
+
) -> bpy.types.Object:
|
| 477 |
+
"""Unions `objects` and applies `REMESH(mode='VOXEL')` + `SMOOTH` for organic fillets."""
|
| 478 |
+
if smooth_iters is not None:
|
| 479 |
+
smooth_iterations = int(smooth_iters)
|
| 480 |
+
resolved = _resolve_object_list(objects)
|
| 481 |
+
if not resolved:
|
| 482 |
+
raise ValueError(
|
| 483 |
+
f'voxel_smooth_union({name!r}) received empty objects list'
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
base_obj = resolved[0]
|
| 487 |
+
if base_obj.name != name:
|
| 488 |
+
base_obj.name = name
|
| 489 |
+
base_obj.data.name = name
|
| 490 |
+
|
| 491 |
+
for other in resolved[1:]:
|
| 492 |
+
_apply_boolean_modifier_safe(base_obj, other, operation='UNION')
|
| 493 |
+
if other.name in bpy.data.objects:
|
| 494 |
+
bpy.data.objects.remove(other, do_unlink=True)
|
| 495 |
+
|
| 496 |
+
_select_only(base_obj)
|
| 497 |
+
rem_mod = base_obj.modifiers.new(name='VoxelRemesh', type='REMESH')
|
| 498 |
+
rem_mod.mode = 'VOXEL'
|
| 499 |
+
rem_mod.voxel_size = max(0.0003, float(voxel_size))
|
| 500 |
+
if hasattr(rem_mod, 'adaptivity') and adaptivity > 0.0:
|
| 501 |
+
rem_mod.adaptivity = float(adaptivity)
|
| 502 |
+
rem_mod.use_smooth_shade = True
|
| 503 |
+
bpy.ops.object.modifier_apply(modifier=rem_mod.name)
|
| 504 |
+
|
| 505 |
+
if int(smooth_iterations) > 0:
|
| 506 |
+
sm_mod = base_obj.modifiers.new(name='Smooth', type='SMOOTH')
|
| 507 |
+
sm_mod.iterations = int(smooth_iterations)
|
| 508 |
+
sm_mod.factor = 0.5
|
| 509 |
+
bpy.ops.object.modifier_apply(modifier=sm_mod.name)
|
| 510 |
+
|
| 511 |
+
base_obj.data.update()
|
| 512 |
+
return base_obj
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def apply_boolean_cutter(
|
| 516 |
+
target_obj: bpy.types.Object | str,
|
| 517 |
+
cutter_obj: bpy.types.Object | str,
|
| 518 |
+
*,
|
| 519 |
+
operation: str = 'DIFFERENCE',
|
| 520 |
+
solver: str = 'MANIFOLD',
|
| 521 |
+
) -> bpy.types.Object:
|
| 522 |
+
"""Applies a Blender boolean `cutter_obj` (`DIFFERENCE`/`UNION`/`INTERSECT`) to `target_obj`."""
|
| 523 |
+
del solver
|
| 524 |
+
tgt = _resolve_object_list(target_obj)[0]
|
| 525 |
+
cut = _resolve_object_list(cutter_obj)[0]
|
| 526 |
+
_apply_boolean_modifier_safe(tgt, cut, operation=str(operation).upper())
|
| 527 |
+
return tgt
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def _compute_uv_span(target_obj: bpy.types.Object) -> float:
|
| 531 |
+
"""Returns `max(u_ptp, v_ptp)` across all UV loops of `target_obj`."""
|
| 532 |
+
if not target_obj.data.uv_layers:
|
| 533 |
+
return 0.0
|
| 534 |
+
uv_data = target_obj.data.uv_layers.active.data
|
| 535 |
+
if not uv_data:
|
| 536 |
+
return 0.0
|
| 537 |
+
us = [float(lp.uv.x) for lp in uv_data]
|
| 538 |
+
vs = [float(lp.uv.y) for lp in uv_data]
|
| 539 |
+
return max(max(us) - min(us), max(vs) - min(vs))
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _compute_uv_bbox_tuple(
|
| 543 |
+
target_obj: bpy.types.Object,
|
| 544 |
+
) -> tuple[float, float, float, float] | None:
|
| 545 |
+
"""Returns `(u_min, v_min, u_max, v_max)` for `target_obj`'s active UV layer, or `None`."""
|
| 546 |
+
if (
|
| 547 |
+
target_obj is None
|
| 548 |
+
or target_obj.type != 'MESH'
|
| 549 |
+
or not target_obj.data.uv_layers
|
| 550 |
+
):
|
| 551 |
+
return None
|
| 552 |
+
uv_layer = target_obj.data.uv_layers.active or target_obj.data.uv_layers[0]
|
| 553 |
+
if not uv_layer.data:
|
| 554 |
+
return None
|
| 555 |
+
us = [float(lp.uv.x) for lp in uv_layer.data]
|
| 556 |
+
vs = [float(lp.uv.y) for lp in uv_layer.data]
|
| 557 |
+
return (min(us), min(vs), max(us), max(vs))
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _uvs_need_unwrap(target_obj: bpy.types.Object) -> bool:
|
| 561 |
+
"""Returns True if `target_obj` has no UVs, degenerate UVs, or UVs outside `[-0.05, 1.05]` (e.g.
|
| 562 |
+
|
| 563 |
+
raw millimeter UVs).
|
| 564 |
+
"""
|
| 565 |
+
bbox = _compute_uv_bbox_tuple(target_obj)
|
| 566 |
+
if bbox is None:
|
| 567 |
+
return True
|
| 568 |
+
u_min, v_min, u_max, v_max = bbox
|
| 569 |
+
if (
|
| 570 |
+
u_min < -0.05
|
| 571 |
+
or v_min < -0.05
|
| 572 |
+
or u_max > 1.05
|
| 573 |
+
or v_max > 1.05
|
| 574 |
+
or (u_max - u_min) < 1e-5
|
| 575 |
+
or (v_max - v_min) < 1e-5
|
| 576 |
+
):
|
| 577 |
+
return True
|
| 578 |
+
return False
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def _bmesh_box_atlas_unwrap(
|
| 582 |
+
target_obj: bpy.types.Object, margin: float = 0.005
|
| 583 |
+
) -> None:
|
| 584 |
+
"""Context-free pure-`bmesh` 6-direction (`+-X, +-Y, +-Z`) UV fallback."""
|
| 585 |
+
bm = bmesh.new()
|
| 586 |
+
bm.from_mesh(target_obj.data)
|
| 587 |
+
if not bm.faces:
|
| 588 |
+
bm.free()
|
| 589 |
+
return
|
| 590 |
+
uv_layer = bm.loops.layers.uv.active
|
| 591 |
+
if uv_layer is None:
|
| 592 |
+
uv_layer = bm.loops.layers.uv.new('UVMap')
|
| 593 |
+
|
| 594 |
+
bmin = mathutils.Vector((1e9, 1e9, 1e9))
|
| 595 |
+
bmax = mathutils.Vector((-1e9, -1e9, -1e9))
|
| 596 |
+
for v in bm.verts:
|
| 597 |
+
for k in range(3):
|
| 598 |
+
bmin[k] = min(bmin[k], v.co[k])
|
| 599 |
+
bmax[k] = max(bmax[k], v.co[k])
|
| 600 |
+
span = mathutils.Vector((
|
| 601 |
+
max(bmax.x - bmin.x, 1e-6),
|
| 602 |
+
max(bmax.y - bmin.y, 1e-6),
|
| 603 |
+
max(bmax.z - bmin.z, 1e-6),
|
| 604 |
+
))
|
| 605 |
+
|
| 606 |
+
cell_w = 1.0 / 3.0
|
| 607 |
+
cell_h = 1.0 / 2.0
|
| 608 |
+
pad_u = min(0.08, max(0.002, float(margin))) * cell_w
|
| 609 |
+
pad_v = min(0.08, max(0.002, float(margin))) * cell_h
|
| 610 |
+
in_w = cell_w - 2.0 * pad_u
|
| 611 |
+
in_h = cell_h - 2.0 * pad_v
|
| 612 |
+
|
| 613 |
+
for face in bm.faces:
|
| 614 |
+
n = face.normal
|
| 615 |
+
ax, ay, az = abs(n.x), abs(n.y), abs(n.z)
|
| 616 |
+
if ax >= ay and ax >= az:
|
| 617 |
+
col, row = (0, 0) if n.x >= 0.0 else (0, 1)
|
| 618 |
+
proj = lambda c: ((c.y - bmin.y) / span.y, (c.z - bmin.z) / span.z)
|
| 619 |
+
elif ay >= ax and ay >= az:
|
| 620 |
+
col, row = (1, 0) if n.y >= 0.0 else (1, 1)
|
| 621 |
+
proj = lambda c: ((c.x - bmin.x) / span.x, (c.z - bmin.z) / span.z)
|
| 622 |
+
else:
|
| 623 |
+
col, row = (2, 0) if n.z >= 0.0 else (2, 1)
|
| 624 |
+
proj = lambda c: ((c.x - bmin.x) / span.x, (c.y - bmin.y) / span.y)
|
| 625 |
+
|
| 626 |
+
u_base = col * cell_w + pad_u
|
| 627 |
+
v_base = row * cell_h + pad_v
|
| 628 |
+
for loop in face.loops:
|
| 629 |
+
ru, rv = proj(loop.vert.co)
|
| 630 |
+
loop[uv_layer].uv = (
|
| 631 |
+
u_base + max(0.0, min(1.0, ru)) * in_w,
|
| 632 |
+
v_base + max(0.0, min(1.0, rv)) * in_h,
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
bm.to_mesh(target_obj.data)
|
| 636 |
+
bm.free()
|
| 637 |
+
target_obj.data.update()
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def smart_seam_unwrap(
|
| 641 |
+
target_obj: bpy.types.Object,
|
| 642 |
+
*,
|
| 643 |
+
angle_limit_deg: float = 66.0,
|
| 644 |
+
margin: float = 0.005,
|
| 645 |
+
) -> bpy.types.Object:
|
| 646 |
+
"""Unwraps `target_obj` using native Blender conformal unwrap or smart UV project.
|
| 647 |
+
|
| 648 |
+
Zero hidden seam injection, zero UV island mirroring, and zero island
|
| 649 |
+
rotation overrides:
|
| 650 |
+
- If `target_obj` already has marked `use_seam` edges (`seam_count > 0`),
|
| 651 |
+
runs `bpy.ops.uv.unwrap(method='CONFORMAL', margin=margin)`.
|
| 652 |
+
- If `seam_count == 0`, runs `bpy.ops.uv.smart_project(angle_limit=...,
|
| 653 |
+
island_margin=margin)`.
|
| 654 |
+
|
| 655 |
+
Args:
|
| 656 |
+
target_obj: Blender mesh object to unwrap.
|
| 657 |
+
angle_limit_deg: Angle limit in degrees for `smart_project` when `seam_count
|
| 658 |
+
== 0` (`66.0` default).
|
| 659 |
+
margin: UV island margin in `[0, 1]` space (`0.005` default).
|
| 660 |
+
|
| 661 |
+
Returns:
|
| 662 |
+
`target_obj` with unwrapped active UV layer.
|
| 663 |
+
"""
|
| 664 |
+
mesh_data = target_obj.data
|
| 665 |
+
if len(mesh_data.polygons) == 0:
|
| 666 |
+
return target_obj
|
| 667 |
+
|
| 668 |
+
if not mesh_data.uv_layers:
|
| 669 |
+
mesh_data.uv_layers.new(name='UVMap')
|
| 670 |
+
|
| 671 |
+
seam_count = sum(1 for edge in mesh_data.edges if edge.use_seam)
|
| 672 |
+
|
| 673 |
+
prev_active = bpy.context.view_layer.objects.active
|
| 674 |
+
prev_selected = [o for o in bpy.data.objects if o.select_get()]
|
| 675 |
+
prev_hide = bool(target_obj.hide_viewport)
|
| 676 |
+
target_obj.hide_viewport = False
|
| 677 |
+
op_succeeded = False
|
| 678 |
+
|
| 679 |
+
try:
|
| 680 |
+
if bpy.context.active_object and bpy.context.active_object.mode != 'OBJECT':
|
| 681 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 682 |
+
_select_only(target_obj)
|
| 683 |
+
bpy.ops.object.mode_set(mode='EDIT')
|
| 684 |
+
bpy.ops.mesh.select_mode(type='FACE')
|
| 685 |
+
bpy.ops.mesh.reveal()
|
| 686 |
+
bpy.ops.mesh.select_all(action='SELECT')
|
| 687 |
+
if seam_count > 0:
|
| 688 |
+
bpy.ops.uv.unwrap(method='CONFORMAL', margin=float(margin))
|
| 689 |
+
op_succeeded = True
|
| 690 |
+
if _uvs_need_unwrap(target_obj):
|
| 691 |
+
bpy.ops.uv.smart_project(
|
| 692 |
+
angle_limit=math.radians(float(angle_limit_deg)),
|
| 693 |
+
island_margin=float(margin),
|
| 694 |
+
)
|
| 695 |
+
else:
|
| 696 |
+
bpy.ops.uv.smart_project(
|
| 697 |
+
angle_limit=math.radians(float(angle_limit_deg)),
|
| 698 |
+
island_margin=float(margin),
|
| 699 |
+
)
|
| 700 |
+
op_succeeded = True
|
| 701 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 702 |
+
except RuntimeError:
|
| 703 |
+
try:
|
| 704 |
+
if (
|
| 705 |
+
bpy.context.active_object
|
| 706 |
+
and bpy.context.active_object.mode != 'OBJECT'
|
| 707 |
+
):
|
| 708 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 709 |
+
except RuntimeError:
|
| 710 |
+
pass
|
| 711 |
+
finally:
|
| 712 |
+
target_obj.hide_viewport = prev_hide
|
| 713 |
+
for obj in bpy.data.objects:
|
| 714 |
+
want_sel = obj in prev_selected
|
| 715 |
+
if obj.select_get() != want_sel:
|
| 716 |
+
obj.select_set(want_sel)
|
| 717 |
+
if prev_active is not None and prev_active.name in bpy.data.objects:
|
| 718 |
+
bpy.context.view_layer.objects.active = prev_active
|
| 719 |
+
|
| 720 |
+
if not op_succeeded or _uvs_need_unwrap(target_obj):
|
| 721 |
+
_bmesh_box_atlas_unwrap(target_obj, margin=float(margin))
|
| 722 |
+
mesh_data.update()
|
| 723 |
+
return target_obj
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
def smart_uv_project(
|
| 727 |
+
objects: (
|
| 728 |
+
bpy.types.Object
|
| 729 |
+
| str
|
| 730 |
+
| list[bpy.types.Object | str]
|
| 731 |
+
| Sequence[bpy.types.Object | str]
|
| 732 |
+
),
|
| 733 |
+
*,
|
| 734 |
+
angle_limit_deg: float = 66.0,
|
| 735 |
+
island_margin: float = 0.01,
|
| 736 |
+
margin: float | None = None,
|
| 737 |
+
) -> list[bpy.types.Object]:
|
| 738 |
+
"""Unwraps each mesh object in `objects` individually into `[0, 1]^2` via `bpy.ops.uv.smart_project`.
|
| 739 |
+
|
| 740 |
+
Never packs multiple objects into a shared atlas.
|
| 741 |
+
"""
|
| 742 |
+
eff_margin = float(margin if margin is not None else island_margin)
|
| 743 |
+
resolved = _resolve_object_list(objects)
|
| 744 |
+
valid = [o for o in resolved if o.type == 'MESH' and len(o.data.polygons) > 0]
|
| 745 |
+
if not valid:
|
| 746 |
+
return []
|
| 747 |
+
|
| 748 |
+
prev_active = bpy.context.view_layer.objects.active
|
| 749 |
+
prev_selected = [o for o in bpy.data.objects if o.select_get()]
|
| 750 |
+
|
| 751 |
+
try:
|
| 752 |
+
for target_obj in valid:
|
| 753 |
+
mesh_data = target_obj.data
|
| 754 |
+
if not mesh_data.uv_layers:
|
| 755 |
+
mesh_data.uv_layers.new(name='UVMap')
|
| 756 |
+
prev_hide = bool(target_obj.hide_viewport)
|
| 757 |
+
target_obj.hide_viewport = False
|
| 758 |
+
op_succeeded = False
|
| 759 |
+
try:
|
| 760 |
+
if (
|
| 761 |
+
bpy.context.active_object
|
| 762 |
+
and bpy.context.active_object.mode != 'OBJECT'
|
| 763 |
+
):
|
| 764 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 765 |
+
_select_only(target_obj)
|
| 766 |
+
bpy.ops.object.mode_set(mode='EDIT')
|
| 767 |
+
bpy.ops.mesh.select_mode(type='FACE')
|
| 768 |
+
bpy.ops.mesh.reveal()
|
| 769 |
+
bpy.ops.mesh.select_all(action='SELECT')
|
| 770 |
+
bpy.ops.uv.smart_project(
|
| 771 |
+
angle_limit=math.radians(float(angle_limit_deg)),
|
| 772 |
+
island_margin=eff_margin,
|
| 773 |
+
)
|
| 774 |
+
op_succeeded = True
|
| 775 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 776 |
+
except RuntimeError:
|
| 777 |
+
try:
|
| 778 |
+
if (
|
| 779 |
+
bpy.context.active_object
|
| 780 |
+
and bpy.context.active_object.mode != 'OBJECT'
|
| 781 |
+
):
|
| 782 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 783 |
+
except RuntimeError:
|
| 784 |
+
pass
|
| 785 |
+
finally:
|
| 786 |
+
target_obj.hide_viewport = prev_hide
|
| 787 |
+
|
| 788 |
+
if not op_succeeded or _uvs_need_unwrap(target_obj):
|
| 789 |
+
_bmesh_box_atlas_unwrap(target_obj, margin=eff_margin)
|
| 790 |
+
mesh_data.update()
|
| 791 |
+
finally:
|
| 792 |
+
for obj in bpy.data.objects:
|
| 793 |
+
want_sel = obj in prev_selected
|
| 794 |
+
if obj.select_get() != want_sel:
|
| 795 |
+
obj.select_set(want_sel)
|
| 796 |
+
if prev_active is not None and prev_active.name in bpy.data.objects:
|
| 797 |
+
bpy.context.view_layer.objects.active = prev_active
|
| 798 |
+
|
| 799 |
+
return valid
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
def pack_shared_uv_atlas(
|
| 803 |
+
objs: (
|
| 804 |
+
bpy.types.Object
|
| 805 |
+
| str
|
| 806 |
+
| list[bpy.types.Object | str]
|
| 807 |
+
| Sequence[bpy.types.Object | str]
|
| 808 |
+
),
|
| 809 |
+
*,
|
| 810 |
+
margin: float = 0.005,
|
| 811 |
+
rotate: bool = True,
|
| 812 |
+
align_minimal_bbox: bool = True,
|
| 813 |
+
match_3d_area: bool = True,
|
| 814 |
+
) -> None:
|
| 815 |
+
"""Packs UV islands of `1` or more mesh objects into `[0, 1]^2` via Blender C++ operators.
|
| 816 |
+
|
| 817 |
+
Uses multi-object edit mode (`bpy.ops.uv.unwrap(method='CONFORMAL')`,
|
| 818 |
+
`bpy.ops.uv.average_islands_scale()`, and `bpy.ops.uv.pack_islands`) while
|
| 819 |
+
preserving custom analytical split normals.
|
| 820 |
+
"""
|
| 821 |
+
del align_minimal_bbox # Handled natively by C++ pack_islands
|
| 822 |
+
resolved = _resolve_object_list(objs)
|
| 823 |
+
valid = [o for o in resolved if o.type == 'MESH' and len(o.data.polygons) > 0]
|
| 824 |
+
if not valid:
|
| 825 |
+
return
|
| 826 |
+
|
| 827 |
+
bpy.context.view_layer.update()
|
| 828 |
+
for obj in valid:
|
| 829 |
+
if not obj.data.uv_layers:
|
| 830 |
+
obj.data.uv_layers.new(name='UVMap')
|
| 831 |
+
if _uvs_need_unwrap(obj):
|
| 832 |
+
smart_uv_project([obj], angle_limit_deg=66.0, island_margin=float(margin))
|
| 833 |
+
|
| 834 |
+
prev_active = bpy.context.view_layer.objects.active
|
| 835 |
+
prev_selected = [o for o in bpy.data.objects if o.select_get()]
|
| 836 |
+
prev_hide = {o: bool(o.hide_viewport) for o in valid}
|
| 837 |
+
|
| 838 |
+
try:
|
| 839 |
+
if bpy.context.active_object and bpy.context.active_object.mode != 'OBJECT':
|
| 840 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 841 |
+
|
| 842 |
+
for o in bpy.data.objects:
|
| 843 |
+
o.select_set(False)
|
| 844 |
+
for o in valid:
|
| 845 |
+
o.hide_viewport = False
|
| 846 |
+
o.select_set(True)
|
| 847 |
+
bpy.context.view_layer.objects.active = valid[0]
|
| 848 |
+
|
| 849 |
+
bpy.ops.object.mode_set(mode='EDIT')
|
| 850 |
+
bpy.ops.mesh.select_mode(type='FACE')
|
| 851 |
+
bpy.ops.mesh.reveal()
|
| 852 |
+
bpy.ops.mesh.select_all(action='SELECT')
|
| 853 |
+
try:
|
| 854 |
+
bpy.ops.uv.unwrap(method='CONFORMAL', margin=float(margin))
|
| 855 |
+
except RuntimeError:
|
| 856 |
+
pass
|
| 857 |
+
if match_3d_area:
|
| 858 |
+
try:
|
| 859 |
+
bpy.ops.uv.average_islands_scale()
|
| 860 |
+
except RuntimeError:
|
| 861 |
+
pass
|
| 862 |
+
bpy.ops.uv.pack_islands(
|
| 863 |
+
rotate=bool(rotate),
|
| 864 |
+
rotate_method='CARDINAL',
|
| 865 |
+
scale=True,
|
| 866 |
+
margin=float(margin),
|
| 867 |
+
shape_method='AABB',
|
| 868 |
+
)
|
| 869 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 870 |
+
finally:
|
| 871 |
+
try:
|
| 872 |
+
if (
|
| 873 |
+
bpy.context.active_object
|
| 874 |
+
and bpy.context.active_object.mode != 'OBJECT'
|
| 875 |
+
):
|
| 876 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 877 |
+
except RuntimeError:
|
| 878 |
+
pass
|
| 879 |
+
for o, h_val in prev_hide.items():
|
| 880 |
+
o.hide_viewport = h_val
|
| 881 |
+
for obj in bpy.data.objects:
|
| 882 |
+
want_sel = obj in prev_selected
|
| 883 |
+
if obj.select_get() != want_sel:
|
| 884 |
+
obj.select_set(want_sel)
|
| 885 |
+
if prev_active is not None and prev_active.name in bpy.data.objects:
|
| 886 |
+
bpy.context.view_layer.objects.active = prev_active
|
| 887 |
+
|
| 888 |
+
for obj in valid:
|
| 889 |
+
if _uvs_need_unwrap(obj):
|
| 890 |
+
smart_uv_project([obj], angle_limit_deg=66.0, island_margin=float(margin))
|
| 891 |
+
obj.data.update()
|
| 892 |
+
|
| 893 |
+
if len(valid) > 1:
|
| 894 |
+
full_span_count = sum(1 for o in valid if _compute_uv_span(o) > 0.65)
|
| 895 |
+
if full_span_count > 1:
|
| 896 |
+
n_objs = len(valid)
|
| 897 |
+
n_cols = max(1, int(math.ceil(math.sqrt(n_objs))))
|
| 898 |
+
n_rows = max(1, int(math.ceil(n_objs / n_cols)))
|
| 899 |
+
cell_w = 1.0 / n_cols
|
| 900 |
+
cell_h = 1.0 / n_rows
|
| 901 |
+
pad = min(0.02, max(0.002, float(margin)))
|
| 902 |
+
for idx, obj in enumerate(valid):
|
| 903 |
+
uv_layer = obj.data.uv_layers.active
|
| 904 |
+
if uv_layer is None or len(uv_layer.data) == 0:
|
| 905 |
+
continue
|
| 906 |
+
us = [float(d.uv.x) for d in uv_layer.data]
|
| 907 |
+
vs = [float(d.uv.y) for d in uv_layer.data]
|
| 908 |
+
umin, umax = min(us), max(us)
|
| 909 |
+
vmin, vmax = min(vs), max(vs)
|
| 910 |
+
du = max(umax - umin, 1e-6)
|
| 911 |
+
dv = max(vmax - vmin, 1e-6)
|
| 912 |
+
col = idx % n_cols
|
| 913 |
+
row = idx // n_cols
|
| 914 |
+
u0 = col * cell_w + pad
|
| 915 |
+
v0 = row * cell_h + pad
|
| 916 |
+
u1 = (col + 1) * cell_w - pad
|
| 917 |
+
v1 = (row + 1) * cell_h - pad
|
| 918 |
+
for d in uv_layer.data:
|
| 919 |
+
d.uv.x = u0 + ((float(d.uv.x) - umin) / du) * max(1e-4, u1 - u0)
|
| 920 |
+
d.uv.y = v0 + ((float(d.uv.y) - vmin) / dv) * max(1e-4, v1 - v0)
|
| 921 |
+
obj.data.update()
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
def _export_single_object_via_wm_obj(
|
| 925 |
+
target_obj: bpy.types.Object,
|
| 926 |
+
out_obj_path: str,
|
| 927 |
+
*,
|
| 928 |
+
triangulate: bool = True,
|
| 929 |
+
export_uv: bool = True,
|
| 930 |
+
export_normals: bool = True,
|
| 931 |
+
origin_vec: mathutils.Vector | None = None,
|
| 932 |
+
) -> None:
|
| 933 |
+
"""Exports `target_obj` to `out_obj_path` via Blender C++ `bpy.ops.wm.obj_export`."""
|
| 934 |
+
os.makedirs(os.path.dirname(os.path.abspath(out_obj_path)), exist_ok=True)
|
| 935 |
+
prev_active = bpy.context.view_layer.objects.active
|
| 936 |
+
prev_selected = [o for o in bpy.data.objects if o.select_get()]
|
| 937 |
+
prev_hide_vp = bool(target_obj.hide_viewport)
|
| 938 |
+
orig_mat = target_obj.matrix_world.copy()
|
| 939 |
+
|
| 940 |
+
try:
|
| 941 |
+
if bpy.context.active_object and bpy.context.active_object.mode != 'OBJECT':
|
| 942 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 943 |
+
target_obj.hide_viewport = False
|
| 944 |
+
if origin_vec is not None and origin_vec.length_squared > 1e-18:
|
| 945 |
+
shifted = orig_mat.copy()
|
| 946 |
+
shifted.translation = orig_mat.translation - origin_vec
|
| 947 |
+
target_obj.matrix_world = shifted
|
| 948 |
+
bpy.context.view_layer.update()
|
| 949 |
+
|
| 950 |
+
_select_only(target_obj)
|
| 951 |
+
bpy.ops.wm.obj_export(
|
| 952 |
+
filepath=os.path.abspath(out_obj_path),
|
| 953 |
+
export_selected_objects=True,
|
| 954 |
+
apply_modifiers=True,
|
| 955 |
+
export_triangulated_mesh=bool(triangulate),
|
| 956 |
+
export_uv=bool(export_uv),
|
| 957 |
+
export_normals=bool(export_normals),
|
| 958 |
+
export_materials=False,
|
| 959 |
+
forward_axis='Y',
|
| 960 |
+
up_axis='Z',
|
| 961 |
+
)
|
| 962 |
+
finally:
|
| 963 |
+
target_obj.matrix_world = orig_mat
|
| 964 |
+
target_obj.hide_viewport = prev_hide_vp
|
| 965 |
+
for obj in bpy.data.objects:
|
| 966 |
+
want_sel = obj in prev_selected
|
| 967 |
+
if obj.select_get() != want_sel:
|
| 968 |
+
obj.select_set(want_sel)
|
| 969 |
+
if prev_active is not None and prev_active.name in bpy.data.objects:
|
| 970 |
+
bpy.context.view_layer.objects.active = prev_active
|
| 971 |
+
bpy.context.view_layer.update()
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
def finalize_and_export_obj(
|
| 975 |
+
target_obj: bpy.types.Object,
|
| 976 |
+
out_obj_path: str,
|
| 977 |
+
*,
|
| 978 |
+
crease_deg: float | None = None,
|
| 979 |
+
world_pos: tuple[float, float, float] | None = None,
|
| 980 |
+
body_pos: tuple[float, float, float] | None = None,
|
| 981 |
+
ensure_uvs: bool = True,
|
| 982 |
+
earclip_in_place: bool = False,
|
| 983 |
+
) -> dict[str, int]:
|
| 984 |
+
"""Syncs normals if needed and exports `.obj` via Blender's C++ `bpy.ops.wm.obj_export`."""
|
| 985 |
+
bpy.context.view_layer.update()
|
| 986 |
+
mesh_data = target_obj.data
|
| 987 |
+
|
| 988 |
+
if ensure_uvs and _uvs_need_unwrap(target_obj):
|
| 989 |
+
smart_uv_project([target_obj], angle_limit_deg=66.0, island_margin=0.01)
|
| 990 |
+
|
| 991 |
+
n_ngons = sum(1 for poly in mesh_data.polygons if len(poly.vertices) > 4)
|
| 992 |
+
if earclip_in_place and n_ngons > 0:
|
| 993 |
+
bm = bmesh.new()
|
| 994 |
+
bm.from_mesh(mesh_data)
|
| 995 |
+
ngon_faces = [f for f in bm.faces if len(f.verts) > 4]
|
| 996 |
+
if ngon_faces:
|
| 997 |
+
bmesh.ops.triangulate(
|
| 998 |
+
bm, faces=ngon_faces, quad_method='BEAUTY', ngon_method='EAR_CLIP'
|
| 999 |
+
)
|
| 1000 |
+
bm.to_mesh(mesh_data)
|
| 1001 |
+
bm.free()
|
| 1002 |
+
mesh_data.update()
|
| 1003 |
+
|
| 1004 |
+
if crease_deg is not None:
|
| 1005 |
+
bm = bmesh.new()
|
| 1006 |
+
bm.from_mesh(mesh_data)
|
| 1007 |
+
thresh = math.radians(float(crease_deg))
|
| 1008 |
+
for edge in bm.edges:
|
| 1009 |
+
if len(edge.link_faces) == 2 and edge.calc_face_angle(0.0) > thresh:
|
| 1010 |
+
edge.smooth = False
|
| 1011 |
+
bm.to_mesh(mesh_data)
|
| 1012 |
+
bm.free()
|
| 1013 |
+
mesh_data.update()
|
| 1014 |
+
_apply_weighted_normals(target_obj, force_smooth=True)
|
| 1015 |
+
elif not getattr(mesh_data, 'has_custom_normals', False):
|
| 1016 |
+
_apply_weighted_normals(target_obj, force_smooth=False)
|
| 1017 |
+
|
| 1018 |
+
origin_raw = (
|
| 1019 |
+
body_pos
|
| 1020 |
+
if body_pos is not None
|
| 1021 |
+
else (world_pos if world_pos is not None else (0.0, 0.0, 0.0))
|
| 1022 |
+
)
|
| 1023 |
+
origin_vec = mathutils.Vector(
|
| 1024 |
+
(float(origin_raw[0]), float(origin_raw[1]), float(origin_raw[2]))
|
| 1025 |
+
)
|
| 1026 |
+
|
| 1027 |
+
_export_single_object_via_wm_obj(
|
| 1028 |
+
target_obj,
|
| 1029 |
+
out_obj_path,
|
| 1030 |
+
triangulate=True,
|
| 1031 |
+
export_uv=bool(mesh_data.uv_layers),
|
| 1032 |
+
export_normals=True,
|
| 1033 |
+
origin_vec=origin_vec,
|
| 1034 |
+
)
|
| 1035 |
+
|
| 1036 |
+
n_verts = len(mesh_data.vertices)
|
| 1037 |
+
n_quads = sum(1 for p in mesh_data.polygons if len(p.vertices) == 4)
|
| 1038 |
+
n_tris = sum(1 for p in mesh_data.polygons if len(p.vertices) == 3)
|
| 1039 |
+
return {
|
| 1040 |
+
'verts': n_verts,
|
| 1041 |
+
'quads': n_quads,
|
| 1042 |
+
'tris': n_tris,
|
| 1043 |
+
'earclipped_ngons': n_ngons,
|
| 1044 |
+
}
|
| 1045 |
+
|
| 1046 |
+
|
| 1047 |
+
def _select_extreme_hull_points(
|
| 1048 |
+
pts: Sequence[mathutils.Vector], cap: int
|
| 1049 |
+
) -> list[mathutils.Vector]:
|
| 1050 |
+
"""Selects `cap` non-coplanar extreme hull vertices via support + farthest-point sampling."""
|
| 1051 |
+
n_pts = len(pts)
|
| 1052 |
+
if n_pts <= cap:
|
| 1053 |
+
return [p.copy() for p in pts]
|
| 1054 |
+
|
| 1055 |
+
bmin = mathutils.Vector((1e9, 1e9, 1e9))
|
| 1056 |
+
bmax = mathutils.Vector((-1e9, -1e9, -1e9))
|
| 1057 |
+
for p in pts:
|
| 1058 |
+
for k in range(3):
|
| 1059 |
+
bmin[k] = min(bmin[k], p[k])
|
| 1060 |
+
bmax[k] = max(bmax[k], p[k])
|
| 1061 |
+
span = bmax - bmin
|
| 1062 |
+
|
| 1063 |
+
# 1. Seed a non-degenerate 3D simplex so even sub-millimeter thin sheets keep
|
| 1064 |
+
# both opposing faces instead of collapsing to 2D.
|
| 1065 |
+
k_max = max(range(3), key=lambda k: float(span[k]))
|
| 1066 |
+
i0 = min(range(n_pts), key=lambda i: float(pts[i][k_max]))
|
| 1067 |
+
i1 = max(range(n_pts), key=lambda i: float(pts[i][k_max]))
|
| 1068 |
+
selected: list[int] = [i0]
|
| 1069 |
+
if i1 != i0:
|
| 1070 |
+
selected.append(i1)
|
| 1071 |
+
|
| 1072 |
+
d01 = pts[i1] - pts[i0]
|
| 1073 |
+
if d01.length > 1e-12:
|
| 1074 |
+
d01_u = d01.normalized()
|
| 1075 |
+
i2 = max(
|
| 1076 |
+
range(n_pts),
|
| 1077 |
+
key=lambda i: float((pts[i] - pts[i0]).cross(d01_u).length_squared),
|
| 1078 |
+
)
|
| 1079 |
+
if i2 not in selected:
|
| 1080 |
+
selected.append(i2)
|
| 1081 |
+
n_plane = d01.cross(pts[i2] - pts[i0])
|
| 1082 |
+
if n_plane.length > 1e-12 and len(selected) < cap:
|
| 1083 |
+
n_u = n_plane.normalized()
|
| 1084 |
+
i3 = min(range(n_pts), key=lambda i: float((pts[i] - pts[i0]).dot(n_u)))
|
| 1085 |
+
i4 = max(range(n_pts), key=lambda i: float((pts[i] - pts[i0]).dot(n_u)))
|
| 1086 |
+
for cand in (i3, i4):
|
| 1087 |
+
if cand not in selected and len(selected) < cap:
|
| 1088 |
+
selected.append(cand)
|
| 1089 |
+
|
| 1090 |
+
# 2. Bbox-whitened coordinates give thin and thick axes equal directional weight.
|
| 1091 |
+
inv_span = mathutils.Vector((
|
| 1092 |
+
1.0 / max(float(span.x), 1e-9),
|
| 1093 |
+
1.0 / max(float(span.y), 1e-9),
|
| 1094 |
+
1.0 / max(float(span.z), 1e-9),
|
| 1095 |
+
))
|
| 1096 |
+
w_pts = [
|
| 1097 |
+
mathutils.Vector((
|
| 1098 |
+
(p.x - bmin.x) * inv_span.x,
|
| 1099 |
+
(p.y - bmin.y) * inv_span.y,
|
| 1100 |
+
(p.z - bmin.z) * inv_span.z,
|
| 1101 |
+
))
|
| 1102 |
+
for p in pts
|
| 1103 |
+
]
|
| 1104 |
+
|
| 1105 |
+
support_dirs = [
|
| 1106 |
+
(1, 0, 0),
|
| 1107 |
+
(-1, 0, 0),
|
| 1108 |
+
(0, 1, 0),
|
| 1109 |
+
(0, -1, 0),
|
| 1110 |
+
(0, 0, 1),
|
| 1111 |
+
(0, 0, -1),
|
| 1112 |
+
(1, 1, 1),
|
| 1113 |
+
(1, 1, -1),
|
| 1114 |
+
(1, -1, 1),
|
| 1115 |
+
(1, -1, -1),
|
| 1116 |
+
(-1, 1, 1),
|
| 1117 |
+
(-1, 1, -1),
|
| 1118 |
+
(-1, -1, 1),
|
| 1119 |
+
(-1, -1, -1),
|
| 1120 |
+
(1, 1, 0),
|
| 1121 |
+
(1, -1, 0),
|
| 1122 |
+
(-1, 1, 0),
|
| 1123 |
+
(-1, -1, 0),
|
| 1124 |
+
(1, 0, 1),
|
| 1125 |
+
(1, 0, -1),
|
| 1126 |
+
(-1, 0, 1),
|
| 1127 |
+
(-1, 0, -1),
|
| 1128 |
+
(0, 1, 1),
|
| 1129 |
+
(0, 1, -1),
|
| 1130 |
+
(0, -1, 1),
|
| 1131 |
+
(0, -1, -1),
|
| 1132 |
+
]
|
| 1133 |
+
sel_set = set(selected)
|
| 1134 |
+
for dx, dy, dz in support_dirs:
|
| 1135 |
+
if len(selected) >= cap:
|
| 1136 |
+
break
|
| 1137 |
+
d_vec = mathutils.Vector((float(dx), float(dy), float(dz))).normalized()
|
| 1138 |
+
best_i = max(range(n_pts), key=lambda i: float(w_pts[i].dot(d_vec)))
|
| 1139 |
+
if best_i not in sel_set:
|
| 1140 |
+
selected.append(best_i)
|
| 1141 |
+
sel_set.add(best_i)
|
| 1142 |
+
|
| 1143 |
+
# 3. Fill remaining budget up to `cap` via greedy farthest-point sampling.
|
| 1144 |
+
if len(selected) < cap:
|
| 1145 |
+
min_d2 = [1e30] * n_pts
|
| 1146 |
+
for s_idx in selected:
|
| 1147 |
+
ws = w_pts[s_idx]
|
| 1148 |
+
for i in range(n_pts):
|
| 1149 |
+
d2 = float((w_pts[i] - ws).length_squared)
|
| 1150 |
+
if d2 < min_d2[i]:
|
| 1151 |
+
min_d2[i] = d2
|
| 1152 |
+
while len(selected) < cap:
|
| 1153 |
+
best_i = max(range(n_pts), key=lambda i: min_d2[i])
|
| 1154 |
+
if best_i in sel_set or min_d2[best_i] <= 1e-18:
|
| 1155 |
+
break
|
| 1156 |
+
selected.append(best_i)
|
| 1157 |
+
sel_set.add(best_i)
|
| 1158 |
+
ws = w_pts[best_i]
|
| 1159 |
+
for i in range(n_pts):
|
| 1160 |
+
d2 = float((w_pts[i] - ws).length_squared)
|
| 1161 |
+
if d2 < min_d2[i]:
|
| 1162 |
+
min_d2[i] = d2
|
| 1163 |
+
|
| 1164 |
+
return [pts[i].copy() for i in selected]
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
def _rebuild_clean_hull_bm(bm: Any, pts: Sequence[mathutils.Vector]) -> float:
|
| 1168 |
+
"""Rebuilds `bm` as a pure triangulated exterior convex hull and returns 3D volume."""
|
| 1169 |
+
bm.clear()
|
| 1170 |
+
seen: set[tuple[int, int, int]] = set()
|
| 1171 |
+
for p in pts:
|
| 1172 |
+
qk = (
|
| 1173 |
+
int(round(float(p.x) * 1e8)),
|
| 1174 |
+
int(round(float(p.y) * 1e8)),
|
| 1175 |
+
int(round(float(p.z) * 1e8)),
|
| 1176 |
+
)
|
| 1177 |
+
if qk not in seen:
|
| 1178 |
+
seen.add(qk)
|
| 1179 |
+
bm.verts.new(p)
|
| 1180 |
+
|
| 1181 |
+
if len(bm.verts) < 4:
|
| 1182 |
+
return 0.0
|
| 1183 |
+
|
| 1184 |
+
hull_res = bmesh.ops.convex_hull(bm, input=bm.verts[:])
|
| 1185 |
+
unused_verts = list({
|
| 1186 |
+
ele
|
| 1187 |
+
for key in ('geom_interior', 'geom_unused')
|
| 1188 |
+
for ele in hull_res.get(key, [])
|
| 1189 |
+
if isinstance(ele, bmesh.types.BMVert) and ele.is_valid
|
| 1190 |
+
})
|
| 1191 |
+
if unused_verts:
|
| 1192 |
+
bmesh.ops.delete(bm, geom=unused_verts, context='VERTS')
|
| 1193 |
+
|
| 1194 |
+
if not bm.faces or len(bm.verts) < 4:
|
| 1195 |
+
return 0.0
|
| 1196 |
+
|
| 1197 |
+
bmesh.ops.triangulate(bm, faces=bm.faces[:])
|
| 1198 |
+
bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
|
| 1199 |
+
bm.normal_update()
|
| 1200 |
+
|
| 1201 |
+
bm.verts.ensure_lookup_table()
|
| 1202 |
+
ref = bm.verts[0].co
|
| 1203 |
+
vol6 = 0.0
|
| 1204 |
+
for face in bm.faces:
|
| 1205 |
+
if len(face.verts) == 3:
|
| 1206 |
+
v0 = face.verts[0].co - ref
|
| 1207 |
+
v1 = face.verts[1].co - ref
|
| 1208 |
+
v2 = face.verts[2].co - ref
|
| 1209 |
+
vol6 += float(v0.dot(v1.cross(v2)))
|
| 1210 |
+
return abs(vol6) / 6.0
|
| 1211 |
+
|
| 1212 |
+
|
| 1213 |
+
def _append_object_world_mesh_to_bm(
|
| 1214 |
+
bm: Any,
|
| 1215 |
+
src_obj: bpy.types.Object,
|
| 1216 |
+
depsgraph_holder: list[Any],
|
| 1217 |
+
col_name: str,
|
| 1218 |
+
) -> None:
|
| 1219 |
+
"""Appends `src_obj`'s mesh (or evaluated curve/surface) into `bm` in world space."""
|
| 1220 |
+
v_start = len(bm.verts)
|
| 1221 |
+
if src_obj.type == 'MESH' and (
|
| 1222 |
+
len(src_obj.data.vertices) > 0 or not src_obj.modifiers
|
| 1223 |
+
):
|
| 1224 |
+
bm.from_mesh(src_obj.data)
|
| 1225 |
+
elif src_obj.type in {'MESH', 'CURVE', 'SURFACE', 'FONT', 'META'}:
|
| 1226 |
+
if not depsgraph_holder:
|
| 1227 |
+
depsgraph_holder.append(bpy.context.evaluated_depsgraph_get())
|
| 1228 |
+
eval_obj = src_obj.evaluated_get(depsgraph_holder[0])
|
| 1229 |
+
eval_mesh = eval_obj.to_mesh()
|
| 1230 |
+
try:
|
| 1231 |
+
if eval_mesh is not None:
|
| 1232 |
+
bm.from_mesh(eval_mesh)
|
| 1233 |
+
finally:
|
| 1234 |
+
if eval_mesh is not None:
|
| 1235 |
+
eval_obj.to_mesh_clear()
|
| 1236 |
+
else:
|
| 1237 |
+
raise TypeError(
|
| 1238 |
+
f'Unsupported Blender object type {src_obj.type!r} for collision hull '
|
| 1239 |
+
f'{col_name!r} (object {src_obj.name!r})'
|
| 1240 |
+
)
|
| 1241 |
+
bm.verts.ensure_lookup_table()
|
| 1242 |
+
new_verts = bm.verts[v_start:]
|
| 1243 |
+
if new_verts:
|
| 1244 |
+
bmesh.ops.transform(bm, matrix=src_obj.matrix_world, verts=new_verts)
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
def export_convex_hull_col(
|
| 1248 |
+
source_obj_or_points: Any,
|
| 1249 |
+
out_obj_path: str,
|
| 1250 |
+
*,
|
| 1251 |
+
clip_bounds_world_m: tuple[Sequence[float], Sequence[float]] | None = None,
|
| 1252 |
+
clip_bounds_m: tuple[Sequence[float], Sequence[float]] | None = None,
|
| 1253 |
+
max_verts: int = 64,
|
| 1254 |
+
name: str | None = None,
|
| 1255 |
+
world_pos: tuple[float, float, float] = (0.0, 0.0, 0.0),
|
| 1256 |
+
body_pos: tuple[float, float, float] | None = None,
|
| 1257 |
+
) -> bpy.types.Object:
|
| 1258 |
+
"""Builds, plane-clips, caps (`<= max_verts`), validates, and exports a convex hull `.obj`.
|
| 1259 |
+
|
| 1260 |
+
Args:
|
| 1261 |
+
source_obj_or_points: One of: 1. A single `bpy.types.Object` (`MESH`, or
|
| 1262 |
+
`CURVE`/`SURFACE`/`FONT`/`META` evaluated via `depsgraph.to_mesh()`) or
|
| 1263 |
+
`str` object name in `bpy.data.objects`. 2. A sequence of
|
| 1264 |
+
`bpy.types.Object | str` (e.g. multi-part rigid-body visual meshes), all
|
| 1265 |
+
merged in world space into one `BMesh` before 6-plane `bisect_plane`
|
| 1266 |
+
clipping. 3. A sequence of 3D world `(x, y, z)` points in meters.
|
| 1267 |
+
out_obj_path: Output `*_col.obj` path.
|
| 1268 |
+
clip_bounds_world_m: Optional `(cmin_xyz_m, cmax_xyz_m)` world-space axis-
|
| 1269 |
+
aligned clipping box. For mesh/curve objects, runs 6 true 3D half-space
|
| 1270 |
+
plane cuts (`bmesh.ops.bisect_plane`) so long edges/faces spanning across
|
| 1271 |
+
`cmin..cmax` are cleanly sliced at the boundary.
|
| 1272 |
+
clip_bounds_m: Optional keyword alias for `clip_bounds_world_m`.
|
| 1273 |
+
max_verts: Maximum hull vertex count (`>= 4`, `64` default matching MuJoCo's
|
| 1274 |
+
MJX `maxhullvert` limit).
|
| 1275 |
+
name: Optional scene object name (defaults to `out_obj_path` stem).
|
| 1276 |
+
world_pos: Body origin `(px, py, pz)` in world meters subtracted from hull
|
| 1277 |
+
vertices (`body_pos` overrides `world_pos` if given).
|
| 1278 |
+
body_pos: Optional alias overriding `world_pos`.
|
| 1279 |
+
|
| 1280 |
+
Returns:
|
| 1281 |
+
Scene collision hull `Object` (`location = origin_vec`, `hide_render =
|
| 1282 |
+
True`).
|
| 1283 |
+
|
| 1284 |
+
Raises:
|
| 1285 |
+
ValueError: If `max_verts < 4`, `clip_bounds_world_m` is inverted, fewer
|
| 1286 |
+
than `4` vertices remain after clipping, or 3D hull volume `<= 1e-12 m^3`.
|
| 1287 |
+
"""
|
| 1288 |
+
cap = int(max_verts)
|
| 1289 |
+
if cap < 4:
|
| 1290 |
+
raise ValueError(f'max_verts must be >= 4; got {max_verts}')
|
| 1291 |
+
|
| 1292 |
+
pos_ref = body_pos if body_pos is not None else world_pos
|
| 1293 |
+
origin_vec = mathutils.Vector(
|
| 1294 |
+
(float(pos_ref[0]), float(pos_ref[1]), float(pos_ref[2]))
|
| 1295 |
+
)
|
| 1296 |
+
col_name = name or os.path.splitext(os.path.basename(out_obj_path))[0]
|
| 1297 |
+
|
| 1298 |
+
effective_clip = (
|
| 1299 |
+
clip_bounds_world_m if clip_bounds_world_m is not None else clip_bounds_m
|
| 1300 |
+
)
|
| 1301 |
+
cmin: tuple[float, float, float] | None = None
|
| 1302 |
+
cmax: tuple[float, float, float] | None = None
|
| 1303 |
+
if effective_clip is not None:
|
| 1304 |
+
if (
|
| 1305 |
+
len(effective_clip) == 2
|
| 1306 |
+
and isinstance(effective_clip[0], Sequence)
|
| 1307 |
+
and not isinstance(effective_clip[0], (str, bytes))
|
| 1308 |
+
):
|
| 1309 |
+
raw_min, raw_max = effective_clip
|
| 1310 |
+
cmin = (float(raw_min[0]), float(raw_min[1]), float(raw_min[2]))
|
| 1311 |
+
cmax = (float(raw_max[0]), float(raw_max[1]), float(raw_max[2]))
|
| 1312 |
+
elif len(effective_clip) == 6:
|
| 1313 |
+
cmin = (
|
| 1314 |
+
float(effective_clip[0]),
|
| 1315 |
+
float(effective_clip[1]),
|
| 1316 |
+
float(effective_clip[2]),
|
| 1317 |
+
)
|
| 1318 |
+
cmax = (
|
| 1319 |
+
float(effective_clip[3]),
|
| 1320 |
+
float(effective_clip[4]),
|
| 1321 |
+
float(effective_clip[5]),
|
| 1322 |
+
)
|
| 1323 |
+
else:
|
| 1324 |
+
raise ValueError(
|
| 1325 |
+
f'clip_bounds_world_m for {col_name!r} must be '
|
| 1326 |
+
'((xmin, ymin, zmin), (xmax, ymax, zmax)) or '
|
| 1327 |
+
f'(xmin, ymin, zmin, xmax, ymax, zmax); got {effective_clip!r}'
|
| 1328 |
+
)
|
| 1329 |
+
for k in range(3):
|
| 1330 |
+
if cmin[k] > cmax[k]:
|
| 1331 |
+
raise ValueError(
|
| 1332 |
+
f'Collision hull {col_name!r} has inverted clip_bounds_world_m '
|
| 1333 |
+
f'along axis {k}: {cmin} > {cmax}'
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
is_obj_source = False
|
| 1337 |
+
raw_obj_list: list[bpy.types.Object | str] = []
|
| 1338 |
+
if isinstance(source_obj_or_points, (bpy.types.Object, str)):
|
| 1339 |
+
is_obj_source = True
|
| 1340 |
+
raw_obj_list = [source_obj_or_points]
|
| 1341 |
+
elif hasattr(source_obj_or_points, 'data') and hasattr(
|
| 1342 |
+
source_obj_or_points.data, 'vertices'
|
| 1343 |
+
):
|
| 1344 |
+
is_obj_source = True
|
| 1345 |
+
raw_obj_list = [source_obj_or_points]
|
| 1346 |
+
elif isinstance(source_obj_or_points, Sequence) and not isinstance(
|
| 1347 |
+
source_obj_or_points, (str, bytes)
|
| 1348 |
+
):
|
| 1349 |
+
if source_obj_or_points and isinstance(
|
| 1350 |
+
source_obj_or_points[0], (bpy.types.Object, str)
|
| 1351 |
+
):
|
| 1352 |
+
is_obj_source = True
|
| 1353 |
+
raw_obj_list = list(source_obj_or_points)
|
| 1354 |
+
|
| 1355 |
+
bm = bmesh.new()
|
| 1356 |
+
try:
|
| 1357 |
+
if is_obj_source:
|
| 1358 |
+
bpy.context.view_layer.update()
|
| 1359 |
+
resolved_objs = _resolve_object_list(raw_obj_list)
|
| 1360 |
+
depsgraph_holder: list[Any] = []
|
| 1361 |
+
for src_obj in resolved_objs:
|
| 1362 |
+
_append_object_world_mesh_to_bm(bm, src_obj, depsgraph_holder, col_name)
|
| 1363 |
+
if cmin is not None and cmax is not None and bm.verts:
|
| 1364 |
+
plane_cuts = (
|
| 1365 |
+
((cmin[0], 0.0, 0.0), (-1.0, 0.0, 0.0)),
|
| 1366 |
+
((cmax[0], 0.0, 0.0), (1.0, 0.0, 0.0)),
|
| 1367 |
+
((0.0, cmin[1], 0.0), (0.0, -1.0, 0.0)),
|
| 1368 |
+
((0.0, cmax[1], 0.0), (0.0, 1.0, 0.0)),
|
| 1369 |
+
((0.0, 0.0, cmin[2]), (0.0, 0.0, -1.0)),
|
| 1370 |
+
((0.0, 0.0, cmax[2]), (0.0, 0.0, 1.0)),
|
| 1371 |
+
)
|
| 1372 |
+
for p_co, p_no in plane_cuts:
|
| 1373 |
+
if not bm.verts:
|
| 1374 |
+
break
|
| 1375 |
+
geom_all = bm.verts[:] + bm.edges[:] + bm.faces[:]
|
| 1376 |
+
bmesh.ops.bisect_plane(
|
| 1377 |
+
bm,
|
| 1378 |
+
geom=geom_all,
|
| 1379 |
+
dist=1e-7,
|
| 1380 |
+
plane_co=p_co,
|
| 1381 |
+
plane_no=p_no,
|
| 1382 |
+
clear_outer=True,
|
| 1383 |
+
clear_inner=False,
|
| 1384 |
+
)
|
| 1385 |
+
local_pts = [v.co - origin_vec for v in bm.verts]
|
| 1386 |
+
else:
|
| 1387 |
+
local_pts = []
|
| 1388 |
+
for pt in source_obj_or_points:
|
| 1389 |
+
w_pt = mathutils.Vector((float(pt[0]), float(pt[1]), float(pt[2])))
|
| 1390 |
+
if cmin is not None and cmax is not None:
|
| 1391 |
+
if not (
|
| 1392 |
+
cmin[0] - 1e-7 <= w_pt.x <= cmax[0] + 1e-7
|
| 1393 |
+
and cmin[1] - 1e-7 <= w_pt.y <= cmax[1] + 1e-7
|
| 1394 |
+
and cmin[2] - 1e-7 <= w_pt.z <= cmax[2] + 1e-7
|
| 1395 |
+
):
|
| 1396 |
+
continue
|
| 1397 |
+
local_pts.append(w_pt - origin_vec)
|
| 1398 |
+
|
| 1399 |
+
if len(local_pts) < 4:
|
| 1400 |
+
raise ValueError(
|
| 1401 |
+
f'Collision hull {col_name!r} ({out_obj_path!r}) has fewer than 4 '
|
| 1402 |
+
f'vertices ({len(local_pts)}) after world clipping '
|
| 1403 |
+
f'(clip_bounds_world_m={effective_clip}).'
|
| 1404 |
+
)
|
| 1405 |
+
|
| 1406 |
+
vol_m3 = _rebuild_clean_hull_bm(bm, local_pts)
|
| 1407 |
+
if len(bm.verts) > cap:
|
| 1408 |
+
sampled_pts = _select_extreme_hull_points(
|
| 1409 |
+
[v.co.copy() for v in bm.verts], cap
|
| 1410 |
+
)
|
| 1411 |
+
vol_m3 = _rebuild_clean_hull_bm(bm, sampled_pts)
|
| 1412 |
+
|
| 1413 |
+
if len(bm.verts) < 4 or len(bm.faces) < 4 or vol_m3 <= 1e-12:
|
| 1414 |
+
raise ValueError(
|
| 1415 |
+
f'Collision hull {col_name!r} ({out_obj_path!r}) is degenerate or '
|
| 1416 |
+
f'coplanar: verts={len(bm.verts)}, faces={len(bm.faces)}, '
|
| 1417 |
+
f'volume={vol_m3:.3e} m^3 (must exceed 1e-12 m^3; '
|
| 1418 |
+
f'clip_bounds_world_m={effective_clip}).'
|
| 1419 |
+
)
|
| 1420 |
+
|
| 1421 |
+
old_obj = bpy.data.objects.get(col_name)
|
| 1422 |
+
if old_obj is not None:
|
| 1423 |
+
old_mesh = old_obj.data if old_obj.type == 'MESH' else None
|
| 1424 |
+
bpy.data.objects.remove(old_obj, do_unlink=True)
|
| 1425 |
+
if old_mesh is not None and old_mesh.users == 0:
|
| 1426 |
+
bpy.data.meshes.remove(old_mesh)
|
| 1427 |
+
|
| 1428 |
+
mesh_data = bpy.data.meshes.new(col_name)
|
| 1429 |
+
bm.to_mesh(mesh_data)
|
| 1430 |
+
mesh_data.update()
|
| 1431 |
+
finally:
|
| 1432 |
+
bm.free()
|
| 1433 |
+
|
| 1434 |
+
col_obj = bpy.data.objects.new(col_name, mesh_data)
|
| 1435 |
+
bpy.context.scene.collection.objects.link(col_obj)
|
| 1436 |
+
col_obj.location = (origin_vec.x, origin_vec.y, origin_vec.z)
|
| 1437 |
+
col_obj.hide_render = True
|
| 1438 |
+
bpy.context.view_layer.update()
|
| 1439 |
+
|
| 1440 |
+
_export_single_object_via_wm_obj(
|
| 1441 |
+
col_obj,
|
| 1442 |
+
out_obj_path,
|
| 1443 |
+
triangulate=True,
|
| 1444 |
+
export_uv=False,
|
| 1445 |
+
export_normals=False,
|
| 1446 |
+
origin_vec=origin_vec,
|
| 1447 |
+
)
|
| 1448 |
+
return col_obj
|
| 1449 |
+
|
| 1450 |
+
|
| 1451 |
+
class _MatBakeRig:
|
| 1452 |
+
"""Tracks temporary bake nodes and original links for one Blender `Material`."""
|
| 1453 |
+
|
| 1454 |
+
def __init__(self, mat: bpy.types.Material):
|
| 1455 |
+
self.mat = mat
|
| 1456 |
+
self.nt = mat.node_tree
|
| 1457 |
+
self.bsdf = next(
|
| 1458 |
+
(n for n in self.nt.nodes if n.type == 'BSDF_PRINCIPLED'), None
|
| 1459 |
+
)
|
| 1460 |
+
self.out_node = next(
|
| 1461 |
+
(n for n in self.nt.nodes if n.type == 'OUTPUT_MATERIAL'), None
|
| 1462 |
+
)
|
| 1463 |
+
self.orig_surface_sources = (
|
| 1464 |
+
[lk.from_socket for lk in self.out_node.inputs['Surface'].links]
|
| 1465 |
+
if self.out_node is not None
|
| 1466 |
+
else []
|
| 1467 |
+
)
|
| 1468 |
+
self.orig_active = self.nt.nodes.active
|
| 1469 |
+
self.orig_selected = [n for n in self.nt.nodes if n.select]
|
| 1470 |
+
self.img_node = self.nt.nodes.new('ShaderNodeTexImage')
|
| 1471 |
+
self.emit_node = self.nt.nodes.new('ShaderNodeEmission')
|
| 1472 |
+
|
| 1473 |
+
def activate_target_image(self, img: bpy.types.Image) -> None:
|
| 1474 |
+
"""Assigns `img` as the sole selected active target node in `self.nt`."""
|
| 1475 |
+
self.img_node.image = img
|
| 1476 |
+
for node in self.nt.nodes:
|
| 1477 |
+
node.select = False
|
| 1478 |
+
self.img_node.select = True
|
| 1479 |
+
self.nt.nodes.active = self.img_node
|
| 1480 |
+
|
| 1481 |
+
def wire_socket_to_emit(self, socket_name: str) -> None:
|
| 1482 |
+
"""Routes `Principled BSDF` `socket_name` into `emit_node -> Surface`."""
|
| 1483 |
+
for lk in list(self.emit_node.inputs['Color'].links):
|
| 1484 |
+
self.nt.links.remove(lk)
|
| 1485 |
+
for lk in list(self.out_node.inputs['Surface'].links):
|
| 1486 |
+
self.nt.links.remove(lk)
|
| 1487 |
+
|
| 1488 |
+
inp = self.bsdf.inputs[socket_name]
|
| 1489 |
+
if inp.is_linked:
|
| 1490 |
+
self.nt.links.new(
|
| 1491 |
+
inp.links[0].from_socket, self.emit_node.inputs['Color']
|
| 1492 |
+
)
|
| 1493 |
+
else:
|
| 1494 |
+
val = inp.default_value
|
| 1495 |
+
if hasattr(val, '__len__'):
|
| 1496 |
+
rgba = tuple(float(x) for x in val)
|
| 1497 |
+
if len(rgba) == 3:
|
| 1498 |
+
rgba = (rgba[0], rgba[1], rgba[2], 1.0)
|
| 1499 |
+
self.emit_node.inputs['Color'].default_value = rgba
|
| 1500 |
+
else:
|
| 1501 |
+
fv = float(val)
|
| 1502 |
+
self.emit_node.inputs['Color'].default_value = (fv, fv, fv, 1.0)
|
| 1503 |
+
self.nt.links.new(
|
| 1504 |
+
self.emit_node.outputs['Emission'], self.out_node.inputs['Surface']
|
| 1505 |
+
)
|
| 1506 |
+
|
| 1507 |
+
def restore_surface_links(self) -> None:
|
| 1508 |
+
"""Restores the original `Principled BSDF -> Surface` links."""
|
| 1509 |
+
for lk in list(self.emit_node.inputs['Color'].links):
|
| 1510 |
+
self.nt.links.remove(lk)
|
| 1511 |
+
for lk in list(self.out_node.inputs['Surface'].links):
|
| 1512 |
+
self.nt.links.remove(lk)
|
| 1513 |
+
for src_sock in self.orig_surface_sources:
|
| 1514 |
+
self.nt.links.new(src_sock, self.out_node.inputs['Surface'])
|
| 1515 |
+
|
| 1516 |
+
def cleanup(self) -> None:
|
| 1517 |
+
"""Restores original links, selection, and active node and deletes temp nodes."""
|
| 1518 |
+
self.restore_surface_links()
|
| 1519 |
+
if self.img_node.name in self.nt.nodes:
|
| 1520 |
+
self.nt.nodes.remove(self.img_node)
|
| 1521 |
+
if self.emit_node.name in self.nt.nodes:
|
| 1522 |
+
self.nt.nodes.remove(self.emit_node)
|
| 1523 |
+
for node in self.nt.nodes:
|
| 1524 |
+
node.select = node in self.orig_selected
|
| 1525 |
+
if self.orig_active is not None and self.orig_active.name in self.nt.nodes:
|
| 1526 |
+
self.nt.nodes.active = self.orig_active
|
| 1527 |
+
|
| 1528 |
+
|
| 1529 |
+
def _collect_group_materials(
|
| 1530 |
+
grp_objs: Sequence[bpy.types.Object],
|
| 1531 |
+
) -> list[bpy.types.Material]:
|
| 1532 |
+
"""Collects unique valid `Principled BSDF` materials across all slots of `grp_objs`."""
|
| 1533 |
+
mats: list[bpy.types.Material] = []
|
| 1534 |
+
seen: set[bpy.types.Material] = set()
|
| 1535 |
+
for obj in grp_objs:
|
| 1536 |
+
for slot in obj.material_slots:
|
| 1537 |
+
mat = slot.material
|
| 1538 |
+
if mat is None or mat in seen or mat.node_tree is None:
|
| 1539 |
+
continue
|
| 1540 |
+
has_bsdf = any(n.type == 'BSDF_PRINCIPLED' for n in mat.node_tree.nodes)
|
| 1541 |
+
has_out = any(n.type == 'OUTPUT_MATERIAL' for n in mat.node_tree.nodes)
|
| 1542 |
+
if has_bsdf and has_out:
|
| 1543 |
+
seen.add(mat)
|
| 1544 |
+
mats.append(mat)
|
| 1545 |
+
return mats
|
| 1546 |
+
|
| 1547 |
+
|
| 1548 |
+
def bake_pbr_maps(
|
| 1549 |
+
out_dir: str,
|
| 1550 |
+
*,
|
| 1551 |
+
material_groups: (
|
| 1552 |
+
dict[str, bpy.types.Object | str | list[bpy.types.Object | str]]
|
| 1553 |
+
| Mapping[
|
| 1554 |
+
str, bpy.types.Object | str | Sequence[bpy.types.Object | str]
|
| 1555 |
+
]
|
| 1556 |
+
| None
|
| 1557 |
+
) = None,
|
| 1558 |
+
resolution: int = 1024,
|
| 1559 |
+
samples: int = 8,
|
| 1560 |
+
) -> dict[str, dict[str, str]]:
|
| 1561 |
+
"""Bakes `Principled BSDF` graphs across all material slots & objects under `Raw` view transform.
|
| 1562 |
+
|
| 1563 |
+
Supports multi-material meshes (`obj.material_slots`) and multi-object shared
|
| 1564 |
+
UV atlases (`material_groups`). Uses `scene.view_settings.view_transform =
|
| 1565 |
+
'Raw'`
|
| 1566 |
+
and `look = 'None'` so roughness, metallic, and bright basecolor values `>
|
| 1567 |
+
0.8`
|
| 1568 |
+
are never compressed by `'Standard'` / `'AgX'` / `'Filmic'` tone-mapping.
|
| 1569 |
+
Saves `basecolor` as sRGB PNG and `roughness`, `metallic`, `normal` as linear
|
| 1570 |
+
`Non-Color` PNGs, restoring all scene and shader settings in `finally`.
|
| 1571 |
+
|
| 1572 |
+
Args:
|
| 1573 |
+
out_dir: Output directory for `<key>_basecolor.png`, `<key>_roughness.png`,
|
| 1574 |
+
`<key>_metallic.png`, and `<key>_normal.png`.
|
| 1575 |
+
material_groups: Optional mapping `mat_key -> [obj1, obj2, ...]` (or single
|
| 1576 |
+
`bpy.types.Object` / `str` object name) sharing a UV atlas. When `None`,
|
| 1577 |
+
bakes each visible mesh object independently.
|
| 1578 |
+
resolution: Square bake resolution in pixels (`1024` default).
|
| 1579 |
+
samples: Cycles sample count (`8` default).
|
| 1580 |
+
|
| 1581 |
+
Returns:
|
| 1582 |
+
Mapping `key -> {'basecolor': path, 'roughness': path, 'metallic': path,
|
| 1583 |
+
'normal': path}`.
|
| 1584 |
+
"""
|
| 1585 |
+
out_dir = os.path.abspath(out_dir)
|
| 1586 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 1587 |
+
bpy.context.view_layer.update()
|
| 1588 |
+
|
| 1589 |
+
vis_objs = [
|
| 1590 |
+
obj
|
| 1591 |
+
for obj in bpy.data.objects
|
| 1592 |
+
if obj.type == 'MESH'
|
| 1593 |
+
and not obj.hide_render
|
| 1594 |
+
and not obj.name.endswith('_col')
|
| 1595 |
+
and '_hull_' not in obj.name
|
| 1596 |
+
]
|
| 1597 |
+
vis_set = set(vis_objs)
|
| 1598 |
+
|
| 1599 |
+
groups: dict[str, list[bpy.types.Object]] = {}
|
| 1600 |
+
if material_groups is not None:
|
| 1601 |
+
for key, objs in material_groups.items():
|
| 1602 |
+
resolved_grp = _resolve_object_list(objs)
|
| 1603 |
+
valid: list[bpy.types.Object] = []
|
| 1604 |
+
for o in resolved_grp:
|
| 1605 |
+
if o in vis_set and _collect_group_materials([o]):
|
| 1606 |
+
if _uvs_need_unwrap(o):
|
| 1607 |
+
smart_uv_project([o], angle_limit_deg=66.0, island_margin=0.01)
|
| 1608 |
+
if o.data.uv_layers:
|
| 1609 |
+
valid.append(o)
|
| 1610 |
+
if valid:
|
| 1611 |
+
groups[str(key)] = valid
|
| 1612 |
+
else:
|
| 1613 |
+
for obj in vis_objs:
|
| 1614 |
+
if _collect_group_materials([obj]):
|
| 1615 |
+
if _uvs_need_unwrap(obj):
|
| 1616 |
+
smart_uv_project([obj], angle_limit_deg=66.0, island_margin=0.01)
|
| 1617 |
+
if obj.data.uv_layers:
|
| 1618 |
+
groups[obj.name] = [obj]
|
| 1619 |
+
|
| 1620 |
+
if not groups:
|
| 1621 |
+
return {}
|
| 1622 |
+
|
| 1623 |
+
scene = bpy.context.scene
|
| 1624 |
+
prev_engine = scene.render.engine
|
| 1625 |
+
prev_device = scene.cycles.device
|
| 1626 |
+
prev_samples = scene.cycles.samples
|
| 1627 |
+
prev_denoise = scene.cycles.use_denoising
|
| 1628 |
+
prev_margin = scene.render.bake.margin
|
| 1629 |
+
prev_use_clear = scene.render.bake.use_clear
|
| 1630 |
+
prev_vt = scene.view_settings.view_transform
|
| 1631 |
+
prev_look = scene.view_settings.look
|
| 1632 |
+
prev_exposure = scene.view_settings.exposure
|
| 1633 |
+
prev_gamma = scene.view_settings.gamma
|
| 1634 |
+
prev_active = bpy.context.view_layer.objects.active
|
| 1635 |
+
prev_selected = [o for o in bpy.data.objects if o.select_get()]
|
| 1636 |
+
|
| 1637 |
+
results: dict[str, dict[str, str]] = {}
|
| 1638 |
+
try:
|
| 1639 |
+
if bpy.context.active_object and bpy.context.active_object.mode != 'OBJECT':
|
| 1640 |
+
bpy.ops.object.mode_set(mode='OBJECT')
|
| 1641 |
+
|
| 1642 |
+
scene.render.engine = 'CYCLES'
|
| 1643 |
+
scene.cycles.device = 'CPU'
|
| 1644 |
+
scene.cycles.samples = max(1, int(samples))
|
| 1645 |
+
scene.cycles.use_denoising = False
|
| 1646 |
+
scene.render.bake.margin = max(4, int(resolution) // 64)
|
| 1647 |
+
scene.view_settings.view_transform = 'Raw'
|
| 1648 |
+
scene.view_settings.look = 'None'
|
| 1649 |
+
scene.view_settings.exposure = 0.0
|
| 1650 |
+
scene.view_settings.gamma = 1.0
|
| 1651 |
+
|
| 1652 |
+
for key, grp_objs in groups.items():
|
| 1653 |
+
mats = _collect_group_materials(grp_objs)
|
| 1654 |
+
if not mats:
|
| 1655 |
+
continue
|
| 1656 |
+
|
| 1657 |
+
rigs = [_MatBakeRig(mat) for mat in mats]
|
| 1658 |
+
try:
|
| 1659 |
+
bc_p = os.path.join(out_dir, f'{key}_basecolor.png')
|
| 1660 |
+
rg_p = os.path.join(out_dir, f'{key}_roughness.png')
|
| 1661 |
+
mt_p = os.path.join(out_dir, f'{key}_metallic.png')
|
| 1662 |
+
nm_p = os.path.join(out_dir, f'{key}_normal.png')
|
| 1663 |
+
|
| 1664 |
+
for socket_name, out_p, is_srgb in (
|
| 1665 |
+
('Base Color', bc_p, True),
|
| 1666 |
+
('Roughness', rg_p, False),
|
| 1667 |
+
('Metallic', mt_p, False),
|
| 1668 |
+
):
|
| 1669 |
+
bake_img = bpy.data.images.new(
|
| 1670 |
+
f'_pbr_emit_{key}_{socket_name}',
|
| 1671 |
+
width=int(resolution),
|
| 1672 |
+
height=int(resolution),
|
| 1673 |
+
alpha=False,
|
| 1674 |
+
)
|
| 1675 |
+
bake_img.colorspace_settings.name = 'sRGB' if is_srgb else 'Non-Color'
|
| 1676 |
+
try:
|
| 1677 |
+
for rig in rigs:
|
| 1678 |
+
rig.wire_socket_to_emit(socket_name)
|
| 1679 |
+
rig.activate_target_image(bake_img)
|
| 1680 |
+
for idx, obj in enumerate(grp_objs):
|
| 1681 |
+
scene.render.bake.use_clear = idx == 0
|
| 1682 |
+
_select_only(obj)
|
| 1683 |
+
bpy.ops.object.bake(type='EMIT')
|
| 1684 |
+
bake_img.filepath_raw = out_p
|
| 1685 |
+
bake_img.file_format = 'PNG'
|
| 1686 |
+
bake_img.save()
|
| 1687 |
+
finally:
|
| 1688 |
+
bpy.data.images.remove(bake_img)
|
| 1689 |
+
|
| 1690 |
+
for rig in rigs:
|
| 1691 |
+
rig.restore_surface_links()
|
| 1692 |
+
|
| 1693 |
+
norm_img = bpy.data.images.new(
|
| 1694 |
+
f'_pbr_norm_{key}',
|
| 1695 |
+
width=int(resolution),
|
| 1696 |
+
height=int(resolution),
|
| 1697 |
+
alpha=False,
|
| 1698 |
+
)
|
| 1699 |
+
norm_img.colorspace_settings.name = 'Non-Color'
|
| 1700 |
+
try:
|
| 1701 |
+
for rig in rigs:
|
| 1702 |
+
rig.activate_target_image(norm_img)
|
| 1703 |
+
for idx, obj in enumerate(grp_objs):
|
| 1704 |
+
scene.render.bake.use_clear = idx == 0
|
| 1705 |
+
_select_only(obj)
|
| 1706 |
+
bpy.ops.object.bake(
|
| 1707 |
+
type='NORMAL',
|
| 1708 |
+
normal_space='TANGENT',
|
| 1709 |
+
normal_r='POS_X',
|
| 1710 |
+
normal_g='POS_Y',
|
| 1711 |
+
normal_b='POS_Z',
|
| 1712 |
+
)
|
| 1713 |
+
norm_img.filepath_raw = nm_p
|
| 1714 |
+
norm_img.file_format = 'PNG'
|
| 1715 |
+
norm_img.save()
|
| 1716 |
+
finally:
|
| 1717 |
+
bpy.data.images.remove(norm_img)
|
| 1718 |
+
|
| 1719 |
+
results[key] = {
|
| 1720 |
+
'basecolor': bc_p,
|
| 1721 |
+
'roughness': rg_p,
|
| 1722 |
+
'metallic': mt_p,
|
| 1723 |
+
'normal': nm_p,
|
| 1724 |
+
}
|
| 1725 |
+
finally:
|
| 1726 |
+
for rig in rigs:
|
| 1727 |
+
rig.cleanup()
|
| 1728 |
+
finally:
|
| 1729 |
+
scene.render.engine = prev_engine
|
| 1730 |
+
scene.cycles.device = prev_device
|
| 1731 |
+
scene.cycles.samples = prev_samples
|
| 1732 |
+
scene.cycles.use_denoising = prev_denoise
|
| 1733 |
+
scene.render.bake.margin = prev_margin
|
| 1734 |
+
scene.render.bake.use_clear = prev_use_clear
|
| 1735 |
+
scene.view_settings.view_transform = prev_vt
|
| 1736 |
+
scene.view_settings.look = prev_look
|
| 1737 |
+
scene.view_settings.exposure = prev_exposure
|
| 1738 |
+
scene.view_settings.gamma = prev_gamma
|
| 1739 |
+
for obj in bpy.data.objects:
|
| 1740 |
+
want_sel = obj in prev_selected
|
| 1741 |
+
if obj.select_get() != want_sel:
|
| 1742 |
+
obj.select_set(want_sel)
|
| 1743 |
+
if prev_active is not None and prev_active.name in bpy.data.objects:
|
| 1744 |
+
bpy.context.view_layer.objects.active = prev_active
|
| 1745 |
+
|
| 1746 |
+
return results
|
| 1747 |
+
|
| 1748 |
+
|
| 1749 |
+
def _srgb_channel_to_linear(val: float) -> float:
|
| 1750 |
+
"""Converts a single sRGB channel (`0..255` or `0..1`) to linear RGB (`0..1`)."""
|
| 1751 |
+
c = max(0.0, min(1.0, float(val)))
|
| 1752 |
+
if c <= 0.04045:
|
| 1753 |
+
return c / 12.92
|
| 1754 |
+
return ((c + 0.055) / 1.055) ** 2.4
|
| 1755 |
+
|
| 1756 |
+
|
| 1757 |
+
def _srgb_tuple_to_linear_rgba(
|
| 1758 |
+
rgb: Sequence[float | int],
|
| 1759 |
+
) -> tuple[float, float, float, float]:
|
| 1760 |
+
"""Converts a 3- or 4-tuple in `0..255` sRGB or `0..1` sRGB to linear RGBA."""
|
| 1761 |
+
vals = [float(x) for x in rgb]
|
| 1762 |
+
scale = 1.0 / 255.0 if max(vals[:3]) > 1.001 else 1.0
|
| 1763 |
+
r = _srgb_channel_to_linear(vals[0] * scale)
|
| 1764 |
+
g = _srgb_channel_to_linear(vals[1] * scale)
|
| 1765 |
+
b = _srgb_channel_to_linear(vals[2] * scale)
|
| 1766 |
+
a = (vals[3] * scale) if len(vals) >= 4 else 1.0
|
| 1767 |
+
return (r, g, b, max(0.0, min(1.0, a)))
|
| 1768 |
+
|
| 1769 |
+
|
| 1770 |
+
def assign_pbr_material(
|
| 1771 |
+
objects: bpy.types.Object | str | Sequence[bpy.types.Object | str],
|
| 1772 |
+
name: str | None = None,
|
| 1773 |
+
*,
|
| 1774 |
+
base_color: Sequence[float | int] | None = None,
|
| 1775 |
+
base_color_srgb: Sequence[float | int] = (200, 200, 200),
|
| 1776 |
+
roughness: float = 0.4,
|
| 1777 |
+
metallic: float = 0.0,
|
| 1778 |
+
normal_bump_mm: float = 0.0,
|
| 1779 |
+
bump_height_mm: float = 0.0,
|
| 1780 |
+
bump_scale: float = 250.0,
|
| 1781 |
+
) -> bpy.types.Material:
|
| 1782 |
+
"""Assigns a clean `Principled BSDF` material (from 8-bit `0..255` or `0..1` sRGB) to `objects`.
|
| 1783 |
+
|
| 1784 |
+
Binds per-part materials directly to Blender sub-objects before
|
| 1785 |
+
`bmu.bake_pbr_maps`.
|
| 1786 |
+
|
| 1787 |
+
Args:
|
| 1788 |
+
objects: Single mesh object/name or list of mesh objects/names.
|
| 1789 |
+
name: Optional material name. Defaults to `<first_obj_name>_mat`.
|
| 1790 |
+
base_color: Alias for `base_color_srgb` (`0..255` or `0..1` sRGB).
|
| 1791 |
+
base_color_srgb: `(R, G, B)` in `0..255` sRGB (e.g. from `rgb_sample_boxes`
|
| 1792 |
+
`p50`/`p75`) or `0..1` sRGB. Automatically converted to linear RGB.
|
| 1793 |
+
roughness: Scalar surface roughness in `[0, 1]`.
|
| 1794 |
+
metallic: Scalar metallic factor in `[0, 1]`.
|
| 1795 |
+
normal_bump_mm: Alias for `bump_height_mm` in `mm`.
|
| 1796 |
+
bump_height_mm: Optional micro-grain / procedural bump height in `mm`.
|
| 1797 |
+
bump_scale: 3D noise scale when `bump_height_mm > 0`.
|
| 1798 |
+
|
| 1799 |
+
Returns:
|
| 1800 |
+
The created `bpy.types.Material`.
|
| 1801 |
+
"""
|
| 1802 |
+
objs = _resolve_object_list(objects)
|
| 1803 |
+
if not objs:
|
| 1804 |
+
raise ValueError(
|
| 1805 |
+
f'assign_pbr_material: no matching mesh objects for {objects!r}'
|
| 1806 |
+
)
|
| 1807 |
+
mat_name = name or f'{objs[0].name}_mat'
|
| 1808 |
+
mat = bpy.data.materials.get(mat_name) or bpy.data.materials.new(mat_name)
|
| 1809 |
+
if mat.node_tree is None:
|
| 1810 |
+
mat.use_nodes = True
|
| 1811 |
+
nt = mat.node_tree
|
| 1812 |
+
nt.nodes.clear()
|
| 1813 |
+
|
| 1814 |
+
out_node = nt.nodes.new('ShaderNodeOutputMaterial')
|
| 1815 |
+
bsdf = nt.nodes.new('ShaderNodeBsdfPrincipled')
|
| 1816 |
+
color_arg = base_color if base_color is not None else base_color_srgb
|
| 1817 |
+
lin_rgba = _srgb_tuple_to_linear_rgba(color_arg)
|
| 1818 |
+
bsdf.inputs['Base Color'].default_value = lin_rgba
|
| 1819 |
+
bsdf.inputs['Roughness'].default_value = float(max(0.0, min(1.0, roughness)))
|
| 1820 |
+
bsdf.inputs['Metallic'].default_value = float(max(0.0, min(1.0, metallic)))
|
| 1821 |
+
nt.links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])
|
| 1822 |
+
|
| 1823 |
+
eff_bump_mm = (
|
| 1824 |
+
float(normal_bump_mm)
|
| 1825 |
+
if float(normal_bump_mm) > 0.0
|
| 1826 |
+
else float(bump_height_mm)
|
| 1827 |
+
)
|
| 1828 |
+
if eff_bump_mm > 0.0:
|
| 1829 |
+
bump_node = nt.nodes.new('ShaderNodeBump')
|
| 1830 |
+
bump_node.inputs['Strength'].default_value = 1.0
|
| 1831 |
+
bump_node.inputs['Distance'].default_value = max(eff_bump_mm, 0.05) * 0.001
|
| 1832 |
+
coord_node = nt.nodes.new('ShaderNodeTexCoord')
|
| 1833 |
+
noise_node = nt.nodes.new('ShaderNodeTexNoise')
|
| 1834 |
+
noise_node.inputs['Scale'].default_value = float(bump_scale)
|
| 1835 |
+
noise_node.inputs['Detail'].default_value = 4.0
|
| 1836 |
+
noise_node.inputs['Roughness'].default_value = 0.6
|
| 1837 |
+
nt.links.new(coord_node.outputs['Object'], noise_node.inputs['Vector'])
|
| 1838 |
+
nt.links.new(noise_node.outputs['Fac'], bump_node.inputs['Height'])
|
| 1839 |
+
nt.links.new(bump_node.outputs['Normal'], bsdf.inputs['Normal'])
|
| 1840 |
+
|
| 1841 |
+
mat['mujoco_authored_pbr'] = True
|
| 1842 |
+
for obj in objs:
|
| 1843 |
+
if obj.type == 'MESH' and obj.data is not None:
|
| 1844 |
+
obj.data.materials.clear()
|
| 1845 |
+
obj.data.materials.append(mat)
|
| 1846 |
+
obj.color = lin_rgba
|
| 1847 |
+
return mat
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/SKILL.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: fr3-duo-control
|
| 3 |
+
description: Franka Duo robot only (Franka Research 3 / FR3 Duo dual-arm cell with Robotiq 2F-85 grippers, ZED Mini and RealSense D405 cameras). Brings up, homes, and controls it via pylibfranka on hardware or in MuJoCo sim. Use only when the user names Franka Duo, FR3 Duo, or fr3_duo.
|
| 4 |
+
metadata:
|
| 5 |
+
publisher: google
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
# Franka Research 3 Duo Control (`fr3_duo`)
|
| 9 |
+
|
| 10 |
+
Operate and program a dual-arm **FR3 Duo** (`left`/`right` 7-DOF FR3 arms, Robotiq 2F-85 grippers, overhead ZED Mini stereo camera, and wrist RealSense D405 RGB cameras) under `R1–R16` in [safety_rules.md](references/safety_rules.md) and [hardware_limits.md](references/hardware_limits.md). For offline `mode="sim"`, canonical `MjSpec` scenes, and live MuJoCo Studio workflows, see [mujoco_sim.md](references/mujoco_sim.md).
|
| 11 |
+
|
| 12 |
+
## 1. Setup Gate
|
| 13 |
+
|
| 14 |
+
1. **Offline sim only:** Run `Fr3DuoRobot(cfg, mode="sim")` directly (`default_robot_config()` works with no hardware or `config/robot_config.json`; set `MUJOCO_GL=egl` or `osmesa` on headless Linux for `render_sim_cameras`).
|
| 15 |
+
2. **Missing/incomplete `config/robot_config.json`, or bring-up/homing/diagnostics:** Follow [bringup_checklist.md](references/bringup_checklist.md) via [bringup.py](scripts/bringup.py) (`uv run scripts/bringup.py`, e.g. `--dry-run`, `--step geometry`, `--up-to all`, `--step home --yes`; orchestrates [discover_hardware.py](scripts/discover_hardware.py), [check_cameras.py](scripts/check_cameras.py), [check_robot.py](scripts/check_robot.py)). Split operator prompts cleanly across **two turns** during Stage 1 rather than dumping all checks at once:
|
| 16 |
+
* **Turn 1 (connection prerequisite -> run `--step preflight --read-only`):** Confirm only left/right FR3 FCI IPs (stating robot vs. operator left/right) and that joints are unlocked, FCI is enabled, and physical E-stop is within reach. Let `--step preflight` auto-check tilted Desk gravity/payload, USB/RS-485 ports, cameras, and conflicting processes before asking the operator to intervene.
|
| 17 |
+
* **Turn 2 (Stage 1b geometry -> run `--step geometry`):** Show/attach [fr3_duo_dimensions_reference.png](assets/fr3_duo_dimensions_reference.png) inline to the operator and confirm the 6 measurements in meters (`m`): `base_height_m`, `table_height_m` -> `z_table_m`, `table_front_offset_m`, `table_width_m`, `table_depth_m`, and `tcp_offset_z_m` (`0.145 m` stock 2F-85 silicone pads vs `0.185 m` extended fingers). Defer the optional `tmux` prompt (`R11`) until live motion stages.
|
| 18 |
+
Before live hardware actuation or downstream skill composition, `config/robot_config.json` must satisfy `validate_robot_config_complete(cfg) == []` (`arms.{left,right}.{ip,gripper_port}`, all 3 `cameras.*` entries, and `geometry_confirmed=True`).
|
| 19 |
+
3. **Hardware already verified (`R2`, complete config):** Skip bring-up motion checks; run your task with `Fr3DuoRobot(cfg, mode="hardware", dry_run=True)` (or `Fr3DuoSafetyChecker`), then wait for explicit `"go"` (`R1`) before `dry_run=False`.
|
| 20 |
+
|
| 21 |
+
## 2. Canonical Contract, Coordinate Frames & Runtime Control API
|
| 22 |
+
|
| 23 |
+
* **Base frame (`base` / `franka_fr3_duo_world`):** `+X` forward across tabletop (`[0.15, 0.95] m`), `+Y` robot-left (`[-0.55, +0.55] m`; operator-right facing pedestal), `+Z` up (`z_table_m` typically `[-0.03, +0.05] m`). `left` and `right` are from the **robot's perspective (not the operator's when facing the pedestal)**—state both when prompting a human.
|
| 24 |
+
* **Joints, Grippers & Tool Center Point (TCP):** `state_16d` order is `[left_q1..q7, left_grip, right_q1..q7, right_grip]` (`{side}/fr3_joint1..7`). TCP is `{side}/robotiq_gripper_{side}/pinch_site` (`0.145 m` default `tcp_offset_z_m`); gripper `0.0 = 85 mm open`, `1.0 = 0 mm closed` (empty pinch stalls at `0.82–0.91`).
|
| 25 |
+
* **4 Canonical RGB Streams (`1280x720` USB/UVC):** `head_camera_left`, `head_camera_right` (split from `2560x720` ZED Mini stereo), `wrist_camera_left`, `wrist_camera_right` (`{side}/wrist_camera/wrist_camera_{side}` D405).
|
| 26 |
+
* **Python / `uv` Environment (`pylibfranka`):** `pylibfranka` ships pre-built Linux x86_64 wheels for Python `3.9–3.12` (`requires-python = ">=3.9,<3.13"` in [bringup.py](scripts/bringup.py)). Run `uv run scripts/bringup.py ...` directly, or pass `uv run --python 3.12 <task_script>.py` / create `.venv` with `--python 3.12` for custom task scripts.
|
| 27 |
+
* **Architecture (`Fr3DuoRobot` -> `Fr3DuoRealBackend` / `Fr3DuoSimBackend` -> Hardware Controllers + Services):**
|
| 28 |
+
1. **Robot & Backends:**
|
| 29 |
+
* [fr3_duo_robot.py](scripts/fr3_duo_robot.py): `Fr3DuoRobot(cfg, mode="sim"|"hardware", dry_run=False)` context manager validating moves via `Fr3DuoSafetyChecker` and dispatching to `Fr3DuoRealBackend` or `Fr3DuoSimBackend` (`read_state`, `recover_errors`, `render_sim_cameras`, `activate_grippers`, `move_gripper`, `move_arm_waypoints`, `move_bimanual_waypoints`). `Fr3DuoRealBackend` reads `state.current_errors` and attempts `pylibfranka.Robot.automatic_error_recovery()` on recoverable errors/reflexes; extend `fr3_arm_controller.py` + `fr3_duo_robot.py` when adding `pylibfranka` or real-backend features.
|
| 30 |
+
2. **Hardware Controllers:**
|
| 31 |
+
* [fr3_arm_controller.py](scripts/fr3_arm_controller.py): Core `pylibfranka` wrapper (`ArmWorkerProcess` isolated 1 kHz FCI worker, `read_pylibfranka_state`, `recover_pylibfranka_errors`, `audit_arm_desk_config`, `validate_arm_readiness`, `probe_arm_readonly`, `read_arm_joints_or_rest`).
|
| 32 |
+
* [robotiq_gripper_controller.py](scripts/robotiq_gripper_controller.py): `RobotiqGripper`, `RobotiqStatus`, `resolve_serial_ports`, `select_gripper_ports`.
|
| 33 |
+
* [fr3_camera_controller.py](scripts/fr3_camera_controller.py): `Fr3DuoCameraController` (freshness `<= 0.30 s`, side-by-side ZED stereo split), `render_contact_sheet`, `discover_uvc_devices`, `check_linux_usb_permissions`.
|
| 34 |
+
3. **Services / Shared Utilities:**
|
| 35 |
+
* [fr3_config.py](scripts/fr3_config.py): `RobotConfig`, `ArmConfig`, `ArmsConfig`, `CamerasConfig`, `DEFAULT_CONFIG_PATH`, `default_robot_config`, `load_robot_config`, `save_robot_config`, `normalize_robot_config`, `table_box_bounds`, `validate_robot_config_complete`, `detect_preempt_rt`, `resolve_realtime_config`.
|
| 36 |
+
* [fr3_mjcf.py](scripts/fr3_mjcf.py): `build_fr3_duo_spec(cfg)` & `build_fr3_duo_mjcf(cfg)` (single canonical Menagerie `MjSpec` builder + sparse GitHub cache), `DEFAULT_REST_POSE_RAD`.
|
| 37 |
+
* [fr3_kinematics.py](scripts/fr3_kinematics.py): `compute_arm_fk`, `compute_arm_pinch_from_flange`, `estimate_external_wrench_base`, `get_camera_calibration_opencv`, `project_base_points_opencv`.
|
| 38 |
+
* [fr3_safety.py](scripts/fr3_safety.py): `FR3_HW_MAX_VEL_RAD_S`, `FR3_HW_MAX_ACC_RAD_S2` (`7.5` J1–J2, `9.5` J3–J7), `FR3_HW_MAX_JERK_RAD_S3` (`3500` / `4500`), `MIN_INTER_ARM_CLEARANCE_M` (`0.030`), `generate_quintic_trajectory`, `validate_joint_waypoints`, `AbortWatcher`, `Fr3DuoSafetyChecker`.
|
| 39 |
+
|
| 40 |
+
## 3. Composition Map (`rgb-object-localization` -> `motion-planning` -> `fr3_duo_robot` -> `visual-servoing` / `iteration`)
|
| 41 |
+
|
| 42 |
+
* **Perception & planning (`rgb-object-localization`, `motion-planning`, `visual-servoing`):** Pass `get_camera_calibration_opencv(...)` (`K`, `T_base_cam`) to `ray_plane_contour_pose`, `build_fr3_duo_mjcf(cfg)` to `mp.RobotArmPlanner(..., arm="left"|"right")` (`add_other_arm_to_scene`), and `wrist_camera_{side}` (`intrinsics_tuple`, `T_ee_cam`) to `ibvs.Ibvs`.
|
| 43 |
+
* **Iteration & Studio / Sim (`iteration`, `mujoco-studio-sidecar`, `sim2real-gauntlet`):** Stage scripts with 4-cam MP4 capture; build interactive Studio scenes via `fr3_mjcf.build_fr3_duo_spec` ([mujoco_sim.md](references/mujoco_sim.md)) or grade offline.
|
| 44 |
+
|
| 45 |
+
Import sibling `robotics` scripts relative to `skills/fr3-duo-control/` (`../rgb-object-localization/scripts`, `../motion-planning/scripts`, `../visual-servoing/scripts`; include `pillow` and `scipy` via `--with pillow --with scipy` or `.venv` when composing `motion-planning`):
|
| 46 |
+
|
| 47 |
+
```python
|
| 48 |
+
from pathlib import Path
|
| 49 |
+
import sys
|
| 50 |
+
import tempfile
|
| 51 |
+
|
| 52 |
+
_SKILLS_DIR = Path(__file__).resolve().parents[2]
|
| 53 |
+
for rel in ("fr3-duo-control/scripts", "motion-planning/scripts", "rgb-object-localization/scripts", "visual-servoing/scripts"):
|
| 54 |
+
sys.path.insert(0, str(_SKILLS_DIR / rel))
|
| 55 |
+
|
| 56 |
+
from fr3_config import load_robot_config
|
| 57 |
+
from fr3_mjcf import build_fr3_duo_mjcf
|
| 58 |
+
from fr3_kinematics import get_camera_calibration_opencv
|
| 59 |
+
from fr3_duo_robot import Fr3DuoRobot
|
| 60 |
+
from fr3_safety import clamp_q_to_padded_limits
|
| 61 |
+
import motion_planner as mp
|
| 62 |
+
import rgb_localization
|
| 63 |
+
import ibvs
|
| 64 |
+
|
| 65 |
+
cfg = load_robot_config("config/robot_config.json")
|
| 66 |
+
mj_model, mjcf_xml = build_fr3_duo_mjcf(cfg)
|
| 67 |
+
tmp_xml = Path(tempfile.mkdtemp(prefix="fr3_mp_")) / "fr3_duo.xml"
|
| 68 |
+
tmp_xml.write_text(mjcf_xml, encoding="utf-8")
|
| 69 |
+
left_planner = mp.RobotArmPlanner(mjcf_path=str(tmp_xml), arm="left", gripper_cmd=0.0)
|
| 70 |
+
scene = mp.Scene3D()
|
| 71 |
+
table_center, table_half_extents = cfg.table_box_bounds()
|
| 72 |
+
scene.add_aligned_box("table", center=table_center, half_extents=table_half_extents, group="table")
|
| 73 |
+
with Fr3DuoRobot(cfg, mode="sim") as robot: # pass dry_run=True to validate real moves offline first
|
| 74 |
+
state = robot.read_state()
|
| 75 |
+
left_planner.add_other_arm_to_scene(scene, other_arm_q=state["right"]["q_rad"], other_gripper_cmd=state["right"]["gripper_ratio"])
|
| 76 |
+
cal = get_camera_calibration_opencv(mj_model, state["left"]["q_rad"], state["right"]["q_rad"])
|
| 77 |
+
|
| 78 |
+
# 1. Localize target (OpenCV T_base_cam) or triangulate (MuJoCo mj_pose for mp.*)
|
| 79 |
+
pose_3d = rgb_localization.ray_plane_contour_pose(mask_u8, cal["head_camera_left"]["K"], cal["head_camera_left"]["T_base_cam"], z_plane_m=float(cfg.z_table_m))
|
| 80 |
+
table_pt = mp.intersect_ray_plane(640.0, 360.0, cal["head_camera_left"]["mj_pose"], cal["head_camera_left"]["mp_intrinsics"], plane_z=float(cfg.z_table_m))
|
| 81 |
+
|
| 82 |
+
# 2. Plan & execute sparse waypoints (clamping J4 safety margin to [−2.9421, −0.2518])
|
| 83 |
+
plan = left_planner.plan_arm(scene, state["left"]["q_rad"], q_pregrasp)
|
| 84 |
+
safe_wps = [clamp_q_to_padded_limits(q).tolist() for q in plan["waypoints"]]
|
| 85 |
+
robot.move_arm_waypoints("left", safe_wps)
|
| 86 |
+
|
| 87 |
+
# 3. Close-range eye-in-hand IBVS alignment before grasp
|
| 88 |
+
ibvs_left = ibvs.Ibvs(*cal["wrist_camera_left"]["intrinsics_tuple"])
|
| 89 |
+
step = ibvs_left.compute_step(u, v, z_depth, u_goal, v_goal, cal["wrist_camera_left"]["T_ee_cam"])
|
| 90 |
+
```
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/assets/fr3_duo_dimensions_reference.png
ADDED
|
Git LFS Details
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/references/bringup_checklist.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Franka Research 3 Duo Bring-Up Checklist (Stages 0–4)
|
| 2 |
+
|
| 3 |
+
Use this runbook when setting up a **Franka Research 3 Duo (`fr3_duo`)** cell for the first time, after hardware/desk changes, or when diagnosing hardware (`config/robot_config.json` missing/unverified). Once verified, follow `R2` in [safety_rules.md](safety_rules.md) and `--dry-run` your target task directly without re-running bring-up motion steps.
|
| 4 |
+
|
| 5 |
+
All stages run through the single CLI entrypoint [bringup.py](../scripts/bringup.py) (`uv run scripts/bringup.py ...`), which orchestrates internal stage modules `discover_hardware.py`, `check_cameras.py`, and `check_robot.py`.
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## Stage 0 — Environment & `pylibfranka` Pin Check (`R12–R16`)
|
| 10 |
+
|
| 11 |
+
1. Summarize `R1–R16` from [safety_rules.md](safety_rules.md), initialize `NOTES.md`, and run zero-motion offline Stage 0 + safety preview (`uv run scripts/bringup.py --step env --dry-run`). Do **not** bundle Stage 1 geometry or Desk payload checks into an initial prompt yet.
|
| 12 |
+
2. **Environment & asset setup:**
|
| 13 |
+
* **Python (`3.9–3.12`):** `pylibfranka` Linux x86_64 wheels require Python `3.9–3.12` (`requires-python = ">=3.9,<3.13"`). `uv run scripts/bringup.py ...` ([bringup.py](../scripts/bringup.py)) handles this automatically; for custom task scripts or an explicit virtualenv, pass `--python 3.12`.
|
| 14 |
+
* **MuJoCo robot models (auto-cached):** Standalone runs of [fr3_mjcf.py](../scripts/fr3_mjcf.py) automatically sparse-clone and cache `mujoco_menagerie` (`franka_fr3_duo` + `robotiq_2f85`) into `$XDG_CACHE_HOME/mujoco_menagerie` (or `~/.cache/mujoco_menagerie`)—no manual clone or env var needed:
|
| 15 |
+
```bash
|
| 16 |
+
# Zero-motion offline Stage 0 + safety preview:
|
| 17 |
+
uv run scripts/bringup.py --step env --dry-run
|
| 18 |
+
|
| 19 |
+
# Custom task script or explicit Python 3.12 venv:
|
| 20 |
+
uv run --python 3.12 my_task.py --dry-run
|
| 21 |
+
# Or: uv venv --python 3.12 .venv && uv pip install --python .venv/bin/python pylibfranka pyserial opencv-python numpy mujoco scipy
|
| 22 |
+
```
|
| 23 |
+
* **Firmware / `pylibfranka` compatibility:** FR3 system `>= 5.7.0` pairs with `pylibfranka >= 0.14` (`libfranka >= 0.14`); older firmware returns `IncompatibleLibraryVersionException` on `read_once()`.
|
| 24 |
+
* **Linux `video` / `dialout` permissions:** If udev rules do not already grant R/W access to `/dev/video*` and `/dev/ttyUSB*`:
|
| 25 |
+
```bash
|
| 26 |
+
sudo usermod -aG video,dialout "$USER"
|
| 27 |
+
```
|
| 28 |
+
* **Where to run:** `--dry-run` and `Fr3DuoRobot(cfg, mode="sim")` run offline anywhere. Live hardware (FCI Ethernet, `/dev/ttyUSB*`, `/dev/video*`) must run directly (unsandboxed) on the Linux control PC.
|
| 29 |
+
|
| 30 |
+
---
|
| 31 |
+
|
| 32 |
+
## Stage 1 — Read-Only Hardware Discovery & Geometry Calibration (Two-Turn Prompt, `R4`, `R8`, `R16`)
|
| 33 |
+
|
| 34 |
+
### Turn 1 — Minimal Connection Prerequisite -> Immediate Read-Only Preflight
|
| 35 |
+
|
| 36 |
+
1. Ask the operator for **only** the minimal prerequisite to probe read-only:
|
| 37 |
+
* **Left and right FR3 FCI IP addresses** (common defaults: left `172.16.0.2`, right `172.16.1.2`; or verify saved IPs in `config/robot_config.json`), explicitly noting that `left` (`+Y`, operator's right) and `right` (`-Y`, operator's left) are from the **robot's perspective (not the operator's when facing the pedestal)**.
|
| 38 |
+
* Confirm **joints are unlocked, FCI mode is enabled, and physical E-stop is within reach (`R16`)**.
|
| 39 |
+
* *Do not ask the operator to manually verify tilted Desk gravity/payload or conflicting processes up front*—let `--step preflight --read-only` inspect those automatically and only report concrete failures if any occur.
|
| 40 |
+
2. Run Stage 1 preflight immediately (read-only, zero physical motion):
|
| 41 |
+
```bash
|
| 42 |
+
uv run scripts/bringup.py --step preflight --read-only --output-dir logs/stage1
|
| 43 |
+
uv run scripts/bringup.py --up-to preflight --left-ip 172.16.0.2 --right-ip 172.16.1.2 --output-dir logs/stage1
|
| 44 |
+
```
|
| 45 |
+
* `discover_hardware.run_discovery` checks (zero motion):
|
| 46 |
+
* **Host & USB/serial:** `PREEMPT_RT` status, Robotiq RS-485 ports (`0403:6015` preferred, `0403:6014` teleop ignored, auto-binds `/dev/robotiq_gripper_{left,right}`), ZED Mini / D405 V4L2 nodes, `video`/`dialout` R/W access, and conflicting host processes holding serial, camera, or FCI connections (ask the operator to stop conflicts only if detected).
|
| 47 |
+
* **Desk & wrench:** `robot_mode == kIdle`, payload (`m_ee`, `F_x_Cee`, `I_ee`), tilted gravity `O_ddP_O` (`<= 8.0 deg` vs MJCF), free-air wrench `O_F_ext_hat_K <= 6.5 N`, and joint torque residual `tau_ext_hat_filtered <= 4.5 Nm` (why: upright gravity causes `> 15 N` false `tau_ext` and arm droop).
|
| 48 |
+
* **Kinematics match:** `fk_pos_error_m <= 0.005` (`5.0 mm`) vs MJCF FK.
|
| 49 |
+
* Once gripper/camera paths are saved to `config/robot_config.json`, subsequent runs reuse saved bindings unless `--no-write-config` / rediscovery is requested.
|
| 50 |
+
* Non-`PREEMPT_RT` kernels are supported out of the box under `--realtime auto` (`RealtimeConfig.kIgnore`, `<= 15 deg/s` bring-up cap).
|
| 51 |
+
|
| 52 |
+
### Turn 2 — Physical Cell Geometry & Fingertip Calibration (`--step geometry`)
|
| 53 |
+
|
| 54 |
+
3. **Display/attach [fr3_duo_dimensions_reference.png](../assets/fr3_duo_dimensions_reference.png) inline** for the operator (when supported by the UI/harness) and ask them to confirm or provide the 6 floor-mounted measurements in **meters (`m`)**:
|
| 55 |
+
* **`base_height_m` (`H_base_floor`, default `0.913887 m`):** Floor straight up to the **flat center bracket underside between the shoulder cheeks (`z = z_base = +0.1639 m`, `0.163887 m` exact)**—no vertical offset needed.
|
| 56 |
+
* **`table_height_m` (`H_table_floor`, default `0.75 m`):** Floor to the tabletop surface. Derived tabletop Z in `base` frame:
|
| 57 |
+
`z_table_m = 0.163887 - (base_height_m - table_height_m)` (default yields `z_table_m = 0.0 m`).
|
| 58 |
+
* **`table_front_offset_m` (`D_edge`, default assumption `0.25 m` — operator must confirm):** Plumb down from the **front lip of that flat center bracket underside (`x = +0.0844 m`, `0.08437 m` exact, `|y| <= 0.055 m` cyan bar)** and measure horizontally forward to the table front edge (`x_front = 0.08437 + table_front_offset_m`).
|
| 59 |
+
* **`table_width_m` & `table_depth_m` (defaults `1.22 m` wide x `0.74 m` deep):** Confirm physical tabletop footprint in meters.
|
| 60 |
+
* **`tcp_offset_z_m`:** Confirm installed Robotiq fingertips (`0.145 m` stock 2F-85 silicone pads vs `0.185 m` extended fingers).
|
| 61 |
+
```bash
|
| 62 |
+
# Preview current geometry & config completeness offline
|
| 63 |
+
uv run scripts/bringup.py --step geometry --dry-run
|
| 64 |
+
|
| 65 |
+
# Interactive prompt (sets geometry_confirmed=True and saves config/robot_config.json)
|
| 66 |
+
uv run scripts/bringup.py --step geometry --output-dir logs/stage1
|
| 67 |
+
|
| 68 |
+
# Explicit non-interactive calibration + confirmation
|
| 69 |
+
uv run scripts/bringup.py --step geometry --base-height-m 0.913887 --table-height-m 0.75 --table-front-offset-m 0.25 --table-width-m 1.22 --table-depth-m 0.74 --tcp-offset-z-m 0.145 --confirm-geometry
|
| 70 |
+
```
|
| 71 |
+
* Even with `--yes`, `--step geometry` will **not** silently mark unverified default dimensions confirmed; pass explicit measurement flags + `--confirm-geometry` or complete the interactive prompt.
|
| 72 |
+
* **Completeness gate before live Stage 3/4 motion:** `bringup.py` enforces `fr3_config.validate_robot_config_complete(cfg)` before `gripper`, `nudge`, `abort-test`, and `hello-world` (exiting with code `2` and listing missing `arms.{left,right}.ip`, `arms.{left,right}.gripper_port`, `cameras.{head_stereo,wrist_camera_left,wrist_camera_right}`, or `geometry_confirmed=True`).
|
| 73 |
+
|
| 74 |
+
---
|
| 75 |
+
|
| 76 |
+
## Stage 2 — 4-Camera Freshness, Contact Sheet & MP4 Check (`R6`, `R7`)
|
| 77 |
+
|
| 78 |
+
Verify all 4 canonical streams (`head_camera_left`, `head_camera_right`, `wrist_camera_left`, `wrist_camera_right`) via `check_cameras.run_camera_check`:
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
uv run scripts/bringup.py --step cameras --dry-run
|
| 82 |
+
uv run scripts/bringup.py --up-to cameras --read-only --output-dir logs/stage2
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
1. Confirm `age <= 0.30 s`, changing frames (non-frozen digests), and adequate lighting.
|
| 86 |
+
2. Inspect `contact_sheet_2x2.png`, `fk_projection_overlay_2x2.png`, and `cameras_recording.mp4`.
|
| 87 |
+
|
| 88 |
+
---
|
| 89 |
+
|
| 90 |
+
## Stage 3 — Progressive Robot Verification & Abort Unwind (`R1–R6`, `R11`)
|
| 91 |
+
|
| 92 |
+
Before running live motion steps, optionally attach a persistent `tmux` session (`tmux new-session -d -s robot && tmux attach -t robot`, `R11`) so the operator can observe live telemetry and trigger `q` + `Enter` aborts. Run `--dry-run` safety preview first (`R2`), then step progressively through live checks after explicit human `"go"` (`R1`):
|
| 93 |
+
|
| 94 |
+
```bash
|
| 95 |
+
# Offline kinematics & collision preview (no hardware contact)
|
| 96 |
+
uv run scripts/bringup.py --up-to abort-test --dry-run
|
| 97 |
+
|
| 98 |
+
# Interactive progressive bring-up (prompts before live actuation; pass --yes only after workspace is verified clear)
|
| 99 |
+
uv run scripts/bringup.py --step gripper --output-dir logs/stage3
|
| 100 |
+
uv run scripts/bringup.py --step nudge --realtime auto --output-dir logs/stage3
|
| 101 |
+
uv run scripts/bringup.py --step abort-test --realtime auto --output-dir logs/stage3
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
* `gripper`: activates and cycles both Robotiq 2F-85 grippers `0.0 -> 1.0 -> 0.0`, confirming empty-pinch stall (`0.80 <= ratio < 1.0`).
|
| 105 |
+
* `nudge`: executes a smooth ($C^2$ quintic) `5 deg` Joint 1 (J1) sweep and return on `left` then `right`, enforcing `>= 30 mm` inter-arm clearance and `z_min >= z_table_m`.
|
| 106 |
+
* `abort-test`: verifies `q` + `Enter` / `SIGINT` decelerates smoothly and unwinds backwards along `travelled_waypoints` to `rest_pose` **without opening grippers** (`R3`, `R4`).
|
| 107 |
+
|
| 108 |
+
---
|
| 109 |
+
|
| 110 |
+
## Stage 4 — Bimanual "Hello World" Motion & Homing (`R1–R8`, `R14`)
|
| 111 |
+
|
| 112 |
+
Run the full bimanual greeting (`check_robot.run_hello_world` via `bringup.py`) or return both arms cleanly to canonical rest pose (`--step home`):
|
| 113 |
+
|
| 114 |
+
```bash
|
| 115 |
+
# Dry-run preview, then full interactive bring-up through Stage 4 hello-world
|
| 116 |
+
uv run scripts/bringup.py --up-to hello-world --dry-run
|
| 117 |
+
uv run scripts/bringup.py --up-to all --realtime auto --output-dir logs/stage4
|
| 118 |
+
|
| 119 |
+
# Return both arms smoothly to canonical rest_pose (or dry-run first)
|
| 120 |
+
uv run scripts/bringup.py --step home --dry-run
|
| 121 |
+
uv run scripts/bringup.py --step home --yes
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
`hello-world` performs and records:
|
| 125 |
+
* **Motion sequence:** Moves `left` and `right` arms through a collision-checked greeting pose, cycles both grippers once, returns to `rest_pose`, and cleanly closes 1 kHz FCI control.
|
| 126 |
+
* **Saved outputs:** Writes `stage4_hello_world.mp4` (continuous 4-camera video) and `bringup_summary.json`.
|
| 127 |
+
* **Report:** Emits metrics for your 6-field `R14` report.
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/references/hardware_limits.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Franka Research 3 Duo Hardware Limits, Mount Geometry & Sensor Specs
|
| 2 |
+
|
| 3 |
+
## 1. FR3 7-DOF Arm Joint & Dynamic Limits (Per Arm)
|
| 4 |
+
|
| 5 |
+
| Joint | Position Min (`rad`) | Position Max (`rad`) | IK Safety Margin (`rad`) | HW Max Vel (`rad/s`) | Bring-Up Vel Cap (`kIgnore` / `kEnforce`) | Max Torque (`Nm`) | Max Accel (`rad/s^2`) | Max Jerk (`rad/s^3`) |
|
| 6 |
+
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
| 7 |
+
| `fr3_joint1` | `-2.7437` | `+2.7437` | `0.025` | `2.62` | `0.262` (`15 deg/s`) / `0.524` (`30 deg/s`) | `87.0` | `7.5` | `3500` |
|
| 8 |
+
| `fr3_joint2` | `-1.7837` | `+1.7837` | `0.025` | `2.62` | `0.262` / `0.524` | `87.0` | `7.5` | `3500` |
|
| 9 |
+
| `fr3_joint3` | `-2.9007` | `+2.9007` | `0.025` | `2.62` | `0.262` / `0.524` | `87.0` | `9.5` | `4500` |
|
| 10 |
+
| `fr3_joint4` | `-3.0421` | `-0.1518` | **`0.100`** (`[-2.9421, -0.2518]`) | `2.62` | `0.262` / `0.524` | `87.0` | `9.5` | `4500` |
|
| 11 |
+
| `fr3_joint5` | `-2.8065` | `+2.8065` | `0.025` | `5.26` | `0.262` / `0.524` | `12.0` | `9.5` | `4500` |
|
| 12 |
+
| `fr3_joint6` | `+0.5445` | `+4.5169` | `0.025` | `4.18` | `0.262` / `0.524` | `12.0` | `9.5` | `4500` |
|
| 13 |
+
| `fr3_joint7` | `-3.0159` | `+3.0159` | `0.025` | `5.26` | `0.262` / `0.524` | `12.0` | `9.5` | `4500` |
|
| 14 |
+
|
| 15 |
+
* **Mandatory `fr3_joint4` `0.100 rad` padding:** Clamp `fr3_joint4` to `[-2.9421, -0.2518] rad` (`0.100 rad` margin) with nullspace posture regularization (`posture_cost >= 1e-2`, `posture_gain >= 0.5`). *Why:* Gravity droop (`20-35 mrad`) near `-3.0421 rad` trips FR3's `-3.0321 rad` soft reflex and risks elbow-flip singularities.
|
| 16 |
+
* **J1/J2 acceleration & jerk caps:** `FR3_HW_MAX_ACC_RAD_S2` caps J1–J2 at `7.5 rad/s^2` (`3500 rad/s^3` jerk) and J3–J7 at `9.5 rad/s^2` (`4500 rad/s^3` jerk) to avoid `communication_constraints_violation` during 1 kHz position streaming.
|
| 17 |
+
* **Nominal joint impedance gains:** `Kp = (600, 600, 600, 600, 250, 150, 50) Nm/rad`, `Kd = (30, 30, 30, 30, 10, 10, 5) Nm*s/rad`.
|
| 18 |
+
* **Canonical neutral rest poses (`rad`):**
|
| 19 |
+
* Default FR3 Duo bimanual home (rotated outward with vertical TCPs):
|
| 20 |
+
* `left`: `(0.90, -0.30, -0.4330, -2.1180, 0.8727, 1.9509, -0.7647)`
|
| 21 |
+
* `right`: `(-0.90, -0.30, 0.4330, -2.1180, -0.8727, 1.9509, 0.7647)`
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
## 2. Coordinate Frame & Menagerie Mount Geometry
|
| 26 |
+
|
| 27 |
+
All controller Cartesian coordinates, TCP readouts, and external wrenches are expressed in the Duo **`base` frame (`franka_fr3_duo_world`)**:
|
| 28 |
+
|
| 29 |
+
* `+X`: forward across the tabletop (`[0.15, 0.95] m`).
|
| 30 |
+
* `+Y`: robot-left / operator-right when facing the pedestal (`[-0.55, +0.55] m`).
|
| 31 |
+
* `+Z`: vertically upward (`z_table_m` typically `[-0.03, +0.05] m`; minimum inter-arm clearance `>= 0.030 m`).
|
| 32 |
+
* **Floor-mounted pedestal & tabletop defaults (`config/robot_config.json`):** See [fr3_duo_dimensions_reference.png](../assets/fr3_duo_dimensions_reference.png). The `base` origin sits `0.163887 m` (`+0.1639 m`) below the flat center bracket underside between shoulder cheeks (`base_height_m`, default `0.913887 m`), whose front lip is at `x = +0.08437 m` (`+0.0844 m`). Tabletop Z derives from floor measurements as `z_table_m = 0.163887 - (base_height_m - table_height_m)` (default ALOHA `table_height_m = 0.75 m` -> `z_table_m = 0.0 m`). The default ALOHA `1.22 m` wide (`table_width_m`) x `0.74 m` deep (`table_depth_m`) tabletop (`0.04 m` thick) sits `table_front_offset_m = 0.25 m` (`25 cm`) ahead of that bracket underside front lip (`x_front = 0.33437 m`, `x_center = 0.70437 m`; exposed via `cfg.table_box_bounds()`).
|
| 33 |
+
|
| 34 |
+
Canonical MJCF composition (`fr3_mjcf.build_fr3_duo_mjcf()`):
|
| 35 |
+
|
| 36 |
+
* **Source:** Built directly from `mujoco_menagerie` (`franka_fr3_duo/fr3_duo_with_spine.xml` + `robotiq_2f85/2f85.xml`).
|
| 37 |
+
* **Naming normalization:** Renames `{left,right}_fr3v2_*` joints/bodies to `{left,right}/fr3_*`.
|
| 38 |
+
* **Attachments:** Attaches Robotiq 2F-85 grippers at `{left,right}_attachment_site` (rotated `90 deg` about `+Z`) and mounts cameras on `head_link` and `{side}/fr3_link7`.
|
| 39 |
+
|
| 40 |
+
* **Tilted shoulder mounts (`base` frame in `fr3_duo_with_spine.xml`):**
|
| 41 |
+
* `left/fr3_link0`: `pos = (0.037, 0.05018, 0.05)` m, `quat = (0.865807, -0.436878, 0.0222879, -0.242939)` (`wxyz`)
|
| 42 |
+
* `right/fr3_link0`: mirrored symmetric tilted mount on the Duo pedestal
|
| 43 |
+
* **Head & wrist camera extrinsics:**
|
| 44 |
+
* `head_camera_left` / `head_camera_right` on `head_link` (`pos = (0.069440, 0.0 / -0.063, 0.230128)` m, `quat = (0.643441, 0.293230, -0.293230, -0.643441)` `wxyz`, `63.0 mm` stereo baseline).
|
| 45 |
+
* `wrist_camera_{left,right}` (`{side}/wrist_camera/wrist_camera_{side}`) on `{side}/fr3_link7` (`pos = (0.0639045, 0.0, 0.173407)` m, `quat = (0.122788, 0.696364, 0.696364, 0.122788)` `wxyz`).
|
| 46 |
+
* **Note on `pylibfranka` `O_T_EE`:** `RobotState.O_T_EE` is a 16-element **column-major (Fortran-order)** flat array in each arm's local `link0` frame (`np.asarray(o_t_ee, dtype=np.float64).reshape((4, 4), order="F")`). Transform by `T_base_arm` before comparing against `base`-frame MJCF FK!
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
## 3. Robotiq 2F-85 USB/RS-485 Modbus RTU Specifications
|
| 51 |
+
|
| 52 |
+
* **Serial transport:** `115200` baud, `8N1`, parity `None`, default Modbus slave ID `9`; bind via `/dev/serial/by-id/usb-...` symlinks.
|
| 53 |
+
* **Registers:**
|
| 54 |
+
* Write (`0x10`, `0x03E8`..`0x03EA`, 3 registers / 6 bytes): byte 0 `rACT | (rGTO << 3)`, byte 3 `rPR` (`0..255`), byte 4 `rSP` (`0..255`), byte 5 `rFR` (`0..255`).
|
| 55 |
+
* Read (`0x04`, `0x07D0`..`0x07D2`, 3 registers / 6 bytes): byte 0 `gACT`, `gGTO`, `gSTA`, `gOBJ` (`(b0 >> 6) & 0x03`: `0`=moving, `1`=outer contact, `2`=inner object stall, `3`=at requested target), byte 2 `gFLT`, byte 3 `gPR`, byte 4 `gPO` (`0..255`), byte 5 `gCU` (`10 * raw mA`).
|
| 56 |
+
* **Timing & closure physics:**
|
| 57 |
+
* Normalized command/status: `0.0` = fully open (`85 mm`, `raw = 0`), `1.0` = fully closed (`0 mm`, `raw = 255`).
|
| 58 |
+
* Serial onset deadtime: `~160 ms`; full-stroke close time: `~950 ms`.
|
| 59 |
+
* **Empty pad-to-pad contact:** Physical silicone pads touch at `raw = 210..231 / 255` (`ratio ~0.82-0.91`, never `1.0`), generating `~26 N` internal pinch force. Detect object grasps via **jaw travel shortfall** (`gOBJ == 2`, `position_ratio < 0.92`; stall overdrive cap `0.032` -> `0.832` max object command) confirmed by load change or camera view.
|
| 60 |
+
* **Flange & TCP offset:** Stock 2F-85 `pinch_site` sits at `z = 0.145 m` in gripper base frame (`~11.4 mm` 4-bar arc plunge during closure; extended finger variants such as `0.185 m` can be set via `tcp_offset_z_m`).
|
| 61 |
+
|
| 62 |
+
---
|
| 63 |
+
|
| 64 |
+
## 4. 4-Camera UVC Perception Specs & Optical Frame Conversion
|
| 65 |
+
|
| 66 |
+
| Canonical Stream | Hardware Sensor | Resolution & FPS | Nominal Intrinsics (`HD720`) | Notes |
|
| 67 |
+
| :--- | :--- | :---: | :---: | :--- |
|
| 68 |
+
| `head_camera_left` | Stereolabs ZED Mini (left half of `2560x720` UVC) | `1280x720 @ 30 Hz` | `fx=fy=710.0, cx=640, cy=360` | `63.0 mm` stereo baseline; optional `.conf` rectification |
|
| 69 |
+
| `head_camera_right` | Stereolabs ZED Mini (right half of `2560x720` UVC) | `1280x720 @ 30 Hz` | `fx=fy=710.0, cx=640, cy=360` | Right stereo view (`-0.063 m` baseline offset) |
|
| 70 |
+
| `wrist_camera_left` | Intel RealSense D405 (RGB UVC interface) | `1280x720 @ 30 Hz` | `fx=fy=635.0, cx=640, cy=360` | Short-range passive sensor (`0.07-0.50 m`); RGB-only over pure UVC |
|
| 71 |
+
| `wrist_camera_right` | Intel RealSense D405 (RGB UVC interface) | `1280x720 @ 30 Hz` | `fx=fy=635.0, cx=640, cy=360` | Opposing rest orientation comes from tilted ±45° shoulder mounts via FK—never rotate raw pixels in software |
|
| 72 |
+
|
| 73 |
+
* **Camera frame convention:** MuJoCo cameras look along `-Z_cam` (`+X` right, `+Y` up), whereas OpenCV pinhole helpers (`rgb-object-localization`, `visual-servoing`) look along `+Z_cam` (`+X` right, `+Y` down). Convert camera orientation matrices via `R_world_cv = R_world_mj @ np.diag([1.0, -1.0, -1.0])`.
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/references/mujoco_sim.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Franka Research 3 Duo Simulation & MuJoCo Studio Guide
|
| 2 |
+
|
| 3 |
+
Use this reference when running offline simulation trajectories, building
|
| 4 |
+
custom tabletop scenes, or visualizing the **FR3 Duo** live in **MuJoCo
|
| 5 |
+
Studio** before running physical hardware via `Fr3DuoRobot(cfg, mode="hardware")`.
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## 1. Two Ways to Simulate FR3 Duo
|
| 10 |
+
|
| 11 |
+
| Mode | When to use | Entry point |
|
| 12 |
+
| :--- | :--- | :--- |
|
| 13 |
+
| **Control & Bring-up Dry-Run** | Offline collision/tabletop checks, `bringup.py --dry-run`, camera math, or `Fr3DuoRobot` tasks | `Fr3DuoRobot(cfg, mode="sim")` in [fr3_duo_robot.py](../scripts/fr3_duo_robot.py) |
|
| 14 |
+
| **Interactive 3D Studio / Scene Builder** | Custom objects/tasks built with `MjSpec`, live UI sliders, frame scrubbing (`mujoco-studio-sidecar` + `mujoco-spec-editing`) | `build_fr3_duo_spec()` / `build_fr3_duo_mjcf()` in [fr3_mjcf.py](../scripts/fr3_mjcf.py) |
|
| 15 |
+
|
| 16 |
+
Both use the same canonical `fr3_duo_with_spine` + dual Robotiq 2F-85 model,
|
| 17 |
+
16-DoF `state_16d` order `[left_q1..q7, left_grip, right_q1..q7, right_grip]`,
|
| 18 |
+
normalized `[0.0 = 85 mm open, 1.0 = 0 mm closed]` grippers,
|
| 19 |
+
`DEFAULT_REST_POSE_RAD` (MJCF keyframe `'home'`), and four camera names
|
| 20 |
+
(`head_camera_left`, `head_camera_right`, `wrist_camera_left`,
|
| 21 |
+
`wrist_camera_right`).
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
## 2. Offline Simulation with `Fr3DuoRobot`
|
| 26 |
+
|
| 27 |
+
Pass `mode="sim"` (using `Fr3DuoSimBackend`) to test planning, FK projections,
|
| 28 |
+
and camera rendering offline against the canonical fixed-environment scene
|
| 29 |
+
(`mj_forward` kinematics without dynamic `<freejoint/>` object physics):
|
| 30 |
+
|
| 31 |
+
```python
|
| 32 |
+
from fr3_config import load_robot_config
|
| 33 |
+
from fr3_duo_robot import Fr3DuoRobot
|
| 34 |
+
|
| 35 |
+
cfg = load_robot_config("config/robot_config.json")
|
| 36 |
+
with Fr3DuoRobot(cfg, mode="sim") as robot:
|
| 37 |
+
state = robot.read_state()
|
| 38 |
+
frames = robot.render_sim_cameras(width=1280, height=720)
|
| 39 |
+
robot.activate_grippers()
|
| 40 |
+
robot.move_arm_waypoints("left", [state["left"]["q_rad"], q_target])
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
1. **Compose scene automatically:** `Fr3DuoRobot(cfg, mode="sim")` calls
|
| 44 |
+
`fr3_mjcf.build_fr3_duo_mjcf(cfg)` directly from `mujoco_menagerie`
|
| 45 |
+
(`franka_fr3_duo/fr3_duo_with_spine.xml` + `robotiq_2f85/2f85.xml`).
|
| 46 |
+
Standalone runs automatically sparse-clone and cache Menagerie into
|
| 47 |
+
`$XDG_CACHE_HOME/mujoco_menagerie` (or `~/.cache/mujoco_menagerie`)—no manual
|
| 48 |
+
clone or environment variable needed. The tabletop arena (`include_arena=True`)
|
| 49 |
+
places an ALOHA `1.22 m x 0.74 m` (`table_width_m x table_depth_m`) surface
|
| 50 |
+
`0.25 m` (`25 cm`, `table_front_offset_m`) ahead of the flat center bracket
|
| 51 |
+
underside front lip (`x = 0.08437 m`), at `z_table_m = 0.163887 - (base_height_m - table_height_m)`
|
| 52 |
+
(default `0.913887 m` base / `0.75 m` table -> `0.0 m`, matching
|
| 53 |
+
`cfg.table_box_bounds()`), with pinch site offset `cfg.tcp_offset_z_m`
|
| 54 |
+
(`0.145 m` stock 2F-85 vs `0.185 m` extended).
|
| 55 |
+
2. **Headless camera rendering:** Set `MUJOCO_GL=osmesa` (or `egl`) on headless
|
| 56 |
+
Linux when calling `render_sim_cameras(...)`.
|
| 57 |
+
3. **Dynamic object-manipulation sims (`<freejoint/>` props):**
|
| 58 |
+
* Build your scene from `spec = build_fr3_duo_spec(cfg, include_arena=True,
|
| 59 |
+
add_gravcomp=False)` (or `add_gravcomp=True` for Studio gravity-compensated
|
| 60 |
+
playback), add props to `spec.worldbody`, and advance physics with
|
| 61 |
+
`mujoco.mj_step`.
|
| 62 |
+
* Clamp `RobotArmPlanner` paths with `clamp_q_to_padded_limits` (`0.100 rad`
|
| 63 |
+
J4 margin) and validate trajectories with `generate_quintic_trajectory` and
|
| 64 |
+
`Fr3DuoSafetyChecker`.
|
| 65 |
+
* **Contact validation note:** `Fr3DuoSafetyChecker` forbids contacts between
|
| 66 |
+
the arms and non-arm bodies. In dynamic object-manipulation sims,
|
| 67 |
+
instantiate `Fr3DuoSafetyChecker` on the robot+tabletop
|
| 68 |
+
`build_fr3_duo_spec(cfg)` model while stepping physics on the full scene
|
| 69 |
+
`MjModel`.
|
| 70 |
+
4. **Keep sim-to-real parity:** Restrict perception and grasp checks strictly to
|
| 71 |
+
the 4 RGB camera streams + Robotiq closure status (never read privileged
|
| 72 |
+
object poses from `mj_data.xpos`).
|
| 73 |
+
|
| 74 |
+
---
|
| 75 |
+
|
| 76 |
+
## 3. Canonical `MjSpec` Builder & Live MuJoCo Studio (`mujoco` Plugin)
|
| 77 |
+
|
| 78 |
+
When authoring interactive tabletop scenes or visual debugging workflows, load
|
| 79 |
+
**`mujoco-studio-sidecar`**, **`studio`**, and **`spec_editing`**
|
| 80 |
+
from the `robotics` plugin.
|
| 81 |
+
|
| 82 |
+
### Canonical `MjSpec` Contents
|
| 83 |
+
* `fr3_mjcf.build_fr3_duo_spec(cfg=None, *, menagerie_dir=None, include_arena=True, add_gravcomp=False)`
|
| 84 |
+
returns a configurable `mujoco.MjSpec` with both `fr3v2` arms
|
| 85 |
+
(`{left,right}/fr3_*`), tilted spine mount, dual Robotiq 2F-85 grippers
|
| 86 |
+
(`pinch_site`), tabletop arena (`include_arena=True`), `'home'` keyframe
|
| 87 |
+
(`DEFAULT_REST_POSE_RAD`), and calibrated head + wrist cameras.
|
| 88 |
+
* `fr3_mjcf.build_fr3_duo_mjcf(...)` compiles `(MjModel, mjcf_xml)` and strips
|
| 89 |
+
unnamed `<default>` wrappers so `RobotArmPlanner` and `describe_robot` parse
|
| 90 |
+
the XML cleanly.
|
| 91 |
+
|
| 92 |
+
### Minimal Live `SimPlugin` for MuJoCo Studio Web
|
| 93 |
+
Publish the `MjSpec` in `<workspace_dir>/sim_plugin.py` so Studio hot-reloads
|
| 94 |
+
the scene in the aux pane:
|
| 95 |
+
|
| 96 |
+
```python
|
| 97 |
+
from fr3_mjcf import build_fr3_duo_spec
|
| 98 |
+
from mujoco.studio import plugin as studio_plugin
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class Fr3DuoSimPlugin(studio_plugin.SimPlugin):
|
| 102 |
+
def on_load_model(self, event) -> bool:
|
| 103 |
+
if event.path:
|
| 104 |
+
return False
|
| 105 |
+
spec = build_fr3_duo_spec(add_gravcomp=True)
|
| 106 |
+
# Add tabletop props here with spec.worldbody.add_body(...)
|
| 107 |
+
self.handle.set_model(spec)
|
| 108 |
+
return True
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
Launch `<mujoco-studio-sidecar>/scripts/studiod.py --workspace_dir=<dir>` with
|
| 112 |
+
`skills/fr3-duo-control/scripts` on `PYTHONPATH`, then promote validated joint
|
| 113 |
+
trajectories to hardware via `Fr3DuoRobot(cfg, mode="hardware", dry_run=True)`
|
| 114 |
+
under `R1–R16` in [safety_rules.md](safety_rules.md).
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/references/safety_rules.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Franka Research 3 Duo Safety Rules & Operational Rationale (`R1–R16`)
|
| 2 |
+
|
| 3 |
+
Always follow `R1–R16` when operating, programming, or bringing up a dual-arm **FR3 Duo** (`left`/`right` 7-DOF FR3 arms + Robotiq 2F-85 grippers + ZED Mini + RealSense D405 cameras).
|
| 4 |
+
|
| 5 |
+
## Summary of Rules `R1–R16`
|
| 6 |
+
|
| 7 |
+
| Rule | Title | Technical Enforcement & Operational Gate |
|
| 8 |
+
| :--- | :--- | :--- |
|
| 9 |
+
| **R1** | Confirm Desk & get `"go"` before live motion | Confirm Desk brakes open, FCI enabled, tilted Duo gravity vector + Robotiq 2F-85/wrist-camera payload configured. Before energizing live actuators, state arms, start/end poses, `z_min`, peak joint speed, and abort instructions, and wait for explicit human `"go"`. Never ask `"go"` for `--dry-run`, `--read-only`, camera checks, or software setup. |
|
| 10 |
+
| **R2** | Auto-run `--dry-run` first | Always run `--dry-run` (offline `Fr3DuoSafetyChecker` bounds, collision, and FK validation with zero hardware access) before requesting live `"go"`. **Once `config/robot_config.json` is populated and hardware is verified**, `--dry-run` the target task directly without re-running bring-up motion checks. For first-time bring-up, step `env -> preflight -> cameras -> gripper -> nudge -> abort-test -> hello-world`, changing one variable per trial. |
|
| 11 |
+
| **R3** | Abort key on every motion (`q` + `Enter`) | `AbortWatcher` monitors stdin (`q` + `Enter`) and `SIGINT` (`Ctrl-C`), smoothly decelerating ($C^2$) and unwinding backwards along `travelled_waypoints` to `rest_pose` **without opening grippers** so held payloads are never dropped mid-air. |
|
| 12 |
+
| **R4** | Clean FCI stop & post-E-stop recovery | Never close a 1 kHz `pylibfranka` control loop mid-motion; decelerate to zero velocity/acceleration (`MotionFinished`) at `rest_pose` first. After any E-stop or Franka reflex, clear errors in Desk, restart FCI + Robotiq serial sessions, and re-run `bringup.py --step preflight` and `--step gripper` before resuming motion. |
|
| 13 |
+
| **R5** | Speed, $C^2$ quintic, joint & clearance limits | Use $C^2$ quintics (`<= 15 deg/s` under `kIgnore`, `<= 30 deg/s` on `PREEMPT_RT` `kEnforce`, `<= 45 deg/s` explicit `--realtime enforce`), `0.100 rad` J4 margin (`[-2.9421, -0.2518] rad`), `<= 7.5 rad/s^2` / `3500 rad/s^3` on J1–J2 (`9.5` / `4500` on J3–J7), `>= 0.030 m` inter-arm clearance, and `z_table_m` tabletop floor. |
|
| 14 |
+
| **R6** | Pre-flight cameras & free-air `tau_ext` | Verify all 4 canonical RGB streams (`age <= 0.30 s`, non-frozen digests) and free-air `tau_ext <= 6.5 N` (`tau_ext_hat_filtered <= 4.5 Nm`) before motion. Joint torque sensors under-read downward (`-Z`) contact by `~2.8x`: cap `tau_ext <= 9.0 N` (probing) and `<= 18.0 N` (manipulation). |
|
| 15 |
+
| **R7** | Record video of every motion | Record continuous 4-camera MP4 + telemetry from before leaving `rest_pose` until returning cleanly to `rest_pose`. |
|
| 16 |
+
| **R8** | Forward kinematics (`fr3_kinematics.py`) | Verify `fk_pos_error_m <= 5.0 mm` (`0.005 m`) between `fr3_kinematics.compute_arm_pinch_from_flange` and Desk `O_T_EE` (`F_T_EE`-compensated) before motion. |
|
| 17 |
+
| **R9** | Honest grasp & contact verification | Never bypass tactile checks with geometry shortcuts (like `or tcp_dz <= ...`) or infer grasps from width alone; verify jaw travel shortfall (`gOBJ == 2`, `position_ratio < 0.92`) corroborated by load delta or multi-view vision. |
|
| 18 |
+
| **R10** | Re-verify after drift or bumps | Re-run `--step preflight` (`discover_hardware.py`) and camera checks if arms, cameras, or tabletop shift. |
|
| 19 |
+
| **R11** | Persistent `tmux` session `robot` | Run interactive hardware CLIs and camera/control scripts inside `tmux` session `robot` so the operator can monitor telemetry and issue `q` + `Enter` aborts. |
|
| 20 |
+
| **R12** | Keep `NOTES.md` & `robot_config.json` current | Read `NOTES.md` before each session and update `NOTES.md` and `config/robot_config.json` after calibration or hardware changes. |
|
| 21 |
+
| **R13** | Clean single-purpose scripts | Write self-checking scripts with `--dry-run` and JSON config; keep `--dry-run` tests green before hardware runs. |
|
| 22 |
+
| **R14** | 6-field stage report | Report `Result`, `Evidence`, `Numbers measured`, `Done-when checks`, `Concerns`, and `Need from you` after bring-up or task runs. |
|
| 23 |
+
| **R15** | Auto-advance non-motion stages | Auto-advance across software, `--dry-run`, and read-only checks; pause only for physical human actions or `R1` live-motion `"go"`. |
|
| 24 |
+
| **R16** | Human safety & E-stop first | Keep the physical E-stop within immediate operator reach and ensure actuators are idle before any human touches the arms, cables, or workspace. |
|
| 25 |
+
|
| 26 |
+
---
|
| 27 |
+
|
| 28 |
+
## 1. Pre-Flight & Franka Desk Configuration (`R1`, `R2`, `R6`, `R8`)
|
| 29 |
+
|
| 30 |
+
* **Tilted Duo Gravity & EE Payload in Franka Desk (`R1`, `R6`):** On angled Duo pedestals, each arm's `link0` `+Z` axis is tilted away from world vertical. If Franka Desk is left at default upright `(0, 0, -9.81)` gravity or `0 kg` end-effector mass (ignoring the `~0.95 kg` Robotiq 2F-85 + coupling + wrist RealSense), gravity compensation is wrong before motion starts—causing `> 15 N` free-air `tau_ext` bias and sudden downward droop when FCI engages. `fr3_arm_controller.audit_arm_desk_config` and `discover_hardware.run_discovery` verify `fk_pos_error_m <= 5.0 mm` (`R8`) and free-air `tau_ext <= 6.5 N` (`R6`).
|
| 31 |
+
* **Structural `--dry-run` Interlock (`R2`):** Passing `--dry-run` (or `--read-only`) runs offline MuJoCo trajectory & FK collision previews via `fr3_safety.Fr3DuoSafetyChecker` without connecting to hardware/grippers, structurally preventing physical actuation.
|
| 32 |
+
* **4-Camera Freshness & Non-Frozen Digest (`R6`):** Cached or USB-stalled camera buffers can report advancing host timestamps while delivering identical pixels. `fr3_camera_controller.Fr3DuoCameraController.check_freshness` verifies both frame age (`<= 0.30 s`) and pixel variation across repeated reads.
|
| 33 |
+
|
| 34 |
+
## 2. 1 kHz FCI Streaming, Smooth $C^2$ Trajectories & Safe Abort (`R3`, `R4`, `R5`)
|
| 35 |
+
|
| 36 |
+
* **Never Drop an Active 1 kHz FCI Loop Mid-Motion (`R4`):** Abruptly closing a `pylibfranka` control session while joint velocity or acceleration is nonzero triggers an immediate `communication_constraints_violation` / mechanical brake reflex, jarring gears and risking dropped payloads. Every trajectory uses $C^2$-continuous quintic polynomials (`v = 0, a = 0` at start and end) via `fr3_safety.generate_quintic_trajectory` and finishes with `MotionFinished` only after decelerating to rest.
|
| 37 |
+
* **Process Isolation & Real-Time Scaling (`R5`):**
|
| 38 |
+
* **1 kHz loop isolation:** Each arm's FCI loop runs in an isolated `ArmWorkerProcess` (`fr3_arm_controller.py`) with Python GC paused during motion so GIL/GC pauses never miss the 1 ms deadline.
|
| 39 |
+
* **Speed tiers:**
|
| 40 |
+
* Non-`PREEMPT_RT` (`--realtime auto` -> `RealtimeConfig.kIgnore`): `<= 15 deg/s` bring-up default (tunable via `max_joint_speed_deg_s` up to `45 deg/s` in `config/robot_config.json`).
|
| 41 |
+
* `PREEMPT_RT` (`--realtime auto` -> `RealtimeConfig.kEnforce`): `<= 30 deg/s` bring-up cap.
|
| 42 |
+
* Explicit `--realtime enforce`: unlocks up to `<= 45 deg/s`.
|
| 43 |
+
* **Reverse Path Unwind Without Mid-Air Release (`R3`):** When `fr3_safety.AbortWatcher` catches `q` + `Enter` or `SIGINT`, the active trajectory decelerates smoothly (`C^2` stop) and unwinds backwards along `travelled_waypoints` to `rest_pose` while **preserving the current Robotiq gripper command**.
|
| 44 |
+
* **Workspace Floor & Bimanual Clearance (`R5`):** Fit a 2D tilted tabletop plane `z_at_xy(x, y)` when table pitch is nonzero, clamp `fr3_joint4` with a `0.100 rad` margin (`[-2.9421, -0.2518] rad`), cap J1–J2 acceleration at `<= 7.5 rad/s^2`, and maintain `>= 0.030 m` inter-arm clearance (`RobotArmPlanner.add_other_arm_to_scene` + `Fr3DuoSafetyChecker`).
|
| 45 |
+
|
| 46 |
+
## 3. External Force/Torque (`tau_ext`) Estimation Without a Wrist FT Sensor (`R6`, `R9`)
|
| 47 |
+
|
| 48 |
+
* **Coupled `6x7` Spatial Jacobian SVD:** Because standard FR3 Duo cells have no wrist FT-300 force-torque sensor, external 6D wrenches in `base` frame (`+w_env_on_robot`) are estimated from joint torque residuals (`tau_ext`) via `mj_rne` (`qvel = 0`) and a coupled `6x7` spatial Jacobian SVD (`s_floor = 0.05`) in `fr3_kinematics.estimate_external_wrench_base`—never split `3x3` blocks, which leak wrist moments into phantom linear forces.
|
| 49 |
+
* **Vertical `-Z` `~2.8x` Under-Read Warning (`R6`):** Arm-Jacobian `tau_ext` under-reads vertical downward (`-Z`) tip contact relative to physical table force by roughly `2.8x` (`~13.7 N` `tau_ext` corresponds to `~38.4 N` physical force), with `3-4 N` free-air posture drift. Set guarded tabletop contact thresholds `>= 4.5 N` after local free-air tare, enforce `tau_ext` ceilings of **`<= 9.0 N` (~25 N physical) during tabletop probing** and **`<= 18.0 N` (~50 N physical) during manipulation**, and hit the E-stop immediately on visible wrist bowing or pad deflection.
|
| 50 |
+
* **Honest Grasp & Contact Verification (`R9`):** Never bypass tactile contact checks with geometry shortcuts (like `or tcp_dz <= ...`), and never verify Robotiq grasps from width alone (`empty` closure stalls at `0.82-0.91` with `~26 N` internal pad force). Confirm nonzero jaw travel plus `gOBJ == 2` stall shortfall (`< 0.92`) corroborated by load delta or multi-view camera checks.
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/bringup.py
ADDED
|
@@ -0,0 +1,1209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# Copyright 2026 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
# /// script
|
| 17 |
+
# requires-python = ">=3.9,<3.13"
|
| 18 |
+
# dependencies = [
|
| 19 |
+
# "mujoco",
|
| 20 |
+
# "numpy",
|
| 21 |
+
# "opencv-python",
|
| 22 |
+
# "pylibfranka; sys_platform == 'linux' and platform_machine == 'x86_64'",
|
| 23 |
+
# "pyserial",
|
| 24 |
+
# ]
|
| 25 |
+
# ///
|
| 26 |
+
|
| 27 |
+
"""Interactive terminal bring-up CLI runner for Franka Research 3 Duo."""
|
| 28 |
+
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import argparse
|
| 32 |
+
from collections.abc import Callable, Mapping, Sequence
|
| 33 |
+
from datetime import datetime, timezone
|
| 34 |
+
import importlib
|
| 35 |
+
import json
|
| 36 |
+
import math
|
| 37 |
+
import os
|
| 38 |
+
from pathlib import Path
|
| 39 |
+
import sys
|
| 40 |
+
import tempfile
|
| 41 |
+
from typing import Any
|
| 42 |
+
|
| 43 |
+
import check_cameras
|
| 44 |
+
import check_robot
|
| 45 |
+
import discover_hardware
|
| 46 |
+
from fr3_config import (
|
| 47 |
+
DEFAULT_CONFIG_PATH,
|
| 48 |
+
RobotConfig,
|
| 49 |
+
load_robot_config,
|
| 50 |
+
normalize_robot_config,
|
| 51 |
+
resolve_stage_output_dir,
|
| 52 |
+
save_robot_config,
|
| 53 |
+
validate_robot_config_complete,
|
| 54 |
+
)
|
| 55 |
+
from fr3_mjcf import (
|
| 56 |
+
build_fr3_duo_mjcf,
|
| 57 |
+
find_menagerie_dir,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
STAGE_ORDER: tuple[str, ...] = (
|
| 61 |
+
"env",
|
| 62 |
+
"preflight",
|
| 63 |
+
"geometry",
|
| 64 |
+
"cameras",
|
| 65 |
+
"gripper",
|
| 66 |
+
"nudge",
|
| 67 |
+
"abort-test",
|
| 68 |
+
"hello-world",
|
| 69 |
+
"all",
|
| 70 |
+
)
|
| 71 |
+
STEP_CHOICES: tuple[str, ...] = (
|
| 72 |
+
"env",
|
| 73 |
+
"preflight",
|
| 74 |
+
"geometry",
|
| 75 |
+
"cameras",
|
| 76 |
+
"gripper",
|
| 77 |
+
"nudge",
|
| 78 |
+
"abort-test",
|
| 79 |
+
"hello-world",
|
| 80 |
+
"home",
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
_GEOMETRY_CLI_ALLOW_ZERO: dict[str, bool] = {
|
| 84 |
+
"base_height_m": False,
|
| 85 |
+
"table_height_m": True,
|
| 86 |
+
"table_front_offset_m": True,
|
| 87 |
+
"table_width_m": False,
|
| 88 |
+
"table_depth_m": False,
|
| 89 |
+
"tcp_offset_z_m": False,
|
| 90 |
+
}
|
| 91 |
+
_COMPLETE_CONFIG_REQUIRED_STEPS: frozenset[str] = frozenset({
|
| 92 |
+
"gripper",
|
| 93 |
+
"nudge",
|
| 94 |
+
"abort-test",
|
| 95 |
+
"hello-world",
|
| 96 |
+
})
|
| 97 |
+
|
| 98 |
+
_ACTUATION_DESCRIPTIONS: dict[str, str] = {
|
| 99 |
+
"gripper": (
|
| 100 |
+
"Step 3a: Robotiq 2F-85 Gripper Activation & Cycling"
|
| 101 |
+
" (open -> close -> open)"
|
| 102 |
+
),
|
| 103 |
+
"nudge": (
|
| 104 |
+
"Step 3b: Single-Joint J1 Nudge (5 deg slow stroke on left & right"
|
| 105 |
+
" arms)"
|
| 106 |
+
),
|
| 107 |
+
"abort-test": (
|
| 108 |
+
"Step 3c: Abort-and-Unwind Test (10 deg stroke interrupted to test"
|
| 109 |
+
" Hermite C^2 stop & rewind)"
|
| 110 |
+
),
|
| 111 |
+
"hello-world": (
|
| 112 |
+
"Step 4: Bimanual Hello World (synchronized wave + gripper cycle +"
|
| 113 |
+
" 4-camera video)"
|
| 114 |
+
),
|
| 115 |
+
"home": "Step 4h: Smooth Bimanual Homing to Canonical Rest Pose",
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
| 120 |
+
"""Parses command-line arguments for the FR3 Duo bring-up runner."""
|
| 121 |
+
parser = argparse.ArgumentParser(
|
| 122 |
+
description=(
|
| 123 |
+
"Interactive terminal bring-up runner for Franka Research 3 Duo"
|
| 124 |
+
" across Stages 0-4 (env check, preflight discovery, geometry"
|
| 125 |
+
" calibration, camera verification, staged actuation, and homing)."
|
| 126 |
+
)
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--config",
|
| 130 |
+
type=Path,
|
| 131 |
+
default=Path(DEFAULT_CONFIG_PATH),
|
| 132 |
+
help="Path to robot configuration JSON.",
|
| 133 |
+
)
|
| 134 |
+
parser.add_argument(
|
| 135 |
+
"--no-write-config",
|
| 136 |
+
action="store_true",
|
| 137 |
+
help="If set, runs preflight without saving robot_config.json.",
|
| 138 |
+
)
|
| 139 |
+
parser.add_argument(
|
| 140 |
+
"--read-only",
|
| 141 |
+
action="store_true",
|
| 142 |
+
help=(
|
| 143 |
+
"Run in read-only mode without writing config or commanding"
|
| 144 |
+
" physical actuation."
|
| 145 |
+
),
|
| 146 |
+
)
|
| 147 |
+
parser.add_argument(
|
| 148 |
+
"--left-ip", type=str, default=None, help="Left arm FCI IP."
|
| 149 |
+
)
|
| 150 |
+
parser.add_argument(
|
| 151 |
+
"--right-ip", type=str, default=None, help="Right arm FCI IP."
|
| 152 |
+
)
|
| 153 |
+
parser.add_argument(
|
| 154 |
+
"--base-height-m",
|
| 155 |
+
type=float,
|
| 156 |
+
default=None,
|
| 157 |
+
help="Floor to flat center bracket underside height in meters.",
|
| 158 |
+
)
|
| 159 |
+
parser.add_argument(
|
| 160 |
+
"--table-height-m",
|
| 161 |
+
type=float,
|
| 162 |
+
default=None,
|
| 163 |
+
help="Floor to tabletop height in meters.",
|
| 164 |
+
)
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--table-front-offset-m",
|
| 167 |
+
type=float,
|
| 168 |
+
default=None,
|
| 169 |
+
help=(
|
| 170 |
+
"Horizontal gap from bracket underside front lip to table front [m]."
|
| 171 |
+
),
|
| 172 |
+
)
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"--table-width-m",
|
| 175 |
+
type=float,
|
| 176 |
+
default=None,
|
| 177 |
+
help="Tabletop width along Y in meters.",
|
| 178 |
+
)
|
| 179 |
+
parser.add_argument(
|
| 180 |
+
"--table-depth-m",
|
| 181 |
+
type=float,
|
| 182 |
+
default=None,
|
| 183 |
+
help="Tabletop depth along X in meters.",
|
| 184 |
+
)
|
| 185 |
+
parser.add_argument(
|
| 186 |
+
"--tcp-offset-z-m",
|
| 187 |
+
type=float,
|
| 188 |
+
default=None,
|
| 189 |
+
help="Robotiq fingertip Z offset from flange in meters (0.145 or 0.185).",
|
| 190 |
+
)
|
| 191 |
+
parser.add_argument(
|
| 192 |
+
"--confirm-geometry",
|
| 193 |
+
action="store_true",
|
| 194 |
+
help="Mark physical cell geometry & fingertip measurements confirmed.",
|
| 195 |
+
)
|
| 196 |
+
parser.add_argument(
|
| 197 |
+
"--output-dir",
|
| 198 |
+
type=Path,
|
| 199 |
+
default=None,
|
| 200 |
+
help="Base directory for bring-up step outputs and summary JSON.",
|
| 201 |
+
)
|
| 202 |
+
parser.add_argument(
|
| 203 |
+
"--dry-run",
|
| 204 |
+
action="store_true",
|
| 205 |
+
help=(
|
| 206 |
+
"Verify MJCF kinematics and trajectory limits without opening live"
|
| 207 |
+
" hardware or commanding motion."
|
| 208 |
+
),
|
| 209 |
+
)
|
| 210 |
+
parser.add_argument(
|
| 211 |
+
"--realtime",
|
| 212 |
+
choices=("auto", "enforce", "ignore"),
|
| 213 |
+
default="auto",
|
| 214 |
+
help="FCI realtime scheduling policy.",
|
| 215 |
+
)
|
| 216 |
+
target_group = parser.add_mutually_exclusive_group()
|
| 217 |
+
target_group.add_argument(
|
| 218 |
+
"--up-to",
|
| 219 |
+
choices=STAGE_ORDER,
|
| 220 |
+
default="all",
|
| 221 |
+
help="Run progressively up to and including this stage.",
|
| 222 |
+
)
|
| 223 |
+
target_group.add_argument(
|
| 224 |
+
"--step",
|
| 225 |
+
choices=STEP_CHOICES,
|
| 226 |
+
default=None,
|
| 227 |
+
help="Run only this single bring-up step (or 'home').",
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--yes",
|
| 231 |
+
"-y",
|
| 232 |
+
action="store_true",
|
| 233 |
+
help="Auto-confirm interactive actuation prompts without prompting.",
|
| 234 |
+
)
|
| 235 |
+
return parser.parse_args(argv)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def _write_summary(out_dir: Path, summary: dict[str, Any]) -> None:
|
| 239 |
+
try:
|
| 240 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 241 |
+
summary_path = out_dir / "bringup_summary.json"
|
| 242 |
+
summary_path.write_text(
|
| 243 |
+
json.dumps(summary, indent=2) + "\n", encoding="utf-8"
|
| 244 |
+
)
|
| 245 |
+
except OSError as exc:
|
| 246 |
+
print(
|
| 247 |
+
f"Warning: Failed to write bringup_summary.json: {exc}",
|
| 248 |
+
file=sys.stderr,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _call_stage(
|
| 253 |
+
fn: Callable[..., tuple[int, dict[str, Any]]], *args: Any, **kwargs: Any
|
| 254 |
+
) -> tuple[int, dict[str, Any], str | None]:
|
| 255 |
+
"""Calls a stage `run_*` function and traps unexpected runtime errors."""
|
| 256 |
+
try:
|
| 257 |
+
rc, report = fn(*args, **kwargs)
|
| 258 |
+
return int(rc), report, None
|
| 259 |
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
| 260 |
+
err_msg = f"{type(exc).__name__}: {exc}"
|
| 261 |
+
print(f" ERROR: {err_msg}", file=sys.stderr)
|
| 262 |
+
return 1, {}, err_msg
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _fmt_opt(val: Any) -> Any:
|
| 266 |
+
return "N/A" if val is None else val
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _fail_step(
|
| 270 |
+
out_dir: Path,
|
| 271 |
+
summary: dict[str, Any],
|
| 272 |
+
step_key: str,
|
| 273 |
+
rc: int,
|
| 274 |
+
error: str | None = None,
|
| 275 |
+
) -> int:
|
| 276 |
+
summary["status"] = "failed"
|
| 277 |
+
info: dict[str, Any] = {"status": "failed", "exit_code": rc}
|
| 278 |
+
if error:
|
| 279 |
+
info["error"] = error
|
| 280 |
+
summary["steps"][step_key] = info
|
| 281 |
+
_write_summary(out_dir, summary)
|
| 282 |
+
return rc
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def _resolve_steps_to_run(args: argparse.Namespace) -> list[str]:
|
| 286 |
+
if args.step is not None:
|
| 287 |
+
return [str(args.step)]
|
| 288 |
+
up_to = str(args.up_to or "all")
|
| 289 |
+
progressive = (
|
| 290 |
+
"env",
|
| 291 |
+
"preflight",
|
| 292 |
+
"geometry",
|
| 293 |
+
"cameras",
|
| 294 |
+
"gripper",
|
| 295 |
+
"nudge",
|
| 296 |
+
"abort-test",
|
| 297 |
+
"hello-world",
|
| 298 |
+
)
|
| 299 |
+
if up_to == "all":
|
| 300 |
+
return list(progressive)
|
| 301 |
+
idx = progressive.index(up_to)
|
| 302 |
+
return list(progressive[: idx + 1])
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _run_env_step(
|
| 306 |
+
cfg: RobotConfig,
|
| 307 |
+
out_dir: Path,
|
| 308 |
+
summary: dict[str, Any],
|
| 309 |
+
*,
|
| 310 |
+
is_hw: bool,
|
| 311 |
+
mode_label: str,
|
| 312 |
+
) -> int:
|
| 313 |
+
"""Executes Step 0 module, MJCF, and dry-run trajectory pre-checks."""
|
| 314 |
+
print("\n--- Step 0: Environment & Pre-Check ---")
|
| 315 |
+
optional_notes = {
|
| 316 |
+
"serial": "pyserial hardware driver; only required for live hardware",
|
| 317 |
+
"pylibfranka": "Franka FCI binding; only required for live hardware",
|
| 318 |
+
}
|
| 319 |
+
missing_required: list[str] = []
|
| 320 |
+
for mod_name, is_req in (
|
| 321 |
+
("numpy", True),
|
| 322 |
+
("mujoco", True),
|
| 323 |
+
("cv2", True),
|
| 324 |
+
("serial", is_hw),
|
| 325 |
+
("pylibfranka", is_hw),
|
| 326 |
+
):
|
| 327 |
+
try:
|
| 328 |
+
mod = importlib.import_module(mod_name)
|
| 329 |
+
ver = getattr(mod, "__version__", "")
|
| 330 |
+
print(
|
| 331 |
+
f" [PASS] Python module '{mod_name}'" + (f" ({ver})" if ver else "")
|
| 332 |
+
)
|
| 333 |
+
except ImportError:
|
| 334 |
+
if is_req:
|
| 335 |
+
print(
|
| 336 |
+
f" [FAIL] Python module '{mod_name}' missing (required for"
|
| 337 |
+
f" mode={mode_label})"
|
| 338 |
+
)
|
| 339 |
+
missing_required.append(mod_name)
|
| 340 |
+
else:
|
| 341 |
+
print(
|
| 342 |
+
f" [WARN] Python module '{mod_name}' missing"
|
| 343 |
+
f" ({optional_notes.get(mod_name, 'optional dependency')})"
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
menagerie_path = find_menagerie_dir()
|
| 347 |
+
if missing_required:
|
| 348 |
+
print(
|
| 349 |
+
f"\n[FAIL] Step 0 environment check failed: missing {missing_required}",
|
| 350 |
+
file=sys.stderr,
|
| 351 |
+
)
|
| 352 |
+
summary["status"] = "failed"
|
| 353 |
+
summary["steps"]["env"] = {
|
| 354 |
+
"status": "failed",
|
| 355 |
+
"missing_modules": missing_required,
|
| 356 |
+
}
|
| 357 |
+
_write_summary(out_dir, summary)
|
| 358 |
+
return 1
|
| 359 |
+
|
| 360 |
+
step0_dir = out_dir / "step0_precheck"
|
| 361 |
+
step0_dir.mkdir(parents=True, exist_ok=True)
|
| 362 |
+
mjcf_err: str | None = None
|
| 363 |
+
try:
|
| 364 |
+
build_fr3_duo_mjcf(cfg)
|
| 365 |
+
if menagerie_path is None:
|
| 366 |
+
menagerie_path = find_menagerie_dir()
|
| 367 |
+
if menagerie_path is not None:
|
| 368 |
+
print(f" [PASS] Canonical Duo MJCF ready (Menagerie: {menagerie_path})")
|
| 369 |
+
else:
|
| 370 |
+
print(" [PASS] Canonical Duo MJCF ready (Menagerie)")
|
| 371 |
+
except (RuntimeError, OSError, ValueError) as exc:
|
| 372 |
+
mjcf_err = f"{type(exc).__name__}: {exc}"
|
| 373 |
+
print(f" ERROR: MJCF compile check failed: {mjcf_err}", file=sys.stderr)
|
| 374 |
+
|
| 375 |
+
dry_check_rc, _, dry_check_err = _call_stage(
|
| 376 |
+
check_robot.run_robot_check,
|
| 377 |
+
cfg,
|
| 378 |
+
mode="nudge",
|
| 379 |
+
dry_run=True,
|
| 380 |
+
output_dir=step0_dir,
|
| 381 |
+
output_json=step0_dir / "dry_run_check.json",
|
| 382 |
+
)
|
| 383 |
+
if mjcf_err is not None or dry_check_rc != 0:
|
| 384 |
+
print(
|
| 385 |
+
"\n[FAIL] Step 0 MuJoCo & trajectory pre-check failed.", file=sys.stderr
|
| 386 |
+
)
|
| 387 |
+
summary["status"] = "failed"
|
| 388 |
+
step0_info: dict[str, Any] = {
|
| 389 |
+
"status": "failed",
|
| 390 |
+
"mjcf_ok": mjcf_err is None,
|
| 391 |
+
"dry_check_rc": dry_check_rc,
|
| 392 |
+
}
|
| 393 |
+
if mjcf_err or dry_check_err:
|
| 394 |
+
step0_info["error"] = mjcf_err or dry_check_err
|
| 395 |
+
summary["steps"]["env"] = step0_info
|
| 396 |
+
_write_summary(out_dir, summary)
|
| 397 |
+
return 1
|
| 398 |
+
|
| 399 |
+
print(
|
| 400 |
+
" [PASS] MuJoCo & dry-run pre-check succeeded"
|
| 401 |
+
" (kinematics & safety gates ok)"
|
| 402 |
+
)
|
| 403 |
+
summary["steps"]["env"] = {"status": "ok", "menagerie": bool(menagerie_path)}
|
| 404 |
+
return 0
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def _run_preflight_step(
|
| 408 |
+
cfg: RobotConfig,
|
| 409 |
+
args: argparse.Namespace,
|
| 410 |
+
out_dir: Path,
|
| 411 |
+
summary: dict[str, Any],
|
| 412 |
+
*,
|
| 413 |
+
effective_dry_run: bool,
|
| 414 |
+
is_read_only: bool,
|
| 415 |
+
) -> tuple[int, RobotConfig]:
|
| 416 |
+
"""Runs Step 1 read-only hardware discovery and updates `cfg` if saved."""
|
| 417 |
+
print("\n--- Step 1: Hardware Discovery & Preflight Audit ---")
|
| 418 |
+
step1_dir = out_dir / "step1_preflight"
|
| 419 |
+
step1_dir.mkdir(parents=True, exist_ok=True)
|
| 420 |
+
s1_json = step1_dir / "discovery_report.json"
|
| 421 |
+
write_cfg_in_place = bool(
|
| 422 |
+
not effective_dry_run and not args.no_write_config and not is_read_only
|
| 423 |
+
)
|
| 424 |
+
rc1, d_rep, err1 = _call_stage(
|
| 425 |
+
discover_hardware.run_discovery,
|
| 426 |
+
cfg,
|
| 427 |
+
realtime=args.realtime,
|
| 428 |
+
output_dir=step1_dir,
|
| 429 |
+
output_json=s1_json,
|
| 430 |
+
write_config=args.config if write_cfg_in_place else None,
|
| 431 |
+
read_only=not (write_cfg_in_place and args.config is not None),
|
| 432 |
+
strict_preflight=not (effective_dry_run or is_read_only),
|
| 433 |
+
yes=args.yes,
|
| 434 |
+
)
|
| 435 |
+
if rc1 != 0:
|
| 436 |
+
print(
|
| 437 |
+
f"\n[FAIL] Step 1 preflight blocked (exit code {rc1}) — fix warnings"
|
| 438 |
+
" above before continuing.",
|
| 439 |
+
file=sys.stderr,
|
| 440 |
+
)
|
| 441 |
+
return _fail_step(out_dir, summary, "preflight", rc1, err1), cfg
|
| 442 |
+
|
| 443 |
+
if write_cfg_in_place and args.config is not None and args.config.is_file():
|
| 444 |
+
cfg = load_robot_config(args.config)
|
| 445 |
+
elif d_rep and isinstance(d_rep.get("discovered_config"), Mapping):
|
| 446 |
+
cfg = normalize_robot_config(d_rep["discovered_config"])
|
| 447 |
+
elif d_rep:
|
| 448 |
+
grip_sel = d_rep.get("gripper_selection") or {}
|
| 449 |
+
for side in ("left", "right"):
|
| 450 |
+
if not cfg.arms[side].gripper_port and grip_sel.get(side):
|
| 451 |
+
cfg.arms[side].gripper_port = str(grip_sel[side])
|
| 452 |
+
uvc_devs = d_rep.get("uvc_devices") or []
|
| 453 |
+
if uvc_devs:
|
| 454 |
+
discover_hardware._auto_bind_devices(cfg, grip_sel, list(uvc_devs))
|
| 455 |
+
if args.left_ip:
|
| 456 |
+
cfg.arms.left.ip = str(args.left_ip)
|
| 457 |
+
if args.right_ip:
|
| 458 |
+
cfg.arms.right.ip = str(args.right_ip)
|
| 459 |
+
|
| 460 |
+
if d_rep:
|
| 461 |
+
if d_rep.get("report_path"):
|
| 462 |
+
summary["artifacts"]["discovery_report"] = d_rep["report_path"]
|
| 463 |
+
elif s1_json.is_file():
|
| 464 |
+
summary["artifacts"]["discovery_report"] = str(s1_json)
|
| 465 |
+
rt_cfg = (d_rep.get("realtime_profile") or {}).get(
|
| 466 |
+
"realtime_config", "unknown"
|
| 467 |
+
)
|
| 468 |
+
is_rt = d_rep.get("preempt_rt_detected", False)
|
| 469 |
+
print(f" Realtime Profile: {rt_cfg} (PREEMPT_RT={is_rt})")
|
| 470 |
+
arm_ro = d_rep.get("arm_readout") or {}
|
| 471 |
+
fci_targets = d_rep.get("fci_targets") or {}
|
| 472 |
+
for arm in ("left", "right"):
|
| 473 |
+
rd = arm_ro.get(arm, {})
|
| 474 |
+
da = rd.get("desk_audit") or {}
|
| 475 |
+
reach = (fci_targets.get(arm) or {}).get("tcp_1337_reachable")
|
| 476 |
+
fk_err_mm = float(rd.get("fk_pos_error_m", 0.0)) * 1000.0
|
| 477 |
+
f_norm = float(rd.get("free_air_force_norm_n", 0.0))
|
| 478 |
+
print(
|
| 479 |
+
f" {arm.capitalize()} Arm: tcp_1337={reach} |"
|
| 480 |
+
f" mode={_fmt_opt(da.get('robot_mode'))} |"
|
| 481 |
+
f" m_total={_fmt_opt(da.get('m_total_kg'))} kg |"
|
| 482 |
+
f" grav_err={_fmt_opt(da.get('gravity_angle_err_deg'))} deg |"
|
| 483 |
+
f" fk_err={fk_err_mm:.2f} mm | free_air={f_norm:.2f} N"
|
| 484 |
+
)
|
| 485 |
+
grippers = d_rep.get("gripper_selection") or {}
|
| 486 |
+
print(
|
| 487 |
+
f" Robotiq Grippers: left={grippers.get('left')} |"
|
| 488 |
+
f" right={grippers.get('right')}"
|
| 489 |
+
)
|
| 490 |
+
print(
|
| 491 |
+
f" UVC Cameras: {len(d_rep.get('uvc_devices') or [])} device(s) found"
|
| 492 |
+
)
|
| 493 |
+
notes = [
|
| 494 |
+
*list(d_rep.get("warnings") or []),
|
| 495 |
+
*list(d_rep.get("advisories") or []),
|
| 496 |
+
]
|
| 497 |
+
if notes:
|
| 498 |
+
print(f" Advisories/Warnings ({len(notes)}):")
|
| 499 |
+
for note in notes:
|
| 500 |
+
print(f" - {note}")
|
| 501 |
+
|
| 502 |
+
summary["steps"]["preflight"] = {"status": "ok", "exit_code": 0}
|
| 503 |
+
return 0, cfg
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
_GEOMETRY_PROMPTS: tuple[tuple[str, str, bool], ...] = (
|
| 507 |
+
(
|
| 508 |
+
"base_height_m",
|
| 509 |
+
" 1) base_height_m (floor -> flat center bracket underside) [m]"
|
| 510 |
+
" (default {val:.4f}): ",
|
| 511 |
+
False,
|
| 512 |
+
),
|
| 513 |
+
(
|
| 514 |
+
"table_height_m",
|
| 515 |
+
" 2) table_height_m (floor -> tabletop, ALOHA 0.750) [m]"
|
| 516 |
+
" (default {val:.3f}): ",
|
| 517 |
+
True,
|
| 518 |
+
),
|
| 519 |
+
(
|
| 520 |
+
"table_front_offset_m",
|
| 521 |
+
" 3) table_front_offset_m (bracket front lip -> table front edge)"
|
| 522 |
+
" [m] (default {val:.3f}): ",
|
| 523 |
+
True,
|
| 524 |
+
),
|
| 525 |
+
(
|
| 526 |
+
"table_width_m",
|
| 527 |
+
" 4a) table_width_m (ALOHA 1.220) [m] (default {val:.3f}): ",
|
| 528 |
+
False,
|
| 529 |
+
),
|
| 530 |
+
(
|
| 531 |
+
"table_depth_m",
|
| 532 |
+
" 4b) table_depth_m (ALOHA 0.740) [m] (default {val:.3f}): ",
|
| 533 |
+
False,
|
| 534 |
+
),
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def _geometry_reference_image_path() -> Path:
|
| 539 |
+
"""Resolves `assets/fr3_duo_dimensions_reference.png` relative to skill."""
|
| 540 |
+
rel = Path("assets") / "fr3_duo_dimensions_reference.png"
|
| 541 |
+
for base in (os.path.abspath(__file__), Path(__file__).resolve()):
|
| 542 |
+
candidate = Path(base).parents[1] / rel
|
| 543 |
+
if candidate.is_file():
|
| 544 |
+
return candidate
|
| 545 |
+
return Path(__file__).resolve().parents[1] / rel
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def _validate_geom_value(
|
| 549 |
+
name: str, val: float, *, allow_zero: bool = False
|
| 550 |
+
) -> float:
|
| 551 |
+
if not math.isfinite(val):
|
| 552 |
+
raise ValueError(f"{name} must be finite, got {val!r}")
|
| 553 |
+
if (allow_zero and val < 0.0) or (not allow_zero and val <= 0.0):
|
| 554 |
+
op = ">=" if allow_zero else ">"
|
| 555 |
+
raise ValueError(f"{name} must be {op} 0, got {val!r}")
|
| 556 |
+
return float(val)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def _extract_geometry_cli_updates(
|
| 560 |
+
args: argparse.Namespace,
|
| 561 |
+
) -> tuple[dict[str, float], str | None]:
|
| 562 |
+
"""Extracts and validates geometry CLI overrides from parsed `args`."""
|
| 563 |
+
updates: dict[str, float] = {}
|
| 564 |
+
for field_name, allow_zero in _GEOMETRY_CLI_ALLOW_ZERO.items():
|
| 565 |
+
raw_val = getattr(args, field_name, None)
|
| 566 |
+
if raw_val is None:
|
| 567 |
+
continue
|
| 568 |
+
try:
|
| 569 |
+
updates[field_name] = _validate_geom_value(
|
| 570 |
+
field_name, float(raw_val), allow_zero=allow_zero
|
| 571 |
+
)
|
| 572 |
+
except ValueError as exc:
|
| 573 |
+
return {}, str(exc)
|
| 574 |
+
return updates, None
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def _print_geometry_summary(cfg: RobotConfig, ref_img: Path) -> None:
|
| 578 |
+
"""Prints current physical geometry, derived `z_table_m`, and table box."""
|
| 579 |
+
table_center, table_half_extents = cfg.table_box_bounds()
|
| 580 |
+
print(f" Reference diagram : {ref_img}")
|
| 581 |
+
print(
|
| 582 |
+
f" base_height_m : {cfg.base_height_m:.6f} m"
|
| 583 |
+
" (floor -> flat center bracket underside)"
|
| 584 |
+
)
|
| 585 |
+
print(f" table_height_m : {cfg.table_height_m:.6f} m (floor -> tabletop)")
|
| 586 |
+
print(
|
| 587 |
+
f" table_front_offset: {cfg.table_front_offset_m:.4f} m"
|
| 588 |
+
" (bracket underside front lip -> table front edge)"
|
| 589 |
+
)
|
| 590 |
+
print(
|
| 591 |
+
f" table_width/depth : {cfg.table_width_m:.3f} m x"
|
| 592 |
+
f" {cfg.table_depth_m:.3f} m"
|
| 593 |
+
)
|
| 594 |
+
print(f" tcp_offset_z_m : {cfg.tcp_offset_z_m:.3f} m")
|
| 595 |
+
print(f" Derived z_table_m : {cfg.z_table_m:+.6f} m")
|
| 596 |
+
print(
|
| 597 |
+
f" Table box bounds : center={table_center},"
|
| 598 |
+
f" half_extents={table_half_extents}"
|
| 599 |
+
)
|
| 600 |
+
print(f" geometry_confirmed: {bool(cfg.geometry_confirmed)}")
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def _prompt_geometry_calibration(
|
| 604 |
+
cfg: RobotConfig,
|
| 605 |
+
ref_img: Path,
|
| 606 |
+
input_fn: Callable[[str], str],
|
| 607 |
+
) -> tuple[str, RobotConfig, str | None]:
|
| 608 |
+
"""Interactively prompts for physical cell geometry & fingertip offset."""
|
| 609 |
+
print(
|
| 610 |
+
" Measure your floor-mounted setup per reference diagram:\n"
|
| 611 |
+
f" {ref_img}\n"
|
| 612 |
+
" Press ENTER to accept the default value in parentheses."
|
| 613 |
+
)
|
| 614 |
+
try:
|
| 615 |
+
updates: dict[str, Any] = {"geometry_confirmed": True}
|
| 616 |
+
for field_name, tmpl, allow_zero in _GEOMETRY_PROMPTS:
|
| 617 |
+
default_val = float(getattr(cfg, field_name))
|
| 618 |
+
raw = input_fn(tmpl.format(val=default_val)).strip()
|
| 619 |
+
updates[field_name] = (
|
| 620 |
+
_validate_geom_value(field_name, float(raw), allow_zero=allow_zero)
|
| 621 |
+
if raw
|
| 622 |
+
else default_val
|
| 623 |
+
)
|
| 624 |
+
tcp_raw = (
|
| 625 |
+
input_fn(
|
| 626 |
+
" 5) Fingertips: [1/stock] 2F-85 pads (0.145) | [2/extended]"
|
| 627 |
+
f" ALOHA (0.185) | float [m] (default {cfg.tcp_offset_z_m:.3f}): "
|
| 628 |
+
)
|
| 629 |
+
.strip()
|
| 630 |
+
.lower()
|
| 631 |
+
)
|
| 632 |
+
if not tcp_raw:
|
| 633 |
+
updates["tcp_offset_z_m"] = float(cfg.tcp_offset_z_m)
|
| 634 |
+
elif tcp_raw in ("1", "stock", "s", "pads", "2f85", "2f-85"):
|
| 635 |
+
updates["tcp_offset_z_m"] = 0.145
|
| 636 |
+
elif tcp_raw in ("2", "extended", "ext", "aloha"):
|
| 637 |
+
updates["tcp_offset_z_m"] = 0.185
|
| 638 |
+
else:
|
| 639 |
+
updates["tcp_offset_z_m"] = _validate_geom_value(
|
| 640 |
+
"tcp_offset_z_m", float(tcp_raw)
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
candidate = normalize_robot_config({**cfg.to_dict(), **updates})
|
| 644 |
+
table_center, table_half_extents = candidate.table_box_bounds()
|
| 645 |
+
print(f" -> Computed z_table_m : {candidate.z_table_m:+.6f} m")
|
| 646 |
+
print(
|
| 647 |
+
f" -> Table box bounds : center={table_center},"
|
| 648 |
+
f" half_extents={table_half_extents}"
|
| 649 |
+
)
|
| 650 |
+
print(f" -> tcp_offset_z_m : {candidate.tcp_offset_z_m:.3f} m")
|
| 651 |
+
confirm = (
|
| 652 |
+
input_fn(" Confirm geometry & fingertip measurements? [y/N]: ")
|
| 653 |
+
.strip()
|
| 654 |
+
.lower()
|
| 655 |
+
)
|
| 656 |
+
except (EOFError, KeyboardInterrupt):
|
| 657 |
+
return "stopped", cfg, "geometry_prompt_aborted"
|
| 658 |
+
except ValueError as exc:
|
| 659 |
+
return "invalid", cfg, str(exc)
|
| 660 |
+
|
| 661 |
+
if confirm in ("y", "yes"):
|
| 662 |
+
return "confirmed", candidate, None
|
| 663 |
+
return "stopped", cfg, "geometry_confirmation_declined"
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def _run_geometry_step(
|
| 667 |
+
cfg: RobotConfig,
|
| 668 |
+
args: argparse.Namespace,
|
| 669 |
+
out_dir: Path,
|
| 670 |
+
summary: dict[str, Any],
|
| 671 |
+
*,
|
| 672 |
+
effective_dry_run: bool,
|
| 673 |
+
is_read_only: bool,
|
| 674 |
+
input_fn: Callable[[str], str],
|
| 675 |
+
cli_updates: Mapping[str, float] | None = None,
|
| 676 |
+
) -> tuple[int, RobotConfig]:
|
| 677 |
+
"""Runs Step 1b physical cell geometry & fingertip calibration."""
|
| 678 |
+
print("\n--- Step 1b: Physical Cell Geometry & Fingertip Calibration ---")
|
| 679 |
+
ref_img = _geometry_reference_image_path()
|
| 680 |
+
if cli_updates is None:
|
| 681 |
+
updates, cli_err = _extract_geometry_cli_updates(args)
|
| 682 |
+
if cli_err is not None:
|
| 683 |
+
print(f"\n[FAIL] Invalid geometry CLI flag: {cli_err}", file=sys.stderr)
|
| 684 |
+
return _fail_step(out_dir, summary, "geometry", 2, cli_err), cfg
|
| 685 |
+
else:
|
| 686 |
+
updates = cli_updates
|
| 687 |
+
|
| 688 |
+
confirmed_via_cli = bool(args.confirm_geometry) or (
|
| 689 |
+
len(updates) == len(_GEOMETRY_CLI_ALLOW_ZERO)
|
| 690 |
+
)
|
| 691 |
+
write_cfg = (
|
| 692 |
+
not effective_dry_run and not args.no_write_config and not is_read_only
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
if updates or confirmed_via_cli:
|
| 696 |
+
cfg = normalize_robot_config({
|
| 697 |
+
**cfg.to_dict(),
|
| 698 |
+
**updates,
|
| 699 |
+
"geometry_confirmed": bool(cfg.geometry_confirmed) or confirmed_via_cli,
|
| 700 |
+
})
|
| 701 |
+
|
| 702 |
+
if (
|
| 703 |
+
confirmed_via_cli
|
| 704 |
+
or effective_dry_run
|
| 705 |
+
or (cfg.geometry_confirmed and args.step != "geometry")
|
| 706 |
+
or is_read_only
|
| 707 |
+
or args.no_write_config
|
| 708 |
+
or args.yes
|
| 709 |
+
or (input_fn is input and not sys.stdin.isatty())
|
| 710 |
+
):
|
| 711 |
+
_print_geometry_summary(cfg, ref_img)
|
| 712 |
+
step_entry: dict[str, Any] = {
|
| 713 |
+
"status": "ok",
|
| 714 |
+
"exit_code": 0,
|
| 715 |
+
"geometry_confirmed": bool(cfg.geometry_confirmed),
|
| 716 |
+
"z_table_m": cfg.z_table_m,
|
| 717 |
+
}
|
| 718 |
+
if (updates or confirmed_via_cli) and write_cfg and args.config is not None:
|
| 719 |
+
save_robot_config(cfg, args.config)
|
| 720 |
+
if cfg.geometry_confirmed:
|
| 721 |
+
print(f" Saved confirmed geometry to {args.config}")
|
| 722 |
+
else:
|
| 723 |
+
print(
|
| 724 |
+
f" Saved partial geometry updates (unconfirmed) to {args.config}"
|
| 725 |
+
)
|
| 726 |
+
elif effective_dry_run:
|
| 727 |
+
missing = validate_robot_config_complete(cfg)
|
| 728 |
+
print(
|
| 729 |
+
" Dry-run completeness preview missing:"
|
| 730 |
+
f" {missing or 'NONE (complete)'}"
|
| 731 |
+
)
|
| 732 |
+
if not confirmed_via_cli:
|
| 733 |
+
step_entry["missing_for_live"] = missing
|
| 734 |
+
elif cfg.geometry_confirmed:
|
| 735 |
+
print(" [PASS] Cell geometry & fingertip dimensions already confirmed.")
|
| 736 |
+
elif is_read_only or args.no_write_config:
|
| 737 |
+
print(
|
| 738 |
+
" [WARN] geometry_confirmed is False (skipping interactive prompt in"
|
| 739 |
+
" read-only/--no-write-config mode). Run '--step geometry' or pass"
|
| 740 |
+
" explicit measurement flags + '--confirm-geometry' before live"
|
| 741 |
+
" actuation."
|
| 742 |
+
)
|
| 743 |
+
step_entry["read_only"] = is_read_only
|
| 744 |
+
elif args.yes:
|
| 745 |
+
print(
|
| 746 |
+
" [WARN] geometry_confirmed is False; --yes will NOT auto-confirm"
|
| 747 |
+
" unverified default dimensions. Run '--step geometry' interactively"
|
| 748 |
+
" or pass explicit measurement flags + '--confirm-geometry'."
|
| 749 |
+
)
|
| 750 |
+
step_entry["warning"] = "geometry_unconfirmed_with_yes"
|
| 751 |
+
else:
|
| 752 |
+
print(
|
| 753 |
+
" [WARN] geometry_confirmed is False and stdin is not interactive."
|
| 754 |
+
" Run '--step geometry' in an interactive TTY or pass explicit"
|
| 755 |
+
" measurement flags + '--confirm-geometry'."
|
| 756 |
+
)
|
| 757 |
+
step_entry["warning"] = "geometry_unconfirmed_non_tty"
|
| 758 |
+
summary["steps"]["geometry"] = step_entry
|
| 759 |
+
return 0, cfg
|
| 760 |
+
|
| 761 |
+
outcome, new_cfg, prompt_err = _prompt_geometry_calibration(
|
| 762 |
+
cfg, ref_img, input_fn
|
| 763 |
+
)
|
| 764 |
+
if outcome == "invalid":
|
| 765 |
+
print(
|
| 766 |
+
f"\n[FAIL] Invalid geometry input ({prompt_err}); geometry remains"
|
| 767 |
+
" unconfirmed.",
|
| 768 |
+
file=sys.stderr,
|
| 769 |
+
)
|
| 770 |
+
return _fail_step(
|
| 771 |
+
out_dir, summary, "geometry", 2, f"invalid_geometry_input: {prompt_err}"
|
| 772 |
+
), cfg
|
| 773 |
+
if outcome == "stopped":
|
| 774 |
+
print("Geometry calibration stopped; geometry remains unconfirmed.")
|
| 775 |
+
summary["status"] = "stopped_by_operator"
|
| 776 |
+
summary["steps"]["geometry"] = {
|
| 777 |
+
"status": "stopped_by_operator",
|
| 778 |
+
"geometry_confirmed": False,
|
| 779 |
+
}
|
| 780 |
+
_write_summary(out_dir, summary)
|
| 781 |
+
return 0, cfg
|
| 782 |
+
|
| 783 |
+
cfg = new_cfg
|
| 784 |
+
if write_cfg and args.config is not None:
|
| 785 |
+
save_robot_config(cfg, args.config)
|
| 786 |
+
print(f" Saved confirmed geometry to {args.config}")
|
| 787 |
+
summary["steps"]["geometry"] = {
|
| 788 |
+
"status": "ok",
|
| 789 |
+
"exit_code": 0,
|
| 790 |
+
"geometry_confirmed": True,
|
| 791 |
+
"z_table_m": cfg.z_table_m,
|
| 792 |
+
}
|
| 793 |
+
return 0, cfg
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
def _run_cameras_step(
|
| 797 |
+
cfg: RobotConfig,
|
| 798 |
+
args: argparse.Namespace,
|
| 799 |
+
out_dir: Path,
|
| 800 |
+
summary: dict[str, Any],
|
| 801 |
+
*,
|
| 802 |
+
effective_dry_run: bool,
|
| 803 |
+
) -> int:
|
| 804 |
+
"""Runs Step 2 4-camera freshness check, contact sheet, and MP4 recording."""
|
| 805 |
+
print("\n--- Step 2: Camera Verification & Contact Sheet ---")
|
| 806 |
+
step2_dir = out_dir / "step2_cameras"
|
| 807 |
+
step2_dir.mkdir(parents=True, exist_ok=True)
|
| 808 |
+
rc2, c_rep, err2 = _call_stage(
|
| 809 |
+
check_cameras.run_camera_check,
|
| 810 |
+
cfg,
|
| 811 |
+
realtime=args.realtime,
|
| 812 |
+
dry_run=effective_dry_run,
|
| 813 |
+
output_dir=step2_dir,
|
| 814 |
+
output_json=step2_dir / "camera_check_report.json",
|
| 815 |
+
)
|
| 816 |
+
if rc2 != 0:
|
| 817 |
+
print(
|
| 818 |
+
f"\n[FAIL] Step 2 camera check failed (exit code {rc2}).",
|
| 819 |
+
file=sys.stderr,
|
| 820 |
+
)
|
| 821 |
+
return _fail_step(out_dir, summary, "cameras", rc2, err2)
|
| 822 |
+
|
| 823 |
+
for key, art_key, label in (
|
| 824 |
+
("contact_sheet_path", "contact_sheet_2x2", "Contact Sheet"),
|
| 825 |
+
("fk_projection_overlay_path", "fk_projection_overlay_2x2", "FK Overlay"),
|
| 826 |
+
):
|
| 827 |
+
if c_rep.get(key):
|
| 828 |
+
summary["artifacts"][art_key] = c_rep[key]
|
| 829 |
+
print(f" {label:<14}: {c_rep[key]}")
|
| 830 |
+
mp4_path = (c_rep.get("recording") or {}).get("mp4_path")
|
| 831 |
+
if mp4_path:
|
| 832 |
+
summary["artifacts"]["cameras_recording_mp4"] = mp4_path
|
| 833 |
+
print(f" MP4 Recording : {mp4_path}")
|
| 834 |
+
|
| 835 |
+
summary["steps"]["cameras"] = {"status": "ok", "exit_code": 0}
|
| 836 |
+
return 0
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
def _confirm_actuation(
|
| 840 |
+
step_key: str,
|
| 841 |
+
args: argparse.Namespace,
|
| 842 |
+
out_dir: Path,
|
| 843 |
+
summary: dict[str, Any],
|
| 844 |
+
*,
|
| 845 |
+
will_actuate: bool,
|
| 846 |
+
input_fn: Callable[[str], str],
|
| 847 |
+
) -> tuple[str, int]:
|
| 848 |
+
"""Handles interactive `[E-STOP READY]` prompt before live actuation."""
|
| 849 |
+
if not will_actuate:
|
| 850 |
+
return "run", 0
|
| 851 |
+
|
| 852 |
+
if args.yes:
|
| 853 |
+
if step_key == "abort-test" and sys.stdin.isatty():
|
| 854 |
+
print(
|
| 855 |
+
" NOTE: Type 'q' + ENTER (or press Ctrl+C) while the left arm"
|
| 856 |
+
" slowly nudges (10 deg @ 4 deg/s) to trigger smooth C^2"
|
| 857 |
+
" abort-and-unwind."
|
| 858 |
+
)
|
| 859 |
+
return "run", 0
|
| 860 |
+
|
| 861 |
+
if input_fn is input and not sys.stdin.isatty():
|
| 862 |
+
print(
|
| 863 |
+
f"[FAIL] Physical actuation for '{step_key}' requires an"
|
| 864 |
+
" interactive TTY or --yes.",
|
| 865 |
+
file=sys.stderr,
|
| 866 |
+
)
|
| 867 |
+
return "fail", _fail_step(
|
| 868 |
+
out_dir, summary, step_key, 2, "non_interactive_without_yes"
|
| 869 |
+
)
|
| 870 |
+
|
| 871 |
+
print(f"[E-STOP READY] Operator confirmation required for '{step_key}':")
|
| 872 |
+
if step_key == "abort-test":
|
| 873 |
+
print(
|
| 874 |
+
" NOTE: Type 'q' + ENTER (or press Ctrl+C) while the left arm"
|
| 875 |
+
" slowly nudges (10 deg @ 4 deg/s) to trigger smooth C^2"
|
| 876 |
+
" abort-and-unwind."
|
| 877 |
+
)
|
| 878 |
+
|
| 879 |
+
try:
|
| 880 |
+
ans = (
|
| 881 |
+
input_fn("Proceed with actuation? [y = run / s = skip / N,q = quit]: ")
|
| 882 |
+
.strip()
|
| 883 |
+
.lower()
|
| 884 |
+
)
|
| 885 |
+
except (EOFError, KeyboardInterrupt):
|
| 886 |
+
ans = "q"
|
| 887 |
+
|
| 888 |
+
if ans in ("s", "skip"):
|
| 889 |
+
print(f"Skipping '{step_key}'.")
|
| 890 |
+
summary["steps"][step_key] = {"status": "skipped"}
|
| 891 |
+
return "skip", 0
|
| 892 |
+
if ans not in ("y", "yes"):
|
| 893 |
+
msg = (
|
| 894 |
+
f"Bring-up stopped by operator before '{step_key}'."
|
| 895 |
+
if ans in ("q", "quit", "n", "no", "")
|
| 896 |
+
else f"Unrecognized response {ans!r}; stopping bring-up."
|
| 897 |
+
)
|
| 898 |
+
print(msg)
|
| 899 |
+
summary["status"] = "stopped_by_operator"
|
| 900 |
+
summary["steps"][step_key] = {"status": "stopped_by_operator"}
|
| 901 |
+
_write_summary(out_dir, summary)
|
| 902 |
+
return "stop", 0
|
| 903 |
+
return "run", 0
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
def _validate_actuation_result(
|
| 907 |
+
step_key: str,
|
| 908 |
+
sub_rep: Mapping[str, Any],
|
| 909 |
+
sub_dir: Path,
|
| 910 |
+
out_dir: Path,
|
| 911 |
+
summary: dict[str, Any],
|
| 912 |
+
) -> tuple[str, int]:
|
| 913 |
+
"""Checks post-step success/abort invariants for live actuation steps."""
|
| 914 |
+
if step_key == "gripper":
|
| 915 |
+
bad_arms = [
|
| 916 |
+
arm_name
|
| 917 |
+
for arm_name, arm_res in (sub_rep.get("results") or {}).items()
|
| 918 |
+
if isinstance(arm_res, dict)
|
| 919 |
+
and not bool(
|
| 920 |
+
(arm_res.get("gripper_cycle") or {}).get("stroke_ok", True)
|
| 921 |
+
)
|
| 922 |
+
]
|
| 923 |
+
if bad_arms:
|
| 924 |
+
print(
|
| 925 |
+
f"\n[FAIL] Step 3a gripper stroke check failed on {bad_arms}.",
|
| 926 |
+
file=sys.stderr,
|
| 927 |
+
)
|
| 928 |
+
return "fail", _fail_step(
|
| 929 |
+
out_dir, summary, step_key, 1, "gripper_stroke_failed"
|
| 930 |
+
)
|
| 931 |
+
return "ok", 0
|
| 932 |
+
|
| 933 |
+
if step_key in ("nudge", "home"):
|
| 934 |
+
if any(
|
| 935 |
+
isinstance(arm_res, dict)
|
| 936 |
+
and bool((arm_res.get(step_key) or {}).get("aborted", False))
|
| 937 |
+
for arm_res in (sub_rep.get("results") or {}).values()
|
| 938 |
+
):
|
| 939 |
+
print(f"Bring-up stopped by operator abort during '{step_key}'.")
|
| 940 |
+
summary["status"] = "stopped_by_operator"
|
| 941 |
+
summary["steps"][step_key] = {
|
| 942 |
+
"status": "stopped_by_operator",
|
| 943 |
+
"aborted": True,
|
| 944 |
+
}
|
| 945 |
+
_write_summary(out_dir, summary)
|
| 946 |
+
return "stop", 0
|
| 947 |
+
return "ok", 0
|
| 948 |
+
|
| 949 |
+
if step_key == "abort-test":
|
| 950 |
+
abort_info = next(
|
| 951 |
+
(
|
| 952 |
+
arm_res.get("abort_test")
|
| 953 |
+
for arm_res in (sub_rep.get("results") or {}).values()
|
| 954 |
+
if isinstance(arm_res, dict)
|
| 955 |
+
and isinstance(arm_res.get("abort_test"), dict)
|
| 956 |
+
),
|
| 957 |
+
None,
|
| 958 |
+
)
|
| 959 |
+
if abort_info is not None:
|
| 960 |
+
aborted_ok = bool(abort_info.get("aborted", False))
|
| 961 |
+
unwound_ok = bool(abort_info.get("unwound_to_start", False))
|
| 962 |
+
grip_ok = bool(abort_info.get("gripper_preserved", True))
|
| 963 |
+
if not (aborted_ok and unwound_ok and grip_ok):
|
| 964 |
+
print(
|
| 965 |
+
"\n[FAIL] Step 3c abort-test did not verify smooth"
|
| 966 |
+
f" abort-and-unwind (aborted={aborted_ok},"
|
| 967 |
+
f" unwound_to_start={unwound_ok},"
|
| 968 |
+
f" gripper_preserved={grip_ok}). Re-run and type 'q' +"
|
| 969 |
+
" ENTER while the left arm moves.",
|
| 970 |
+
file=sys.stderr,
|
| 971 |
+
)
|
| 972 |
+
return "fail", _fail_step(
|
| 973 |
+
out_dir, summary, step_key, 1, "abort_unwind_not_verified"
|
| 974 |
+
)
|
| 975 |
+
return "ok", 0
|
| 976 |
+
|
| 977 |
+
if step_key == "hello-world":
|
| 978 |
+
mp4_cand = sub_rep.get("mp4_path") or str(
|
| 979 |
+
sub_dir / "stage4_hello_world.mp4"
|
| 980 |
+
)
|
| 981 |
+
if Path(mp4_cand).is_file():
|
| 982 |
+
summary["artifacts"]["stage4_hello_world_mp4"] = str(mp4_cand)
|
| 983 |
+
print(f" Stage 4 MP4 Recording: {mp4_cand}")
|
| 984 |
+
if bool(sub_rep.get("aborted", False)):
|
| 985 |
+
print("Bring-up stopped by operator abort during 'hello-world'.")
|
| 986 |
+
summary["status"] = "stopped_by_operator"
|
| 987 |
+
summary["steps"][step_key] = {
|
| 988 |
+
"status": "stopped_by_operator",
|
| 989 |
+
"aborted": True,
|
| 990 |
+
}
|
| 991 |
+
_write_summary(out_dir, summary)
|
| 992 |
+
return "stop", 0
|
| 993 |
+
return "ok", 0
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def main(
|
| 997 |
+
argv: Sequence[str] | None = None,
|
| 998 |
+
input_fn: Callable[[str], str] = input,
|
| 999 |
+
) -> int:
|
| 1000 |
+
"""Executes the progressive bring-up pipeline or a single bring-up step."""
|
| 1001 |
+
args = parse_args(argv)
|
| 1002 |
+
effective_dry_run = bool(args.dry_run)
|
| 1003 |
+
is_read_only = bool(args.read_only)
|
| 1004 |
+
mode_label = (
|
| 1005 |
+
"dry_run"
|
| 1006 |
+
if effective_dry_run
|
| 1007 |
+
else ("read_only" if is_read_only else "hardware")
|
| 1008 |
+
)
|
| 1009 |
+
|
| 1010 |
+
resolved_out_dir = resolve_stage_output_dir(
|
| 1011 |
+
"bringup", args.output_dir, dry_run=effective_dry_run
|
| 1012 |
+
)
|
| 1013 |
+
out_dir = (
|
| 1014 |
+
resolved_out_dir
|
| 1015 |
+
if resolved_out_dir is not None
|
| 1016 |
+
else Path(tempfile.mkdtemp(prefix="fr3_bringup_"))
|
| 1017 |
+
)
|
| 1018 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 1019 |
+
|
| 1020 |
+
steps_to_run = _resolve_steps_to_run(args)
|
| 1021 |
+
target_desc = (
|
| 1022 |
+
f"step={args.step}" if args.step is not None else f"up_to={args.up_to}"
|
| 1023 |
+
)
|
| 1024 |
+
summary: dict[str, Any] = {
|
| 1025 |
+
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
|
| 1026 |
+
"mode": mode_label,
|
| 1027 |
+
"up_to": None if args.step is not None else args.up_to,
|
| 1028 |
+
"step": args.step,
|
| 1029 |
+
"read_only": is_read_only,
|
| 1030 |
+
"status": "in_progress",
|
| 1031 |
+
"steps": {},
|
| 1032 |
+
"artifacts": {},
|
| 1033 |
+
}
|
| 1034 |
+
|
| 1035 |
+
print(
|
| 1036 |
+
f"=== Franka Research 3 Duo Bring-Up (mode={mode_label},"
|
| 1037 |
+
f" {target_desc}) ==="
|
| 1038 |
+
)
|
| 1039 |
+
print(f"Output directory: {out_dir}")
|
| 1040 |
+
|
| 1041 |
+
try:
|
| 1042 |
+
cfg = load_robot_config(args.config)
|
| 1043 |
+
if args.left_ip:
|
| 1044 |
+
cfg.arms.left.ip = str(args.left_ip)
|
| 1045 |
+
if args.right_ip:
|
| 1046 |
+
cfg.arms.right.ip = str(args.right_ip)
|
| 1047 |
+
except (OSError, ValueError, TypeError) as exc:
|
| 1048 |
+
err_msg = f"{type(exc).__name__}: {exc}"
|
| 1049 |
+
print(f"\n[FAIL] Invalid robot configuration: {err_msg}", file=sys.stderr)
|
| 1050 |
+
return _fail_step(out_dir, summary, steps_to_run[0], 1, err_msg)
|
| 1051 |
+
|
| 1052 |
+
cli_geom_updates, cli_geom_err = _extract_geometry_cli_updates(args)
|
| 1053 |
+
if cli_geom_err is not None:
|
| 1054 |
+
print(
|
| 1055 |
+
f"\n[FAIL] Invalid geometry CLI flag: {cli_geom_err}", file=sys.stderr
|
| 1056 |
+
)
|
| 1057 |
+
err_step = "geometry" if "geometry" in steps_to_run else steps_to_run[0]
|
| 1058 |
+
return _fail_step(out_dir, summary, err_step, 2, cli_geom_err)
|
| 1059 |
+
if cli_geom_updates:
|
| 1060 |
+
cfg = normalize_robot_config({**cfg.to_dict(), **cli_geom_updates})
|
| 1061 |
+
|
| 1062 |
+
if "env" in steps_to_run:
|
| 1063 |
+
rc0 = _run_env_step(
|
| 1064 |
+
cfg,
|
| 1065 |
+
out_dir,
|
| 1066 |
+
summary,
|
| 1067 |
+
is_hw=not effective_dry_run,
|
| 1068 |
+
mode_label=mode_label,
|
| 1069 |
+
)
|
| 1070 |
+
if rc0 != 0:
|
| 1071 |
+
return rc0
|
| 1072 |
+
|
| 1073 |
+
if "preflight" in steps_to_run:
|
| 1074 |
+
rc1, cfg = _run_preflight_step(
|
| 1075 |
+
cfg,
|
| 1076 |
+
args,
|
| 1077 |
+
out_dir,
|
| 1078 |
+
summary,
|
| 1079 |
+
effective_dry_run=effective_dry_run,
|
| 1080 |
+
is_read_only=is_read_only,
|
| 1081 |
+
)
|
| 1082 |
+
if rc1 != 0:
|
| 1083 |
+
return rc1
|
| 1084 |
+
|
| 1085 |
+
if "geometry" in steps_to_run:
|
| 1086 |
+
rc_geom, cfg = _run_geometry_step(
|
| 1087 |
+
cfg,
|
| 1088 |
+
args,
|
| 1089 |
+
out_dir,
|
| 1090 |
+
summary,
|
| 1091 |
+
effective_dry_run=effective_dry_run,
|
| 1092 |
+
is_read_only=is_read_only,
|
| 1093 |
+
input_fn=input_fn,
|
| 1094 |
+
cli_updates=cli_geom_updates,
|
| 1095 |
+
)
|
| 1096 |
+
if rc_geom != 0 or summary.get("status") == "stopped_by_operator":
|
| 1097 |
+
return rc_geom
|
| 1098 |
+
elif cli_geom_updates or args.confirm_geometry:
|
| 1099 |
+
confirmed_via_cli = bool(args.confirm_geometry) or (
|
| 1100 |
+
len(cli_geom_updates) == len(_GEOMETRY_CLI_ALLOW_ZERO)
|
| 1101 |
+
)
|
| 1102 |
+
cfg = normalize_robot_config({
|
| 1103 |
+
**cfg.to_dict(),
|
| 1104 |
+
**cli_geom_updates,
|
| 1105 |
+
"geometry_confirmed": bool(cfg.geometry_confirmed) or confirmed_via_cli,
|
| 1106 |
+
})
|
| 1107 |
+
if (
|
| 1108 |
+
not effective_dry_run
|
| 1109 |
+
and not args.no_write_config
|
| 1110 |
+
and not is_read_only
|
| 1111 |
+
and args.config is not None
|
| 1112 |
+
):
|
| 1113 |
+
save_robot_config(cfg, args.config)
|
| 1114 |
+
|
| 1115 |
+
if "cameras" in steps_to_run:
|
| 1116 |
+
rc2 = _run_cameras_step(
|
| 1117 |
+
cfg,
|
| 1118 |
+
args,
|
| 1119 |
+
out_dir,
|
| 1120 |
+
summary,
|
| 1121 |
+
effective_dry_run=effective_dry_run,
|
| 1122 |
+
)
|
| 1123 |
+
if rc2 != 0:
|
| 1124 |
+
return rc2
|
| 1125 |
+
|
| 1126 |
+
for step_key in steps_to_run:
|
| 1127 |
+
desc = _ACTUATION_DESCRIPTIONS.get(step_key)
|
| 1128 |
+
if desc is None:
|
| 1129 |
+
continue
|
| 1130 |
+
print(f"\n--- {desc} ---")
|
| 1131 |
+
|
| 1132 |
+
will_actuate = not effective_dry_run and not is_read_only
|
| 1133 |
+
if will_actuate and step_key in _COMPLETE_CONFIG_REQUIRED_STEPS:
|
| 1134 |
+
missing_fields = validate_robot_config_complete(cfg)
|
| 1135 |
+
if missing_fields:
|
| 1136 |
+
missing_str = ", ".join(missing_fields)
|
| 1137 |
+
print(
|
| 1138 |
+
f"\n[FAIL] Cannot run live actuation '{step_key}': incomplete"
|
| 1139 |
+
f" robot configuration. Missing/unconfirmed: {missing_str}."
|
| 1140 |
+
" Run '--step preflight' and '--step geometry' (or pass"
|
| 1141 |
+
" measurement flags + '--confirm-geometry') first.",
|
| 1142 |
+
file=sys.stderr,
|
| 1143 |
+
)
|
| 1144 |
+
return _fail_step(
|
| 1145 |
+
out_dir,
|
| 1146 |
+
summary,
|
| 1147 |
+
step_key,
|
| 1148 |
+
2,
|
| 1149 |
+
f"incomplete_config: {missing_str}",
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
action, prompt_rc = _confirm_actuation(
|
| 1153 |
+
step_key,
|
| 1154 |
+
args,
|
| 1155 |
+
out_dir,
|
| 1156 |
+
summary,
|
| 1157 |
+
will_actuate=will_actuate,
|
| 1158 |
+
input_fn=input_fn,
|
| 1159 |
+
)
|
| 1160 |
+
if action == "skip":
|
| 1161 |
+
continue
|
| 1162 |
+
if action in ("fail", "stop"):
|
| 1163 |
+
return prompt_rc
|
| 1164 |
+
|
| 1165 |
+
sub_dir = out_dir / f"step3_{step_key}"
|
| 1166 |
+
sub_dir.mkdir(parents=True, exist_ok=True)
|
| 1167 |
+
rc, sub_rep, sub_err = _call_stage(
|
| 1168 |
+
check_robot.run_robot_check,
|
| 1169 |
+
cfg,
|
| 1170 |
+
mode=step_key,
|
| 1171 |
+
read_only=is_read_only,
|
| 1172 |
+
dry_run=effective_dry_run,
|
| 1173 |
+
realtime=args.realtime,
|
| 1174 |
+
output_dir=sub_dir,
|
| 1175 |
+
)
|
| 1176 |
+
if rc != 0:
|
| 1177 |
+
print(
|
| 1178 |
+
f"\n[FAIL] {desc} returned non-zero exit code {rc}.", file=sys.stderr
|
| 1179 |
+
)
|
| 1180 |
+
return _fail_step(out_dir, summary, step_key, rc, sub_err)
|
| 1181 |
+
|
| 1182 |
+
if will_actuate:
|
| 1183 |
+
outcome, out_rc = _validate_actuation_result(
|
| 1184 |
+
step_key, sub_rep, sub_dir, out_dir, summary
|
| 1185 |
+
)
|
| 1186 |
+
if outcome in ("fail", "stop"):
|
| 1187 |
+
return out_rc
|
| 1188 |
+
|
| 1189 |
+
step_entry: dict[str, Any] = {"status": "ok", "exit_code": 0}
|
| 1190 |
+
if is_read_only:
|
| 1191 |
+
step_entry["read_only"] = True
|
| 1192 |
+
summary["steps"][step_key] = step_entry
|
| 1193 |
+
|
| 1194 |
+
summary["status"] = "ok"
|
| 1195 |
+
_write_summary(out_dir, summary)
|
| 1196 |
+
|
| 1197 |
+
print("\n=======================================================")
|
| 1198 |
+
print(" FR3 DUO BRING-UP COMPLETED SUCCESSFULLY!")
|
| 1199 |
+
print(f" Mode : {mode_label}")
|
| 1200 |
+
print(f" Target : {target_desc}")
|
| 1201 |
+
print(f" Summary : {out_dir / 'bringup_summary.json'}")
|
| 1202 |
+
for art_name, art_p in summary.get("artifacts", {}).items():
|
| 1203 |
+
print(f" Artifact : [{art_name}] -> {art_p}")
|
| 1204 |
+
print("=======================================================")
|
| 1205 |
+
return 0
|
| 1206 |
+
|
| 1207 |
+
|
| 1208 |
+
if __name__ == "__main__":
|
| 1209 |
+
sys.exit(main())
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/check_cameras.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Stage 2 4-camera freshness check, 2x2 contact sheet, and MP4 recorder."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from collections.abc import Mapping
|
| 20 |
+
from datetime import datetime, timezone
|
| 21 |
+
import json
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
from typing import TYPE_CHECKING, Any
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
from fr3_arm_controller import read_arm_joints_or_rest
|
| 30 |
+
from fr3_camera_controller import (
|
| 31 |
+
CANONICAL_CAMERAS,
|
| 32 |
+
CameraFrame,
|
| 33 |
+
Fr3DuoCameraController,
|
| 34 |
+
render_contact_sheet,
|
| 35 |
+
)
|
| 36 |
+
from fr3_config import (
|
| 37 |
+
RobotConfig,
|
| 38 |
+
normalize_robot_config,
|
| 39 |
+
open_mp4_writer,
|
| 40 |
+
resolve_stage_output_dir,
|
| 41 |
+
save_rgb_png,
|
| 42 |
+
)
|
| 43 |
+
import fr3_kinematics
|
| 44 |
+
import fr3_mjcf
|
| 45 |
+
|
| 46 |
+
if TYPE_CHECKING:
|
| 47 |
+
import fr3_duo_robot
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _record_mosaic_mp4(
|
| 51 |
+
rig: Fr3DuoCameraController,
|
| 52 |
+
mp4_path: Path,
|
| 53 |
+
jsonl_path: Path,
|
| 54 |
+
*,
|
| 55 |
+
duration_s: float,
|
| 56 |
+
target_fps: float,
|
| 57 |
+
) -> dict[str, Any]:
|
| 58 |
+
"""Records 2x2 contact-sheet frames to MP4 and per-frame logs to JSONL."""
|
| 59 |
+
mp4_path.parent.mkdir(parents=True, exist_ok=True)
|
| 60 |
+
jsonl_path.parent.mkdir(parents=True, exist_ok=True)
|
| 61 |
+
|
| 62 |
+
first_batch = rig.capture_all()
|
| 63 |
+
first_mosaic = render_contact_sheet(first_batch)
|
| 64 |
+
h, w = int(first_mosaic.shape[0]), int(first_mosaic.shape[1])
|
| 65 |
+
|
| 66 |
+
writer = open_mp4_writer(mp4_path, width=w, height=h, fps=target_fps)
|
| 67 |
+
|
| 68 |
+
total_frames = max(
|
| 69 |
+
2, int(round(max(0.1, float(duration_s)) * float(target_fps)))
|
| 70 |
+
)
|
| 71 |
+
dt_s = 1.0 / max(1.0, float(target_fps))
|
| 72 |
+
frames_written = 0
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
with jsonl_path.open("w", encoding="utf-8") as log_f:
|
| 76 |
+
for idx in range(total_frames):
|
| 77 |
+
t0 = time.monotonic()
|
| 78 |
+
batch: dict[str, CameraFrame] = (
|
| 79 |
+
first_batch if idx == 0 else rig.capture_all()
|
| 80 |
+
)
|
| 81 |
+
mosaic_rgb = first_mosaic if idx == 0 else render_contact_sheet(batch)
|
| 82 |
+
writer.write(np.ascontiguousarray(mosaic_rgb[:, :, ::-1]))
|
| 83 |
+
frames_written += 1
|
| 84 |
+
event = {
|
| 85 |
+
"frame_index": idx,
|
| 86 |
+
"captured_monotonic_s": round(t0, 6),
|
| 87 |
+
"streams": {
|
| 88 |
+
name: {
|
| 89 |
+
"timestamp_s": round(float(frm.timestamp_s), 6),
|
| 90 |
+
"brightness_mean": round(float(frm.brightness_mean), 2),
|
| 91 |
+
}
|
| 92 |
+
for name, frm in batch.items()
|
| 93 |
+
},
|
| 94 |
+
}
|
| 95 |
+
log_f.write(json.dumps(event) + "\n")
|
| 96 |
+
elapsed = time.monotonic() - t0
|
| 97 |
+
if idx + 1 < total_frames and dt_s > elapsed:
|
| 98 |
+
time.sleep(min(0.05, dt_s - elapsed))
|
| 99 |
+
finally:
|
| 100 |
+
writer.release()
|
| 101 |
+
|
| 102 |
+
if not mp4_path.is_file() or mp4_path.stat().st_size == 0:
|
| 103 |
+
raise RuntimeError(f"Failed to encode valid MP4 video at {mp4_path}")
|
| 104 |
+
|
| 105 |
+
return {
|
| 106 |
+
"mp4_path": str(mp4_path),
|
| 107 |
+
"jsonl_path": str(jsonl_path),
|
| 108 |
+
"frames_written": frames_written,
|
| 109 |
+
"resolution": [w, h],
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _render_fk_overlay(
|
| 114 |
+
cfg: RobotConfig,
|
| 115 |
+
snapshot: Mapping[str, CameraFrame],
|
| 116 |
+
fk_file: Path,
|
| 117 |
+
*,
|
| 118 |
+
realtime: str,
|
| 119 |
+
) -> str | None:
|
| 120 |
+
"""Projects left/right pinch TCPs onto camera frames and writes mosaic."""
|
| 121 |
+
try:
|
| 122 |
+
left_q, right_q, fk_warns = read_arm_joints_or_rest(
|
| 123 |
+
cfg, realtime_mode=realtime
|
| 124 |
+
)
|
| 125 |
+
for fw in fk_warns:
|
| 126 |
+
print(f"Warning: {fw}", file=sys.stderr)
|
| 127 |
+
mj_model, _ = fr3_mjcf.build_fr3_duo_mjcf(cfg)
|
| 128 |
+
cal = fr3_kinematics.get_camera_calibration_opencv(
|
| 129 |
+
mj_model, left_q, right_q
|
| 130 |
+
)
|
| 131 |
+
p_left, _ = fr3_kinematics.compute_arm_fk(mj_model, "left", left_q)
|
| 132 |
+
p_right, _ = fr3_kinematics.compute_arm_fk(mj_model, "right", right_q)
|
| 133 |
+
pinch_sites = {"L pinch": p_left, "R pinch": p_right}
|
| 134 |
+
colors = {
|
| 135 |
+
"L pinch": np.array([0, 255, 255], dtype=np.uint8),
|
| 136 |
+
"R pinch": np.array([255, 128, 0], dtype=np.uint8),
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
overlay_snapshot: dict[str, CameraFrame] = {}
|
| 140 |
+
for c_name in CANONICAL_CAMERAS:
|
| 141 |
+
frm = snapshot.get(c_name)
|
| 142 |
+
if frm is None:
|
| 143 |
+
continue
|
| 144 |
+
tile = frm.rgb.copy()
|
| 145 |
+
h_tile, w_tile = tile.shape[:2]
|
| 146 |
+
if c_name in cal:
|
| 147 |
+
k_mat = np.array(cal[c_name]["K"], dtype=np.float64, copy=True)
|
| 148 |
+
cal_w = int(cal[c_name].get("width", w_tile))
|
| 149 |
+
cal_h = int(cal[c_name].get("height", h_tile))
|
| 150 |
+
if cal_w > 0 and cal_h > 0 and (w_tile != cal_w or h_tile != cal_h):
|
| 151 |
+
sx = float(w_tile) / float(cal_w)
|
| 152 |
+
sy = float(h_tile) / float(cal_h)
|
| 153 |
+
k_mat[0, 0] *= sx
|
| 154 |
+
k_mat[0, 2] *= sx
|
| 155 |
+
k_mat[1, 1] *= sy
|
| 156 |
+
k_mat[1, 2] *= sy
|
| 157 |
+
t_base_cam = cal[c_name]["T_base_cam"]
|
| 158 |
+
for label, p_base in pinch_sites.items():
|
| 159 |
+
(u, v), z_depth = fr3_kinematics.project_base_points_opencv(
|
| 160 |
+
p_base, k_mat, t_base_cam
|
| 161 |
+
)
|
| 162 |
+
if z_depth > 0.04:
|
| 163 |
+
ui, vi = int(round(u)), int(round(v))
|
| 164 |
+
col = colors[label]
|
| 165 |
+
r_c = 18
|
| 166 |
+
if -r_c <= ui < w_tile + r_c and -r_c <= vi < h_tile + r_c:
|
| 167 |
+
tile[
|
| 168 |
+
max(0, vi - 2) : min(h_tile, vi + 3),
|
| 169 |
+
max(0, ui - r_c) : min(w_tile, ui + r_c + 1),
|
| 170 |
+
] = col
|
| 171 |
+
tile[
|
| 172 |
+
max(0, vi - r_c) : min(h_tile, vi + r_c + 1),
|
| 173 |
+
max(0, ui - 2) : min(w_tile, ui + 3),
|
| 174 |
+
] = col
|
| 175 |
+
overlay_snapshot[c_name] = CameraFrame(
|
| 176 |
+
name=frm.name,
|
| 177 |
+
rgb=tile,
|
| 178 |
+
timestamp_s=frm.timestamp_s,
|
| 179 |
+
width=frm.width,
|
| 180 |
+
height=frm.height,
|
| 181 |
+
backend=frm.backend,
|
| 182 |
+
)
|
| 183 |
+
save_rgb_png(render_contact_sheet(overlay_snapshot), fk_file)
|
| 184 |
+
return str(fk_file)
|
| 185 |
+
except (RuntimeError, OSError, ValueError, KeyError) as exc:
|
| 186 |
+
print(
|
| 187 |
+
f"Warning: Failed to generate fk_projection_overlay_2x2.png: {exc}",
|
| 188 |
+
file=sys.stderr,
|
| 189 |
+
)
|
| 190 |
+
return None
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def run_camera_check(
|
| 194 |
+
config: RobotConfig | Mapping[str, Any] | None = None,
|
| 195 |
+
*,
|
| 196 |
+
output_dir: Path | None = None,
|
| 197 |
+
output_mp4: Path | None = None,
|
| 198 |
+
output_json: Path | None = None,
|
| 199 |
+
duration_sec: float | None = None,
|
| 200 |
+
fps: float = 15.0,
|
| 201 |
+
max_age_sec: float = 0.30,
|
| 202 |
+
num_reads: int = 3,
|
| 203 |
+
save_references: bool = False,
|
| 204 |
+
dry_run: bool = False,
|
| 205 |
+
realtime: str = "auto",
|
| 206 |
+
sim_robot: fr3_duo_robot.Fr3DuoRobot | None = None,
|
| 207 |
+
) -> tuple[int, dict[str, Any]]:
|
| 208 |
+
"""Runs Stage 2 4-camera freshness check, contact sheet, and MP4 recording."""
|
| 209 |
+
cfg = normalize_robot_config(config)
|
| 210 |
+
effective_dry_run = bool(dry_run)
|
| 211 |
+
|
| 212 |
+
resolved_out_dir = resolve_stage_output_dir(
|
| 213 |
+
"stage2_cameras", output_dir, dry_run=effective_dry_run
|
| 214 |
+
)
|
| 215 |
+
duration_s = (
|
| 216 |
+
float(duration_sec)
|
| 217 |
+
if duration_sec is not None
|
| 218 |
+
else (0.25 if effective_dry_run else 2.0)
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
with Fr3DuoCameraController(
|
| 222 |
+
specs=cfg.cameras,
|
| 223 |
+
dry_run=effective_dry_run,
|
| 224 |
+
sim_robot=sim_robot,
|
| 225 |
+
) as rig:
|
| 226 |
+
freshness = rig.check_freshness(
|
| 227 |
+
max_age_s=max_age_sec,
|
| 228 |
+
num_reads=num_reads,
|
| 229 |
+
interval_s=0.01 if effective_dry_run else 0.05,
|
| 230 |
+
)
|
| 231 |
+
snapshot = rig.capture_all()
|
| 232 |
+
mosaic_rgb = render_contact_sheet(snapshot)
|
| 233 |
+
|
| 234 |
+
contact_sheet_path: str | None = None
|
| 235 |
+
fk_overlay_path: str | None = None
|
| 236 |
+
recording_info: dict[str, Any] | None = None
|
| 237 |
+
|
| 238 |
+
if resolved_out_dir is not None or output_mp4 is not None:
|
| 239 |
+
if resolved_out_dir is not None:
|
| 240 |
+
base_dir = resolved_out_dir
|
| 241 |
+
else:
|
| 242 |
+
assert output_mp4 is not None
|
| 243 |
+
base_dir = output_mp4.parent
|
| 244 |
+
sheet_file = base_dir / "contact_sheet_2x2.png"
|
| 245 |
+
save_rgb_png(mosaic_rgb, sheet_file)
|
| 246 |
+
contact_sheet_path = str(sheet_file)
|
| 247 |
+
|
| 248 |
+
if not effective_dry_run:
|
| 249 |
+
fk_overlay_path = _render_fk_overlay(
|
| 250 |
+
cfg,
|
| 251 |
+
snapshot,
|
| 252 |
+
base_dir / "fk_projection_overlay_2x2.png",
|
| 253 |
+
realtime=realtime,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
if save_references:
|
| 257 |
+
for cam_name in CANONICAL_CAMERAS:
|
| 258 |
+
if cam_name in snapshot:
|
| 259 |
+
save_rgb_png(
|
| 260 |
+
snapshot[cam_name].rgb, base_dir / f"ref_{cam_name}.png"
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
mp4_file = output_mp4 or (base_dir / "cameras_recording.mp4")
|
| 264 |
+
jsonl_file = base_dir / "camera_frames.jsonl"
|
| 265 |
+
recording_info = _record_mosaic_mp4(
|
| 266 |
+
rig,
|
| 267 |
+
mp4_file,
|
| 268 |
+
jsonl_file,
|
| 269 |
+
duration_s=duration_s,
|
| 270 |
+
target_fps=fps,
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
mode_label = "dry_run" if effective_dry_run else "hardware"
|
| 274 |
+
report: dict[str, Any] = {
|
| 275 |
+
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
|
| 276 |
+
"stage": "stage2_check_cameras",
|
| 277 |
+
"mode": mode_label,
|
| 278 |
+
"dry_run": effective_dry_run,
|
| 279 |
+
"freshness": freshness,
|
| 280 |
+
"contact_sheet_shape": list(mosaic_rgb.shape),
|
| 281 |
+
"contact_sheet_path": contact_sheet_path,
|
| 282 |
+
"fk_projection_overlay_path": fk_overlay_path,
|
| 283 |
+
"recording": recording_info,
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
json_path = output_json or (
|
| 287 |
+
resolved_out_dir / "camera_check_report.json"
|
| 288 |
+
if resolved_out_dir is not None
|
| 289 |
+
else None
|
| 290 |
+
)
|
| 291 |
+
if json_path is not None:
|
| 292 |
+
json_path.parent.mkdir(parents=True, exist_ok=True)
|
| 293 |
+
json_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
| 294 |
+
report["report_path"] = str(json_path)
|
| 295 |
+
|
| 296 |
+
tag = "[DRY-RUN]" if effective_dry_run else "[HARDWARE]"
|
| 297 |
+
print(
|
| 298 |
+
f"{tag} Stage 2 Camera Check | ok={freshness['ok']} | "
|
| 299 |
+
f"streams={sorted(freshness['cameras'].keys())} | "
|
| 300 |
+
f"mosaic={list(mosaic_rgb.shape)}"
|
| 301 |
+
)
|
| 302 |
+
if contact_sheet_path is not None:
|
| 303 |
+
print(f" contact_sheet: {contact_sheet_path}")
|
| 304 |
+
if fk_overlay_path is not None:
|
| 305 |
+
print(f" fk_overlay : {fk_overlay_path}")
|
| 306 |
+
if recording_info is not None and recording_info.get("mp4_path"):
|
| 307 |
+
print(
|
| 308 |
+
f" recording_mp4: {recording_info['mp4_path']} "
|
| 309 |
+
f"({recording_info.get('frames_written', 0)} frames)"
|
| 310 |
+
)
|
| 311 |
+
if json_path is not None:
|
| 312 |
+
print(f" report_json : {json_path}")
|
| 313 |
+
for err in freshness.get("errors", []):
|
| 314 |
+
print(f" ERROR: {err}", file=sys.stderr)
|
| 315 |
+
|
| 316 |
+
return (0 if freshness["ok"] else 1), report
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/check_robot.py
ADDED
|
@@ -0,0 +1,765 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Stage 3-4 robot verification, abort-unwind test, homing, and Hello World."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from collections.abc import Callable, Mapping
|
| 20 |
+
from datetime import datetime, timezone
|
| 21 |
+
import json
|
| 22 |
+
import math
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
import sys
|
| 25 |
+
import tempfile
|
| 26 |
+
import threading
|
| 27 |
+
import time
|
| 28 |
+
from typing import Any
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
|
| 32 |
+
from fr3_arm_controller import validate_arm_readiness
|
| 33 |
+
from fr3_camera_controller import Fr3DuoCameraController, render_contact_sheet
|
| 34 |
+
from fr3_config import (
|
| 35 |
+
RobotConfig,
|
| 36 |
+
normalize_robot_config,
|
| 37 |
+
open_mp4_writer,
|
| 38 |
+
resolve_realtime_config,
|
| 39 |
+
resolve_stage_output_dir,
|
| 40 |
+
save_rgb_png,
|
| 41 |
+
)
|
| 42 |
+
from fr3_duo_robot import Fr3DuoRobot
|
| 43 |
+
from fr3_kinematics import compute_arm_fk
|
| 44 |
+
from fr3_mjcf import (
|
| 45 |
+
FR3_IK_MARGINS_RAD,
|
| 46 |
+
FR3_JOINT_LIMITS_RAD,
|
| 47 |
+
)
|
| 48 |
+
from fr3_safety import (
|
| 49 |
+
AbortWatcher,
|
| 50 |
+
Fr3DuoSafetyChecker,
|
| 51 |
+
clamp_q_to_padded_limits,
|
| 52 |
+
generate_quintic_trajectory,
|
| 53 |
+
)
|
| 54 |
+
from robotiq_gripper_controller import EMPTY_CLOSE_MIN_RATIO
|
| 55 |
+
|
| 56 |
+
GREETING_DELTA_LEFT_RAD = (0.08, -0.08, 0.0, 0.12, 0.0, 0.10, 0.0)
|
| 57 |
+
GREETING_DELTA_RIGHT_RAD = (-0.08, -0.08, 0.0, 0.12, 0.0, 0.10, 0.0)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _build_nudge_target(
|
| 61 |
+
q_start: list[float], delta_deg: float, arm: str
|
| 62 |
+
) -> list[float]:
|
| 63 |
+
"""Computes a limit-padded J1 nudge target pose for `arm`."""
|
| 64 |
+
q_target = list(q_start)
|
| 65 |
+
sign = 1.0 if arm == "left" else -1.0
|
| 66 |
+
delta_rad = math.radians(abs(float(delta_deg))) * sign
|
| 67 |
+
low = float(FR3_JOINT_LIMITS_RAD[0, 0]) + float(FR3_IK_MARGINS_RAD[0])
|
| 68 |
+
high = float(FR3_JOINT_LIMITS_RAD[0, 1]) - float(FR3_IK_MARGINS_RAD[0])
|
| 69 |
+
clamped = max(low, min(high, float(q_start[0]) + delta_rad))
|
| 70 |
+
if abs(clamped - q_start[0]) < 1e-3:
|
| 71 |
+
clamped = max(low, min(high, float(q_start[0]) - delta_rad))
|
| 72 |
+
q_target[0] = clamped
|
| 73 |
+
return q_target
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _create_robot(
|
| 77 |
+
cfg: RobotConfig,
|
| 78 |
+
*,
|
| 79 |
+
realtime_mode: str,
|
| 80 |
+
robot_factory: Callable[..., Fr3DuoRobot] | None,
|
| 81 |
+
) -> Fr3DuoRobot:
|
| 82 |
+
"""Constructs a live `Fr3DuoRobot` or invokes `robot_factory`."""
|
| 83 |
+
if robot_factory is not None:
|
| 84 |
+
return robot_factory(cfg, realtime_mode=realtime_mode)
|
| 85 |
+
return Fr3DuoRobot(cfg, mode="hardware", realtime_mode=realtime_mode)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _preview_greeting_safety(
|
| 89 |
+
cfg: RobotConfig, *, max_vel_rad_s: float
|
| 90 |
+
) -> tuple[float, float, int]:
|
| 91 |
+
"""Validates Stage 4 greeting trajectory against table/arm clearance."""
|
| 92 |
+
safety = Fr3DuoSafetyChecker(cfg)
|
| 93 |
+
mj_model = safety.mj_model
|
| 94 |
+
q_left_rest = clamp_q_to_padded_limits(cfg.arms.left.rest_pose_rad).tolist()
|
| 95 |
+
q_right_rest = clamp_q_to_padded_limits(cfg.arms.right.rest_pose_rad).tolist()
|
| 96 |
+
q_left_greet = clamp_q_to_padded_limits(
|
| 97 |
+
[q + dq for q, dq in zip(q_left_rest, GREETING_DELTA_LEFT_RAD)]
|
| 98 |
+
).tolist()
|
| 99 |
+
q_right_greet = clamp_q_to_padded_limits(
|
| 100 |
+
[q + dq for q, dq in zip(q_right_rest, GREETING_DELTA_RIGHT_RAD)]
|
| 101 |
+
).tolist()
|
| 102 |
+
|
| 103 |
+
traj_l_out = generate_quintic_trajectory(
|
| 104 |
+
[q_left_rest, q_left_greet], dt_s=0.001, max_vel_rad_s=max_vel_rad_s
|
| 105 |
+
)
|
| 106 |
+
traj_r_out = generate_quintic_trajectory(
|
| 107 |
+
[q_right_rest, q_right_greet], dt_s=0.001, max_vel_rad_s=max_vel_rad_s
|
| 108 |
+
)
|
| 109 |
+
n_preview = max(len(traj_l_out), len(traj_r_out))
|
| 110 |
+
sample_idx = np.unique(
|
| 111 |
+
np.linspace(0, n_preview - 1, min(16, n_preview), dtype=np.intp)
|
| 112 |
+
)
|
| 113 |
+
min_tcp_z = float("inf")
|
| 114 |
+
min_tcp_dist = float("inf")
|
| 115 |
+
for idx in sample_idx:
|
| 116 |
+
ql = traj_l_out[min(idx, len(traj_l_out) - 1)]
|
| 117 |
+
qr = traj_r_out[min(idx, len(traj_r_out) - 1)]
|
| 118 |
+
pos_l, _ = compute_arm_fk(mj_model, "left", ql)
|
| 119 |
+
pos_r, _ = compute_arm_fk(mj_model, "right", qr)
|
| 120 |
+
min_tcp_z = min(min_tcp_z, float(pos_l[2]), float(pos_r[2]))
|
| 121 |
+
min_tcp_dist = min(min_tcp_dist, float(np.linalg.norm(pos_l - pos_r)))
|
| 122 |
+
|
| 123 |
+
z_table_m = float(cfg.z_table_m)
|
| 124 |
+
min_clearance_m = float(cfg.min_inter_arm_clearance_m)
|
| 125 |
+
if min_tcp_z < z_table_m:
|
| 126 |
+
raise RuntimeError(
|
| 127 |
+
"Stage 4 greeting trajectory dips below z_table_m "
|
| 128 |
+
f"({min_tcp_z:.4f} < {z_table_m:.4f})"
|
| 129 |
+
)
|
| 130 |
+
if min_tcp_dist < min_clearance_m:
|
| 131 |
+
raise RuntimeError(
|
| 132 |
+
f"Stage 4 inter-arm TCP distance {min_tcp_dist:.4f} m < "
|
| 133 |
+
f"{min_clearance_m:.4f} m"
|
| 134 |
+
)
|
| 135 |
+
safety.verify_bimanual_trajectory(traj_l_out, traj_r_out)
|
| 136 |
+
return min_tcp_z, min_tcp_dist, n_preview
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _execute_greeting_with_recording(
|
| 140 |
+
robot: Fr3DuoRobot,
|
| 141 |
+
rig: Fr3DuoCameraController,
|
| 142 |
+
*,
|
| 143 |
+
mp4_path: Path,
|
| 144 |
+
jsonl_path: Path,
|
| 145 |
+
sheet_path: Path,
|
| 146 |
+
fps: float,
|
| 147 |
+
max_speed_deg_s: float,
|
| 148 |
+
) -> tuple[bool, int, int, dict[str, Any]]:
|
| 149 |
+
"""Runs Stage 4 greeting + gripper cycle while recording 4-camera MP4."""
|
| 150 |
+
first_batch = rig.capture_all()
|
| 151 |
+
first_mosaic = render_contact_sheet(first_batch)
|
| 152 |
+
save_rgb_png(first_mosaic, sheet_path)
|
| 153 |
+
writer = open_mp4_writer(
|
| 154 |
+
mp4_path,
|
| 155 |
+
width=int(first_mosaic.shape[1]),
|
| 156 |
+
height=int(first_mosaic.shape[0]),
|
| 157 |
+
fps=fps,
|
| 158 |
+
)
|
| 159 |
+
jsonl_path.parent.mkdir(parents=True, exist_ok=True)
|
| 160 |
+
record_lock = threading.Lock()
|
| 161 |
+
stop_rec = threading.Event()
|
| 162 |
+
current_phase = "pre_motion"
|
| 163 |
+
rec_errors: list[Exception] = []
|
| 164 |
+
frames_written = 0
|
| 165 |
+
motion_frames_written = 0
|
| 166 |
+
aborted = False
|
| 167 |
+
gripper_summary: dict[str, Any] = {}
|
| 168 |
+
|
| 169 |
+
try:
|
| 170 |
+
with jsonl_path.open("w", encoding="utf-8") as log_f:
|
| 171 |
+
|
| 172 |
+
def _write_one_frame(phase_label: str) -> None:
|
| 173 |
+
nonlocal frames_written, motion_frames_written
|
| 174 |
+
batch = rig.capture_all()
|
| 175 |
+
mosaic = render_contact_sheet(batch)
|
| 176 |
+
with record_lock:
|
| 177 |
+
writer.write(np.ascontiguousarray(mosaic[:, :, ::-1]))
|
| 178 |
+
idx_now = frames_written
|
| 179 |
+
frames_written += 1
|
| 180 |
+
if phase_label in (
|
| 181 |
+
"outbound_greeting",
|
| 182 |
+
"gripper_cycle",
|
| 183 |
+
"return_to_rest",
|
| 184 |
+
):
|
| 185 |
+
motion_frames_written += 1
|
| 186 |
+
event = {
|
| 187 |
+
"frame_index": idx_now,
|
| 188 |
+
"phase": phase_label,
|
| 189 |
+
"monotonic_s": round(time.monotonic(), 6),
|
| 190 |
+
}
|
| 191 |
+
log_f.write(json.dumps(event) + "\n")
|
| 192 |
+
|
| 193 |
+
def _recorder_worker() -> None:
|
| 194 |
+
dt_frame = 1.0 / max(1.0, float(fps))
|
| 195 |
+
while not stop_rec.is_set():
|
| 196 |
+
t0 = time.monotonic()
|
| 197 |
+
try:
|
| 198 |
+
_write_one_frame(current_phase)
|
| 199 |
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
| 200 |
+
rec_errors.append(exc)
|
| 201 |
+
break
|
| 202 |
+
wait_s = max(0.0, dt_frame - (time.monotonic() - t0))
|
| 203 |
+
stop_rec.wait(min(wait_s, 0.05))
|
| 204 |
+
|
| 205 |
+
_write_one_frame("pre_motion")
|
| 206 |
+
rec_thread = threading.Thread(
|
| 207 |
+
target=_recorder_worker, name="fr3_stage4_recorder", daemon=True
|
| 208 |
+
)
|
| 209 |
+
rec_thread.start()
|
| 210 |
+
|
| 211 |
+
try:
|
| 212 |
+
st_init = robot.read_state()
|
| 213 |
+
ql_start = clamp_q_to_padded_limits(st_init["left"]["q_rad"]).tolist()
|
| 214 |
+
qr_start = clamp_q_to_padded_limits(st_init["right"]["q_rad"]).tolist()
|
| 215 |
+
ql_mid = clamp_q_to_padded_limits(
|
| 216 |
+
[q + dq for q, dq in zip(ql_start, GREETING_DELTA_LEFT_RAD)]
|
| 217 |
+
).tolist()
|
| 218 |
+
qr_mid = clamp_q_to_padded_limits(
|
| 219 |
+
[q + dq for q, dq in zip(qr_start, GREETING_DELTA_RIGHT_RAD)]
|
| 220 |
+
).tolist()
|
| 221 |
+
|
| 222 |
+
with AbortWatcher() as watcher:
|
| 223 |
+
current_phase = "outbound_greeting"
|
| 224 |
+
out_res = robot.move_bimanual_waypoints(
|
| 225 |
+
[ql_start, ql_mid],
|
| 226 |
+
[qr_start, qr_mid],
|
| 227 |
+
abort_watcher=watcher,
|
| 228 |
+
speed_deg_s=min(max_speed_deg_s, 20.0),
|
| 229 |
+
)
|
| 230 |
+
aborted = bool(out_res.get("aborted", False))
|
| 231 |
+
|
| 232 |
+
if not aborted:
|
| 233 |
+
current_phase = "gripper_cycle"
|
| 234 |
+
robot.activate_grippers()
|
| 235 |
+
for arm in ("left", "right"):
|
| 236 |
+
g_open_0 = robot.move_gripper(arm, 0.0)
|
| 237 |
+
g_closed = robot.move_gripper(arm, 1.0)
|
| 238 |
+
g_open_1 = robot.move_gripper(arm, 0.0)
|
| 239 |
+
gripper_summary[arm] = {
|
| 240 |
+
"open_initial": round(float(g_open_0.position_ratio), 4),
|
| 241 |
+
"closed_ratio": round(float(g_closed.position_ratio), 4),
|
| 242 |
+
"open_final": round(float(g_open_1.position_ratio), 4),
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
current_phase = "return_to_rest"
|
| 246 |
+
ret_res = robot.move_bimanual_waypoints(
|
| 247 |
+
[ql_mid, ql_start],
|
| 248 |
+
[qr_mid, qr_start],
|
| 249 |
+
abort_watcher=watcher,
|
| 250 |
+
speed_deg_s=min(max_speed_deg_s, 20.0),
|
| 251 |
+
)
|
| 252 |
+
aborted = aborted or bool(ret_res.get("aborted", False))
|
| 253 |
+
finally:
|
| 254 |
+
stop_rec.set()
|
| 255 |
+
rec_thread.join(timeout=2.0)
|
| 256 |
+
|
| 257 |
+
if rec_errors:
|
| 258 |
+
raise RuntimeError(
|
| 259 |
+
"Background camera capture failed during Stage 4: "
|
| 260 |
+
f"{rec_errors[0]}"
|
| 261 |
+
) from rec_errors[0]
|
| 262 |
+
_write_one_frame("returned_to_rest")
|
| 263 |
+
finally:
|
| 264 |
+
writer.release()
|
| 265 |
+
|
| 266 |
+
return aborted, frames_written, motion_frames_written, gripper_summary
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def run_hello_world(
|
| 270 |
+
config: RobotConfig | Mapping[str, Any] | None = None,
|
| 271 |
+
*,
|
| 272 |
+
fps: float = 15.0,
|
| 273 |
+
dry_run: bool = False,
|
| 274 |
+
realtime: str = "auto",
|
| 275 |
+
output_dir: Path | None = None,
|
| 276 |
+
output_mp4: Path | None = None,
|
| 277 |
+
output_json: Path | None = None,
|
| 278 |
+
robot_factory: Callable[..., Fr3DuoRobot] | None = None,
|
| 279 |
+
) -> tuple[int, dict[str, Any]]:
|
| 280 |
+
"""Runs Stage 4 offline trajectory preview or live bimanual Hello World."""
|
| 281 |
+
cfg = normalize_robot_config(config)
|
| 282 |
+
effective_dry_run = bool(dry_run)
|
| 283 |
+
rt_info = resolve_realtime_config(
|
| 284 |
+
"auto" if effective_dry_run else realtime
|
| 285 |
+
)
|
| 286 |
+
max_speed_deg_s = float(rt_info.get("max_joint_speed_deg_s", 15.0))
|
| 287 |
+
min_tcp_z, min_tcp_dist, n_preview = _preview_greeting_safety(
|
| 288 |
+
cfg, max_vel_rad_s=math.radians(max_speed_deg_s)
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
resolved_out_dir = resolve_stage_output_dir(
|
| 292 |
+
"stage4", output_dir, dry_run=effective_dry_run
|
| 293 |
+
)
|
| 294 |
+
mode_label = "dry_run" if effective_dry_run else "hardware"
|
| 295 |
+
|
| 296 |
+
if effective_dry_run:
|
| 297 |
+
report: dict[str, Any] = {
|
| 298 |
+
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
|
| 299 |
+
"stage": "stage4_hello_world",
|
| 300 |
+
"mode": mode_label,
|
| 301 |
+
"dry_run": True,
|
| 302 |
+
"min_tcp_z_base_m": round(min_tcp_z, 5),
|
| 303 |
+
"min_inter_arm_tcp_dist_m": round(min_tcp_dist, 5),
|
| 304 |
+
"outbound_steps_1khz": int(n_preview),
|
| 305 |
+
"max_speed_deg_s": max_speed_deg_s,
|
| 306 |
+
}
|
| 307 |
+
json_path = output_json or (
|
| 308 |
+
resolved_out_dir / "stage4_hello_world.json"
|
| 309 |
+
if resolved_out_dir is not None
|
| 310 |
+
else None
|
| 311 |
+
)
|
| 312 |
+
if json_path is not None:
|
| 313 |
+
json_path.parent.mkdir(parents=True, exist_ok=True)
|
| 314 |
+
json_path.write_text(
|
| 315 |
+
json.dumps(report, indent=2) + "\n", encoding="utf-8"
|
| 316 |
+
)
|
| 317 |
+
report["report_path"] = str(json_path)
|
| 318 |
+
print(
|
| 319 |
+
f"[DRY-RUN] Stage 4 FR3 Duo Hello World | "
|
| 320 |
+
f"min_tcp_z={min_tcp_z:.4f} m | min_tcp_dist={min_tcp_dist:.4f} m | "
|
| 321 |
+
f"steps={n_preview}"
|
| 322 |
+
)
|
| 323 |
+
return 0, report
|
| 324 |
+
|
| 325 |
+
if resolved_out_dir is not None:
|
| 326 |
+
base_dir = resolved_out_dir
|
| 327 |
+
elif output_mp4 is not None:
|
| 328 |
+
base_dir = output_mp4.parent
|
| 329 |
+
else:
|
| 330 |
+
base_dir = Path(tempfile.gettempdir()) / "fr3_duo_logs" / "stage4"
|
| 331 |
+
|
| 332 |
+
mp4_path = output_mp4 or (base_dir / "stage4_hello_world.mp4")
|
| 333 |
+
jsonl_path = base_dir / "stage4_hello_world_events.jsonl"
|
| 334 |
+
sheet_path = base_dir / "stage4_contact_sheet.png"
|
| 335 |
+
json_path = output_json or (base_dir / "stage4_hello_world.json")
|
| 336 |
+
|
| 337 |
+
robot = _create_robot(
|
| 338 |
+
cfg, realtime_mode=realtime, robot_factory=robot_factory
|
| 339 |
+
)
|
| 340 |
+
with robot:
|
| 341 |
+
st_init = robot.read_state()
|
| 342 |
+
readiness_warnings: list[str] = []
|
| 343 |
+
for side in ("left", "right"):
|
| 344 |
+
for w in validate_arm_readiness(side, st_init[side]):
|
| 345 |
+
if w not in readiness_warnings:
|
| 346 |
+
readiness_warnings.append(w)
|
| 347 |
+
if readiness_warnings:
|
| 348 |
+
for w in readiness_warnings:
|
| 349 |
+
print(f" WARNING: {w}")
|
| 350 |
+
print(
|
| 351 |
+
"ERROR: Refusing Stage 4 Hello World due to "
|
| 352 |
+
f"{len(readiness_warnings)} preflight warning(s).",
|
| 353 |
+
file=sys.stderr,
|
| 354 |
+
)
|
| 355 |
+
return 2, {
|
| 356 |
+
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
|
| 357 |
+
"stage": "stage4_hello_world",
|
| 358 |
+
"mode": mode_label,
|
| 359 |
+
"dry_run": False,
|
| 360 |
+
"preflight_blocked": True,
|
| 361 |
+
"warnings": readiness_warnings,
|
| 362 |
+
}
|
| 363 |
+
with Fr3DuoCameraController(specs=cfg.cameras, dry_run=False) as rig:
|
| 364 |
+
freshness = rig.check_freshness(
|
| 365 |
+
max_age_s=0.30, num_reads=2, interval_s=0.05
|
| 366 |
+
)
|
| 367 |
+
if not freshness["ok"]:
|
| 368 |
+
raise RuntimeError(
|
| 369 |
+
f"Camera pre-flight failed: {freshness['errors']}"
|
| 370 |
+
)
|
| 371 |
+
aborted, frames_written, motion_frames_written, gripper_summary = (
|
| 372 |
+
_execute_greeting_with_recording(
|
| 373 |
+
robot,
|
| 374 |
+
rig,
|
| 375 |
+
mp4_path=mp4_path,
|
| 376 |
+
jsonl_path=jsonl_path,
|
| 377 |
+
sheet_path=sheet_path,
|
| 378 |
+
fps=fps,
|
| 379 |
+
max_speed_deg_s=max_speed_deg_s,
|
| 380 |
+
)
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
if not mp4_path.is_file() or mp4_path.stat().st_size == 0:
|
| 384 |
+
raise RuntimeError(
|
| 385 |
+
f"Failed to encode valid Stage 4 MP4 video at {mp4_path}"
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
report = {
|
| 389 |
+
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
|
| 390 |
+
"stage": "stage4_hello_world",
|
| 391 |
+
"mode": mode_label,
|
| 392 |
+
"dry_run": False,
|
| 393 |
+
"aborted": aborted,
|
| 394 |
+
"frames_written": frames_written,
|
| 395 |
+
"motion_frames_written": motion_frames_written,
|
| 396 |
+
"mp4_path": str(mp4_path),
|
| 397 |
+
"jsonl_path": str(jsonl_path),
|
| 398 |
+
"contact_sheet_path": str(sheet_path),
|
| 399 |
+
"min_tcp_z_base_m": round(min_tcp_z, 5),
|
| 400 |
+
"min_inter_arm_tcp_dist_m": round(min_tcp_dist, 5),
|
| 401 |
+
"gripper_summary": gripper_summary,
|
| 402 |
+
}
|
| 403 |
+
json_path.parent.mkdir(parents=True, exist_ok=True)
|
| 404 |
+
json_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
| 405 |
+
report["report_path"] = str(json_path)
|
| 406 |
+
|
| 407 |
+
print(
|
| 408 |
+
f"[{mode_label.upper()}] Stage 4 FR3 Duo Hello World | aborted={aborted}"
|
| 409 |
+
f" | frames={frames_written} (motion={motion_frames_written}) | "
|
| 410 |
+
f"mp4={mp4_path}"
|
| 411 |
+
)
|
| 412 |
+
return 0, report
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def _preview_robot_trajectories(
|
| 416 |
+
cfg: RobotConfig,
|
| 417 |
+
*,
|
| 418 |
+
selected_arms: tuple[str, ...],
|
| 419 |
+
eff_mode: str,
|
| 420 |
+
eff_delta_deg: float,
|
| 421 |
+
max_vel_rad_s: float,
|
| 422 |
+
) -> dict[str, Any]:
|
| 423 |
+
"""Runs offline MJCF FK and collision preview for `selected_arms`."""
|
| 424 |
+
safety = Fr3DuoSafetyChecker(cfg)
|
| 425 |
+
mj_model = safety.mj_model
|
| 426 |
+
z_table_m = float(cfg.z_table_m)
|
| 427 |
+
preview: dict[str, Any] = {}
|
| 428 |
+
rest_trajs = {
|
| 429 |
+
side: np.asarray(
|
| 430 |
+
[clamp_q_to_padded_limits(cfg.arms[side].rest_pose_rad).tolist()],
|
| 431 |
+
dtype=np.float64,
|
| 432 |
+
)
|
| 433 |
+
for side in ("left", "right")
|
| 434 |
+
}
|
| 435 |
+
for side in selected_arms:
|
| 436 |
+
q0 = clamp_q_to_padded_limits(cfg.arms[side].rest_pose_rad).tolist()
|
| 437 |
+
q_nudge = _build_nudge_target(q0, eff_delta_deg, side)
|
| 438 |
+
wps = (
|
| 439 |
+
[q0, q_nudge, q0] if eff_mode in ("nudge", "abort-test") else [q0, q0]
|
| 440 |
+
)
|
| 441 |
+
traj = generate_quintic_trajectory(
|
| 442 |
+
wps, dt_s=0.001, max_vel_rad_s=max_vel_rad_s
|
| 443 |
+
)
|
| 444 |
+
sample_idx = np.unique(
|
| 445 |
+
np.linspace(0, len(traj) - 1, min(16, len(traj)), dtype=np.intp)
|
| 446 |
+
)
|
| 447 |
+
min_z = min(
|
| 448 |
+
float(compute_arm_fk(mj_model, side, traj[idx])[0][2])
|
| 449 |
+
for idx in sample_idx
|
| 450 |
+
)
|
| 451 |
+
if min_z < z_table_m:
|
| 452 |
+
raise RuntimeError(
|
| 453 |
+
f"{side} preview trajectory dips below z_table_m "
|
| 454 |
+
f"({min_z:.4f} < {z_table_m:.4f})"
|
| 455 |
+
)
|
| 456 |
+
if side == "left":
|
| 457 |
+
safety.verify_bimanual_trajectory(traj, rest_trajs["right"])
|
| 458 |
+
else:
|
| 459 |
+
safety.verify_bimanual_trajectory(rest_trajs["left"], traj)
|
| 460 |
+
preview[side] = {
|
| 461 |
+
"q_start_rad": [round(float(v), 6) for v in q0],
|
| 462 |
+
"q_peak_rad": [round(float(v), 6) for v in q_nudge],
|
| 463 |
+
"trajectory_steps_1khz": int(len(traj)),
|
| 464 |
+
"min_tcp_z_base_m": round(min_z, 5),
|
| 465 |
+
}
|
| 466 |
+
return preview
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _run_live_robot_mode(
|
| 470 |
+
cfg: RobotConfig,
|
| 471 |
+
robot: Fr3DuoRobot,
|
| 472 |
+
*,
|
| 473 |
+
eff_mode: str,
|
| 474 |
+
arm: str,
|
| 475 |
+
selected_arms: tuple[str, ...],
|
| 476 |
+
eff_delta_deg: float,
|
| 477 |
+
max_speed_deg_s: float,
|
| 478 |
+
st0: Mapping[str, Any],
|
| 479 |
+
results: dict[str, Any],
|
| 480 |
+
warnings_list: list[str],
|
| 481 |
+
) -> None:
|
| 482 |
+
"""Executes one live Stage 3 actuation/homing mode using `robot`."""
|
| 483 |
+
if eff_mode == "gripper":
|
| 484 |
+
robot.activate_grippers()
|
| 485 |
+
for side in selected_arms:
|
| 486 |
+
st_open_1 = robot.move_gripper(side, 0.0)
|
| 487 |
+
st_closed = robot.move_gripper(side, 1.0)
|
| 488 |
+
st_open_2 = robot.move_gripper(side, 0.0)
|
| 489 |
+
excursion = float(st_closed.position_ratio - st_open_1.position_ratio)
|
| 490 |
+
ok_stroke = (
|
| 491 |
+
st_closed.position_ratio >= EMPTY_CLOSE_MIN_RATIO
|
| 492 |
+
and excursion >= 0.50
|
| 493 |
+
)
|
| 494 |
+
if not ok_stroke:
|
| 495 |
+
warnings_list.append(
|
| 496 |
+
f"{side}: gripper stroke below threshold "
|
| 497 |
+
f"(closed={st_closed.position_ratio:.3f})"
|
| 498 |
+
)
|
| 499 |
+
results[side]["gripper_cycle"] = {
|
| 500 |
+
"open_initial": round(float(st_open_1.position_ratio), 4),
|
| 501 |
+
"closed_ratio": round(float(st_closed.position_ratio), 4),
|
| 502 |
+
"open_final": round(float(st_open_2.position_ratio), 4),
|
| 503 |
+
"is_empty_closed": bool(st_closed.is_empty_closed),
|
| 504 |
+
"stroke_ok": ok_stroke,
|
| 505 |
+
}
|
| 506 |
+
return
|
| 507 |
+
|
| 508 |
+
if eff_mode == "nudge":
|
| 509 |
+
with AbortWatcher() as watcher:
|
| 510 |
+
for side in selected_arms:
|
| 511 |
+
q_now = clamp_q_to_padded_limits(
|
| 512 |
+
robot.read_state()[side]["q_rad"]
|
| 513 |
+
).tolist()
|
| 514 |
+
q_peak = _build_nudge_target(q_now, eff_delta_deg, side)
|
| 515 |
+
move_res = robot.move_arm_waypoints(
|
| 516 |
+
side,
|
| 517 |
+
[q_now, q_peak, q_now],
|
| 518 |
+
abort_watcher=watcher,
|
| 519 |
+
speed_deg_s=min(max_speed_deg_s, 15.0),
|
| 520 |
+
)
|
| 521 |
+
results[side]["nudge"] = move_res
|
| 522 |
+
if watcher.aborted:
|
| 523 |
+
break
|
| 524 |
+
return
|
| 525 |
+
|
| 526 |
+
if eff_mode == "abort-test":
|
| 527 |
+
target_arm = selected_arms[0]
|
| 528 |
+
q_now = clamp_q_to_padded_limits(
|
| 529 |
+
robot.read_state()[target_arm]["q_rad"]
|
| 530 |
+
).tolist()
|
| 531 |
+
grip_before = float(robot.read_state()[target_arm]["gripper_ratio"])
|
| 532 |
+
q_far = _build_nudge_target(q_now, eff_delta_deg, target_arm)
|
| 533 |
+
timer: threading.Timer | None = None
|
| 534 |
+
with AbortWatcher() as watcher:
|
| 535 |
+
if not sys.stdin.isatty():
|
| 536 |
+
timer = threading.Timer(
|
| 537 |
+
0.015, watcher.trigger, kwargs={"reason": "auto_abort_test"}
|
| 538 |
+
)
|
| 539 |
+
timer.daemon = True
|
| 540 |
+
timer.start()
|
| 541 |
+
try:
|
| 542 |
+
if sys.stdin.isatty():
|
| 543 |
+
print(
|
| 544 |
+
f" [ACTIVE] Moving {target_arm} arm slowly (10 deg @ 4 deg/s)"
|
| 545 |
+
" — type 'q' + ENTER (or Ctrl+C) now to trigger"
|
| 546 |
+
" abort-and-unwind.",
|
| 547 |
+
flush=True,
|
| 548 |
+
)
|
| 549 |
+
move_res = robot.move_arm_waypoints(
|
| 550 |
+
target_arm,
|
| 551 |
+
[q_now, q_far],
|
| 552 |
+
abort_watcher=watcher,
|
| 553 |
+
speed_deg_s=4.0,
|
| 554 |
+
)
|
| 555 |
+
finally:
|
| 556 |
+
if timer is not None:
|
| 557 |
+
timer.cancel()
|
| 558 |
+
grip_after = float(robot.read_state()[target_arm]["gripper_ratio"])
|
| 559 |
+
results[target_arm]["abort_test"] = {
|
| 560 |
+
**move_res,
|
| 561 |
+
"gripper_preserved": abs(grip_after - grip_before) < 1e-3,
|
| 562 |
+
}
|
| 563 |
+
return
|
| 564 |
+
|
| 565 |
+
if eff_mode == "home":
|
| 566 |
+
speed_cap = min(max_speed_deg_s, 15.0)
|
| 567 |
+
with AbortWatcher() as watcher:
|
| 568 |
+
if arm == "both":
|
| 569 |
+
q_l_now = clamp_q_to_padded_limits(st0["left"]["q_rad"]).tolist()
|
| 570 |
+
q_r_now = clamp_q_to_padded_limits(st0["right"]["q_rad"]).tolist()
|
| 571 |
+
q_l_home = clamp_q_to_padded_limits(
|
| 572 |
+
cfg.arms.left.rest_pose_rad
|
| 573 |
+
).tolist()
|
| 574 |
+
q_r_home = clamp_q_to_padded_limits(
|
| 575 |
+
cfg.arms.right.rest_pose_rad
|
| 576 |
+
).tolist()
|
| 577 |
+
move_res = robot.move_bimanual_waypoints(
|
| 578 |
+
[q_l_now, q_l_home],
|
| 579 |
+
[q_r_now, q_r_home],
|
| 580 |
+
abort_watcher=watcher,
|
| 581 |
+
speed_deg_s=speed_cap,
|
| 582 |
+
)
|
| 583 |
+
results["left"]["home"] = {
|
| 584 |
+
"ok": move_res["ok"],
|
| 585 |
+
"aborted": move_res["aborted"],
|
| 586 |
+
"final_q_rad": move_res["final_left_q_rad"],
|
| 587 |
+
}
|
| 588 |
+
results["right"]["home"] = {
|
| 589 |
+
"ok": move_res["ok"],
|
| 590 |
+
"aborted": move_res["aborted"],
|
| 591 |
+
"final_q_rad": move_res["final_right_q_rad"],
|
| 592 |
+
}
|
| 593 |
+
else:
|
| 594 |
+
side = selected_arms[0]
|
| 595 |
+
q_now = clamp_q_to_padded_limits(st0[side]["q_rad"]).tolist()
|
| 596 |
+
q_home = clamp_q_to_padded_limits(
|
| 597 |
+
cfg.arms[side].rest_pose_rad
|
| 598 |
+
).tolist()
|
| 599 |
+
results[side]["home"] = robot.move_arm_waypoints(
|
| 600 |
+
side, [q_now, q_home], abort_watcher=watcher, speed_deg_s=speed_cap
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def run_robot_check(
|
| 605 |
+
config: RobotConfig | Mapping[str, Any] | None = None,
|
| 606 |
+
*,
|
| 607 |
+
mode: str = "check",
|
| 608 |
+
arm: str = "both",
|
| 609 |
+
delta_deg: float | None = None,
|
| 610 |
+
read_only: bool = False,
|
| 611 |
+
dry_run: bool = False,
|
| 612 |
+
realtime: str = "auto",
|
| 613 |
+
fps: float = 15.0,
|
| 614 |
+
output_dir: Path | None = None,
|
| 615 |
+
output_mp4: Path | None = None,
|
| 616 |
+
output_json: Path | None = None,
|
| 617 |
+
robot_factory: Callable[..., Fr3DuoRobot] | None = None,
|
| 618 |
+
) -> tuple[int, dict[str, Any]]:
|
| 619 |
+
"""Runs Stage 3-4 offline trajectory check or live robot verification."""
|
| 620 |
+
valid_modes = (
|
| 621 |
+
"check",
|
| 622 |
+
"gripper",
|
| 623 |
+
"nudge",
|
| 624 |
+
"abort-test",
|
| 625 |
+
"home",
|
| 626 |
+
"hello-world",
|
| 627 |
+
)
|
| 628 |
+
if mode not in valid_modes:
|
| 629 |
+
raise ValueError(
|
| 630 |
+
f"Invalid check_robot mode={mode!r}; expected one of {valid_modes}"
|
| 631 |
+
)
|
| 632 |
+
if arm not in ("both", "left", "right"):
|
| 633 |
+
raise ValueError(
|
| 634 |
+
f"Invalid arm={arm!r}; expected 'both', 'left', or 'right'"
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
cfg = normalize_robot_config(config)
|
| 638 |
+
eff_mode = "check" if read_only else mode
|
| 639 |
+
effective_dry_run = bool(dry_run or read_only)
|
| 640 |
+
|
| 641 |
+
if eff_mode == "hello-world":
|
| 642 |
+
return run_hello_world(
|
| 643 |
+
cfg,
|
| 644 |
+
fps=fps,
|
| 645 |
+
dry_run=effective_dry_run,
|
| 646 |
+
realtime=realtime,
|
| 647 |
+
output_dir=output_dir,
|
| 648 |
+
output_mp4=output_mp4,
|
| 649 |
+
output_json=output_json,
|
| 650 |
+
robot_factory=robot_factory,
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
rt_info = resolve_realtime_config(
|
| 654 |
+
"auto" if effective_dry_run else realtime
|
| 655 |
+
)
|
| 656 |
+
max_speed_deg_s = float(rt_info.get("max_joint_speed_deg_s", 15.0))
|
| 657 |
+
selected_arms = ("left", "right") if arm == "both" else (arm,)
|
| 658 |
+
eff_delta_deg = (
|
| 659 |
+
float(delta_deg)
|
| 660 |
+
if delta_deg is not None
|
| 661 |
+
else (10.0 if eff_mode == "abort-test" else 5.0)
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
preview = _preview_robot_trajectories(
|
| 665 |
+
cfg,
|
| 666 |
+
selected_arms=selected_arms,
|
| 667 |
+
eff_mode=eff_mode,
|
| 668 |
+
eff_delta_deg=eff_delta_deg,
|
| 669 |
+
max_vel_rad_s=math.radians(max_speed_deg_s),
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
results: dict[str, Any] = {}
|
| 673 |
+
warnings_list: list[str] = []
|
| 674 |
+
preflight_blocked = False
|
| 675 |
+
|
| 676 |
+
if not effective_dry_run:
|
| 677 |
+
robot = _create_robot(
|
| 678 |
+
cfg, realtime_mode=realtime, robot_factory=robot_factory
|
| 679 |
+
)
|
| 680 |
+
with robot:
|
| 681 |
+
st0 = robot.read_state()
|
| 682 |
+
for side in ("left", "right"):
|
| 683 |
+
arm_st = st0[side]
|
| 684 |
+
fk_err_m = float(arm_st.get("fk_pos_error_m", 0.0))
|
| 685 |
+
f_ext_n = float(
|
| 686 |
+
np.linalg.norm(
|
| 687 |
+
np.asarray(arm_st["tau_ext_base_6d"], dtype=np.float64)[:3]
|
| 688 |
+
)
|
| 689 |
+
)
|
| 690 |
+
for w in validate_arm_readiness(side, arm_st):
|
| 691 |
+
if w not in warnings_list:
|
| 692 |
+
warnings_list.append(w)
|
| 693 |
+
results[side] = {
|
| 694 |
+
"initial_fk_pos_error_m": round(fk_err_m, 6),
|
| 695 |
+
"initial_force_norm_n": round(f_ext_n, 3),
|
| 696 |
+
"initial_gripper_ratio": round(float(arm_st["gripper_ratio"]), 4),
|
| 697 |
+
"desk_audit": arm_st.get("desk_audit"),
|
| 698 |
+
}
|
| 699 |
+
|
| 700 |
+
if eff_mode != "check" and warnings_list:
|
| 701 |
+
preflight_blocked = True
|
| 702 |
+
else:
|
| 703 |
+
_run_live_robot_mode(
|
| 704 |
+
cfg,
|
| 705 |
+
robot,
|
| 706 |
+
eff_mode=eff_mode,
|
| 707 |
+
arm=arm,
|
| 708 |
+
selected_arms=selected_arms,
|
| 709 |
+
eff_delta_deg=eff_delta_deg,
|
| 710 |
+
max_speed_deg_s=max_speed_deg_s,
|
| 711 |
+
st0=st0,
|
| 712 |
+
results=results,
|
| 713 |
+
warnings_list=warnings_list,
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
mode_label = "dry_run" if effective_dry_run else "hardware"
|
| 717 |
+
report: dict[str, Any] = {
|
| 718 |
+
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
|
| 719 |
+
"stage": "stage3_check_robot",
|
| 720 |
+
"check_mode": eff_mode,
|
| 721 |
+
"execution_mode": mode_label,
|
| 722 |
+
"dry_run": effective_dry_run,
|
| 723 |
+
"preflight_blocked": preflight_blocked,
|
| 724 |
+
"realtime_profile": rt_info,
|
| 725 |
+
"preview": preview,
|
| 726 |
+
"results": results,
|
| 727 |
+
"warnings": warnings_list,
|
| 728 |
+
}
|
| 729 |
+
|
| 730 |
+
resolved_out_dir = resolve_stage_output_dir(
|
| 731 |
+
"stage3", output_dir, dry_run=effective_dry_run
|
| 732 |
+
)
|
| 733 |
+
json_path = output_json or (
|
| 734 |
+
resolved_out_dir / f"check_robot_{eff_mode}.json"
|
| 735 |
+
if resolved_out_dir is not None
|
| 736 |
+
else None
|
| 737 |
+
)
|
| 738 |
+
if json_path is not None:
|
| 739 |
+
json_path.parent.mkdir(parents=True, exist_ok=True)
|
| 740 |
+
json_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
| 741 |
+
report["report_path"] = str(json_path)
|
| 742 |
+
|
| 743 |
+
tag = "[DRY-RUN]" if effective_dry_run else "[HARDWARE]"
|
| 744 |
+
print(
|
| 745 |
+
f"{tag} Stage 3 Robot Check (mode={eff_mode}, arms={list(selected_arms)})"
|
| 746 |
+
f" | max_speed={max_speed_deg_s:.1f} deg/s | "
|
| 747 |
+
f"warnings={len(warnings_list)}"
|
| 748 |
+
)
|
| 749 |
+
for warning in warnings_list:
|
| 750 |
+
print(f" WARNING: {warning}")
|
| 751 |
+
if preflight_blocked:
|
| 752 |
+
print(
|
| 753 |
+
f"ERROR: Refusing Stage 3 hardware actuation ({eff_mode}) due to "
|
| 754 |
+
f"{len(warnings_list)} preflight warning(s).",
|
| 755 |
+
file=sys.stderr,
|
| 756 |
+
)
|
| 757 |
+
return 2, report
|
| 758 |
+
if eff_mode == "gripper" and any(
|
| 759 |
+
not (results.get(side, {}).get("gripper_cycle") or {}).get(
|
| 760 |
+
"stroke_ok", True
|
| 761 |
+
)
|
| 762 |
+
for side in selected_arms
|
| 763 |
+
):
|
| 764 |
+
return 1, report
|
| 765 |
+
return 0, report
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/discover_hardware.py
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Stage 1 read-only hardware discovery and FK cross-check for FR3 Duo."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from collections.abc import Callable, Mapping, Sequence
|
| 20 |
+
from datetime import datetime, timezone
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
import sys
|
| 25 |
+
from typing import Any
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
from fr3_arm_controller import probe_arm_readonly
|
| 30 |
+
from fr3_arm_controller import tcp_port_reachable
|
| 31 |
+
from fr3_camera_controller import (
|
| 32 |
+
V4L2Camera,
|
| 33 |
+
check_linux_usb_permissions,
|
| 34 |
+
discover_uvc_devices,
|
| 35 |
+
require_cv2,
|
| 36 |
+
resolve_zed_conf_path,
|
| 37 |
+
)
|
| 38 |
+
from fr3_config import (
|
| 39 |
+
RobotConfig,
|
| 40 |
+
detect_preempt_rt,
|
| 41 |
+
normalize_robot_config,
|
| 42 |
+
resolve_realtime_config,
|
| 43 |
+
resolve_stage_output_dir,
|
| 44 |
+
save_rgb_png,
|
| 45 |
+
save_robot_config,
|
| 46 |
+
)
|
| 47 |
+
from fr3_kinematics import compute_arm_fk
|
| 48 |
+
from fr3_mjcf import (
|
| 49 |
+
build_fr3_duo_mjcf,
|
| 50 |
+
find_menagerie_dir,
|
| 51 |
+
)
|
| 52 |
+
from robotiq_gripper_controller import (
|
| 53 |
+
resolve_serial_ports,
|
| 54 |
+
select_gripper_ports,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _capture_wrist_preview_png(
|
| 59 |
+
cfg: RobotConfig, preview_path: Path
|
| 60 |
+
) -> Path | None:
|
| 61 |
+
"""Grabs a side-by-side 1-frame preview of wrist_camera_left/right."""
|
| 62 |
+
tiles: list[np.ndarray] = []
|
| 63 |
+
try:
|
| 64 |
+
cv2 = require_cv2()
|
| 65 |
+
except RuntimeError:
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
for role, label_prefix in (
|
| 69 |
+
("wrist_camera_left", "A / wrist_camera_left"),
|
| 70 |
+
("wrist_camera_right", "B / wrist_camera_right"),
|
| 71 |
+
):
|
| 72 |
+
spec = cfg.cameras[role]
|
| 73 |
+
frame_rgb: np.ndarray | None = None
|
| 74 |
+
try:
|
| 75 |
+
cam = V4L2Camera(spec, spec.width, spec.height)
|
| 76 |
+
try:
|
| 77 |
+
frame_rgb, _ = cam.capture_rgb()
|
| 78 |
+
finally:
|
| 79 |
+
cam.close()
|
| 80 |
+
except (RuntimeError, OSError, ValueError, KeyError):
|
| 81 |
+
frame_rgb = None
|
| 82 |
+
if frame_rgb is None:
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
tile = cv2.resize(frame_rgb, (640, 360), interpolation=cv2.INTER_AREA)
|
| 86 |
+
banner_h = 28
|
| 87 |
+
tile[:banner_h] = (tile[:banner_h].astype(np.uint16) // 4).astype(np.uint8)
|
| 88 |
+
ser_tag = f"serial={spec.serial}" if spec.serial else spec.device_path
|
| 89 |
+
cv2.putText(
|
| 90 |
+
tile,
|
| 91 |
+
f"{label_prefix} ({ser_tag})",
|
| 92 |
+
(10, banner_h - 7),
|
| 93 |
+
cv2.FONT_HERSHEY_SIMPLEX,
|
| 94 |
+
0.55,
|
| 95 |
+
(245, 248, 255),
|
| 96 |
+
1,
|
| 97 |
+
cv2.LINE_AA,
|
| 98 |
+
)
|
| 99 |
+
tiles.append(tile)
|
| 100 |
+
|
| 101 |
+
mosaic = np.ascontiguousarray(np.concatenate(tiles, axis=1))
|
| 102 |
+
save_rgb_png(mosaic, preview_path)
|
| 103 |
+
return preview_path
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _confirm_wrist_camera_mapping(
|
| 107 |
+
cfg: RobotConfig,
|
| 108 |
+
*,
|
| 109 |
+
preview_dir: Path,
|
| 110 |
+
input_fn: Callable[[str], str],
|
| 111 |
+
) -> bool:
|
| 112 |
+
"""Prompts operator to confirm or swap unhinted left/right wrist cameras."""
|
| 113 |
+
wl = cfg.cameras.wrist_camera_left
|
| 114 |
+
wr = cfg.cameras.wrist_camera_right
|
| 115 |
+
preview_file = _capture_wrist_preview_png(
|
| 116 |
+
cfg, preview_dir / "wrist_camera_preview.png"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
print("\nAuto-bound RealSense wrist cameras without udev/config mapping:")
|
| 120 |
+
print(
|
| 121 |
+
f" [A] wrist_camera_left : serial={wl.serial or 'n/a'} "
|
| 122 |
+
f"({wl.device_path or 'n/a'})"
|
| 123 |
+
)
|
| 124 |
+
print(
|
| 125 |
+
f" [B] wrist_camera_right: serial={wr.serial or 'n/a'} "
|
| 126 |
+
f"({wr.device_path or 'n/a'})"
|
| 127 |
+
)
|
| 128 |
+
if preview_file is not None:
|
| 129 |
+
print(f" Preview image: {preview_file}")
|
| 130 |
+
|
| 131 |
+
reply = input_fn(
|
| 132 |
+
"Confirm left/right wrist mapping ([K]eep A=left/B=right, or [s]wap): "
|
| 133 |
+
)
|
| 134 |
+
if reply.strip().lower() in ("s", "swap"):
|
| 135 |
+
wl.serial, wr.serial = wr.serial, wl.serial
|
| 136 |
+
wl.device_path, wr.device_path = wr.device_path, wl.device_path
|
| 137 |
+
print(
|
| 138 |
+
" Swapped wrist cameras -> "
|
| 139 |
+
f"left={wl.serial or wl.device_path}, "
|
| 140 |
+
f"right={wr.serial or wr.device_path}"
|
| 141 |
+
)
|
| 142 |
+
return True
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _discover_grippers(
|
| 146 |
+
cfg: RobotConfig, *, rediscover: bool
|
| 147 |
+
) -> tuple[list[dict[str, Any]], dict[str, Any], list[dict[str, Any]]]:
|
| 148 |
+
"""Resolves Robotiq serial ports or reuses valid configured paths."""
|
| 149 |
+
has_configured = bool(
|
| 150 |
+
not rediscover
|
| 151 |
+
and cfg.arms.left.gripper_port
|
| 152 |
+
and cfg.arms.right.gripper_port
|
| 153 |
+
and os.path.exists(cfg.arms.left.gripper_port)
|
| 154 |
+
and os.path.exists(cfg.arms.right.gripper_port)
|
| 155 |
+
)
|
| 156 |
+
if not has_configured:
|
| 157 |
+
serial_ports = resolve_serial_ports()
|
| 158 |
+
cfg_grippers = {
|
| 159 |
+
"left": cfg.arms.left.gripper_port,
|
| 160 |
+
"right": cfg.arms.right.gripper_port,
|
| 161 |
+
}
|
| 162 |
+
return serial_ports, select_gripper_ports(serial_ports, cfg_grippers), (
|
| 163 |
+
serial_ports
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
selection: dict[str, Any] = {
|
| 167 |
+
"left": cfg.arms.left.gripper_port,
|
| 168 |
+
"right": cfg.arms.right.gripper_port,
|
| 169 |
+
"warnings": [],
|
| 170 |
+
"advisories": [],
|
| 171 |
+
}
|
| 172 |
+
perm_nodes = [
|
| 173 |
+
{
|
| 174 |
+
"path": port,
|
| 175 |
+
"resolved_path": os.path.realpath(port),
|
| 176 |
+
"device_role_hint": "robotiq_rs485",
|
| 177 |
+
"serial_rw_ok": os.access(port, os.R_OK | os.W_OK),
|
| 178 |
+
}
|
| 179 |
+
for port in (cfg.arms.left.gripper_port, cfg.arms.right.gripper_port)
|
| 180 |
+
if port
|
| 181 |
+
]
|
| 182 |
+
return [], selection, perm_nodes
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _discover_cameras(
|
| 186 |
+
cfg: RobotConfig, *, rediscover: bool
|
| 187 |
+
) -> list[dict[str, Any]]:
|
| 188 |
+
"""Discovers UVC devices or reuses valid configured camera paths."""
|
| 189 |
+
configured_cams = cfg.cameras.as_spec_map()
|
| 190 |
+
has_configured = bool(
|
| 191 |
+
not rediscover
|
| 192 |
+
and all(
|
| 193 |
+
sp.device_path and os.path.exists(sp.device_path)
|
| 194 |
+
for sp in configured_cams.values()
|
| 195 |
+
)
|
| 196 |
+
)
|
| 197 |
+
if not has_configured:
|
| 198 |
+
return discover_uvc_devices()
|
| 199 |
+
|
| 200 |
+
return [
|
| 201 |
+
{
|
| 202 |
+
"name": role,
|
| 203 |
+
"family": "zed" if role == "head_stereo" else "realsense",
|
| 204 |
+
"device_path": sp.device_path,
|
| 205 |
+
"video_node": os.path.realpath(sp.device_path),
|
| 206 |
+
"serial": sp.serial,
|
| 207 |
+
"v4l2_rw_ok": os.access(sp.device_path, os.R_OK | os.W_OK),
|
| 208 |
+
}
|
| 209 |
+
for role, sp in configured_cams.items()
|
| 210 |
+
]
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _collect_hardware_device_labels(
|
| 214 |
+
serial_nodes: Sequence[Mapping[str, Any]],
|
| 215 |
+
uvc_devices: Sequence[Mapping[str, Any]],
|
| 216 |
+
) -> dict[str, str]:
|
| 217 |
+
"""Maps resolved `/dev/...` paths for discovered hardware to display labels."""
|
| 218 |
+
dev_labels: dict[str, str] = {}
|
| 219 |
+
for sp in serial_nodes:
|
| 220 |
+
raw = str(sp.get("path") or "").strip()
|
| 221 |
+
resolved = str(sp.get("resolved_path") or raw).strip()
|
| 222 |
+
role = str(sp.get("device_role_hint") or "serial_port")
|
| 223 |
+
for cand in (raw, resolved):
|
| 224 |
+
if cand:
|
| 225 |
+
key = os.path.realpath(cand)
|
| 226 |
+
dev_labels.setdefault(key, f"serial port {raw or resolved} ({role})")
|
| 227 |
+
|
| 228 |
+
for dev in uvc_devices:
|
| 229 |
+
raw = str(dev.get("device_path") or "").strip()
|
| 230 |
+
vnode = str(dev.get("video_node") or raw).strip()
|
| 231 |
+
fam = str(dev.get("family") or "uvc").upper()
|
| 232 |
+
for cand in (raw, vnode):
|
| 233 |
+
if cand:
|
| 234 |
+
key = os.path.realpath(cand)
|
| 235 |
+
dev_labels.setdefault(key, f"{fam} camera {vnode or raw}")
|
| 236 |
+
return dev_labels
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def find_conflicting_hardware_processes(
|
| 240 |
+
serial_nodes: Sequence[Mapping[str, Any]],
|
| 241 |
+
uvc_devices: Sequence[Mapping[str, Any]],
|
| 242 |
+
*,
|
| 243 |
+
proc_root: Path = Path("/proc"),
|
| 244 |
+
own_pid: int | None = None,
|
| 245 |
+
) -> list[dict[str, Any]]:
|
| 246 |
+
"""Finds other Linux processes holding open FDs on robot serial/V4L2 nodes."""
|
| 247 |
+
dev_labels = _collect_hardware_device_labels(serial_nodes, uvc_devices)
|
| 248 |
+
if not dev_labels or not proc_root.is_dir():
|
| 249 |
+
return []
|
| 250 |
+
|
| 251 |
+
self_pid = os.getpid() if own_pid is None else int(own_pid)
|
| 252 |
+
conflicts: list[dict[str, Any]] = []
|
| 253 |
+
seen: set[tuple[int, str]] = set()
|
| 254 |
+
try:
|
| 255 |
+
proc_entries = sorted(proc_root.iterdir(), key=lambda p: p.name)
|
| 256 |
+
except OSError:
|
| 257 |
+
return []
|
| 258 |
+
|
| 259 |
+
for pid_dir in proc_entries:
|
| 260 |
+
if not pid_dir.name.isdigit():
|
| 261 |
+
continue
|
| 262 |
+
pid = int(pid_dir.name)
|
| 263 |
+
if pid == self_pid:
|
| 264 |
+
continue
|
| 265 |
+
fd_dir = pid_dir / "fd"
|
| 266 |
+
try:
|
| 267 |
+
fd_entries = list(fd_dir.iterdir())
|
| 268 |
+
except OSError:
|
| 269 |
+
continue
|
| 270 |
+
|
| 271 |
+
comm: str | None = None
|
| 272 |
+
for fd_link in fd_entries:
|
| 273 |
+
try:
|
| 274 |
+
target = os.readlink(fd_link)
|
| 275 |
+
except OSError:
|
| 276 |
+
continue
|
| 277 |
+
if not target.startswith("/dev/"):
|
| 278 |
+
continue
|
| 279 |
+
norm_target = os.path.realpath(target)
|
| 280 |
+
label = dev_labels.get(norm_target) or dev_labels.get(target)
|
| 281 |
+
if label is None:
|
| 282 |
+
continue
|
| 283 |
+
key = (pid, norm_target)
|
| 284 |
+
if key in seen:
|
| 285 |
+
continue
|
| 286 |
+
seen.add(key)
|
| 287 |
+
if comm is None:
|
| 288 |
+
try:
|
| 289 |
+
comm = (
|
| 290 |
+
(pid_dir / "comm").read_text(encoding="utf-8").strip()
|
| 291 |
+
or "unknown"
|
| 292 |
+
)
|
| 293 |
+
except OSError:
|
| 294 |
+
comm = "unknown"
|
| 295 |
+
conflicts.append({
|
| 296 |
+
"pid": pid,
|
| 297 |
+
"process": comm,
|
| 298 |
+
"device_path": norm_target,
|
| 299 |
+
"device_label": label,
|
| 300 |
+
})
|
| 301 |
+
return conflicts
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _append_usb_permission_warnings(
|
| 305 |
+
usb_permissions: Mapping[str, Any],
|
| 306 |
+
uvc_devices: list[dict[str, Any]],
|
| 307 |
+
warnings_list: list[str],
|
| 308 |
+
) -> None:
|
| 309 |
+
"""Appends human-actionable dialout/video R/W permission warnings."""
|
| 310 |
+
serial_issues = usb_permissions.get("serial_access_issues") or []
|
| 311 |
+
if serial_issues:
|
| 312 |
+
issue_paths = ", ".join(
|
| 313 |
+
str(s.get("path") or s.get("resolved_path") or "unknown")
|
| 314 |
+
for s in serial_issues
|
| 315 |
+
)
|
| 316 |
+
if not usb_permissions.get("in_dialout_group", False):
|
| 317 |
+
warnings_list.append(
|
| 318 |
+
f"Serial port(s) ({issue_paths}) lack R/W permission and user is "
|
| 319 |
+
"not in 'dialout' group. Run: "
|
| 320 |
+
'sudo usermod -aG video,dialout "$USER"'
|
| 321 |
+
)
|
| 322 |
+
else:
|
| 323 |
+
warnings_list.append(
|
| 324 |
+
f"Serial port(s) ({issue_paths}) lack R/W permission."
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
v4l2_issues = usb_permissions.get("v4l2_access_issues") or []
|
| 328 |
+
if uvc_devices and v4l2_issues:
|
| 329 |
+
issue_paths = ", ".join(
|
| 330 |
+
str(d.get("video_node") or d.get("device_path") or "unknown")
|
| 331 |
+
for d in v4l2_issues
|
| 332 |
+
)
|
| 333 |
+
if not usb_permissions.get("in_video_group", False):
|
| 334 |
+
warnings_list.append(
|
| 335 |
+
f"V4L2 camera node(s) ({issue_paths}) lack R/W permission and user "
|
| 336 |
+
"is not in 'video' group. Run: "
|
| 337 |
+
'sudo usermod -aG video,dialout "$USER"'
|
| 338 |
+
)
|
| 339 |
+
else:
|
| 340 |
+
warnings_list.append(
|
| 341 |
+
f"V4L2 camera node(s) ({issue_paths}) lack R/W permission."
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def _auto_bind_devices(
|
| 346 |
+
cfg: RobotConfig,
|
| 347 |
+
gripper_selection: Mapping[str, Any],
|
| 348 |
+
uvc_devices: list[dict[str, Any]],
|
| 349 |
+
) -> list[str]:
|
| 350 |
+
"""Auto-binds discovered gripper ports, ZED stereo, and D405 wrists."""
|
| 351 |
+
for side in ("left", "right"):
|
| 352 |
+
arm_cfg = cfg.arms[side]
|
| 353 |
+
if not arm_cfg.gripper_port and gripper_selection.get(side):
|
| 354 |
+
arm_cfg.gripper_port = str(gripper_selection[side])
|
| 355 |
+
|
| 356 |
+
zed_cams = [d for d in uvc_devices if d.get("family") == "zed"]
|
| 357 |
+
if zed_cams:
|
| 358 |
+
zed = zed_cams[0]
|
| 359 |
+
z_ser = str(zed.get("serial") or "")
|
| 360 |
+
z_dev = str(zed.get("device_path") or zed.get("video_node") or "")
|
| 361 |
+
search_dirs = [cfg.zed_settings_dir]
|
| 362 |
+
found_conf = resolve_zed_conf_path(serial=z_ser, search_dirs=search_dirs)
|
| 363 |
+
if found_conf is None and (not z_ser or not z_ser.isdigit()):
|
| 364 |
+
found_conf = resolve_zed_conf_path(serial="", search_dirs=search_dirs)
|
| 365 |
+
if found_conf is not None and (not z_ser or z_ser.upper() == "OV580"):
|
| 366 |
+
conf_stem = found_conf.stem
|
| 367 |
+
if conf_stem.lower().startswith("sn") and len(conf_stem) > 2:
|
| 368 |
+
z_ser = conf_stem[2:]
|
| 369 |
+
for d in uvc_devices:
|
| 370 |
+
if d.get("family") == "zed" and not d.get("serial"):
|
| 371 |
+
d["serial"] = z_ser
|
| 372 |
+
head_cfg = cfg.cameras.head_stereo
|
| 373 |
+
if not head_cfg.serial and z_ser:
|
| 374 |
+
head_cfg.serial = z_ser
|
| 375 |
+
if not head_cfg.device_path and z_dev:
|
| 376 |
+
head_cfg.device_path = z_dev
|
| 377 |
+
if found_conf and not head_cfg.zed_conf_path:
|
| 378 |
+
head_cfg.zed_conf_path = str(found_conf)
|
| 379 |
+
|
| 380 |
+
unique_rs = sorted(
|
| 381 |
+
(d for d in uvc_devices if d.get("family") == "realsense"),
|
| 382 |
+
key=lambda d: (
|
| 383 |
+
str(d.get("serial") or ""),
|
| 384 |
+
str(d.get("device_path") or d.get("video_node") or ""),
|
| 385 |
+
),
|
| 386 |
+
)
|
| 387 |
+
assigned_rs_indices: set[int] = set()
|
| 388 |
+
for side in ("left", "right"):
|
| 389 |
+
w_cfg = cfg.cameras[f"wrist_camera_{side}"]
|
| 390 |
+
matched_idx: int | None = None
|
| 391 |
+
if w_cfg.serial:
|
| 392 |
+
for idx, d in enumerate(unique_rs):
|
| 393 |
+
if idx not in assigned_rs_indices and d.get("serial") == w_cfg.serial:
|
| 394 |
+
matched_idx = idx
|
| 395 |
+
break
|
| 396 |
+
if matched_idx is None:
|
| 397 |
+
hint_matches = [
|
| 398 |
+
idx
|
| 399 |
+
for idx, d in enumerate(unique_rs)
|
| 400 |
+
if idx not in assigned_rs_indices and d.get("side_hint") == side
|
| 401 |
+
]
|
| 402 |
+
if len(hint_matches) == 1:
|
| 403 |
+
matched_idx = hint_matches[0]
|
| 404 |
+
if matched_idx is not None:
|
| 405 |
+
assigned_rs_indices.add(matched_idx)
|
| 406 |
+
rs = unique_rs[matched_idx]
|
| 407 |
+
if not w_cfg.serial and rs.get("serial"):
|
| 408 |
+
w_cfg.serial = str(rs["serial"])
|
| 409 |
+
dev_cand = rs.get("device_path") or rs.get("video_node")
|
| 410 |
+
if not w_cfg.device_path and dev_cand:
|
| 411 |
+
w_cfg.device_path = str(dev_cand)
|
| 412 |
+
|
| 413 |
+
auto_bound_wrists: list[str] = []
|
| 414 |
+
for side in ("left", "right"):
|
| 415 |
+
w_cfg = cfg.cameras[f"wrist_camera_{side}"]
|
| 416 |
+
if w_cfg.serial or w_cfg.device_path:
|
| 417 |
+
continue
|
| 418 |
+
next_idx = next(
|
| 419 |
+
(
|
| 420 |
+
idx
|
| 421 |
+
for idx in range(len(unique_rs))
|
| 422 |
+
if idx not in assigned_rs_indices
|
| 423 |
+
),
|
| 424 |
+
None,
|
| 425 |
+
)
|
| 426 |
+
if next_idx is not None:
|
| 427 |
+
assigned_rs_indices.add(next_idx)
|
| 428 |
+
rs = unique_rs[next_idx]
|
| 429 |
+
if rs.get("serial"):
|
| 430 |
+
w_cfg.serial = str(rs["serial"])
|
| 431 |
+
dev_cand = rs.get("device_path") or rs.get("video_node")
|
| 432 |
+
if dev_cand:
|
| 433 |
+
w_cfg.device_path = str(dev_cand)
|
| 434 |
+
auto_bound_wrists.append(
|
| 435 |
+
f"wrist_camera_{side}=serial:{w_cfg.serial or 'n/a'} "
|
| 436 |
+
f"({w_cfg.device_path or 'n/a'})"
|
| 437 |
+
)
|
| 438 |
+
return auto_bound_wrists
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def _print_discovery_summary(
|
| 442 |
+
*,
|
| 443 |
+
cfg: RobotConfig,
|
| 444 |
+
report: Mapping[str, Any],
|
| 445 |
+
menagerie_path: Path | None,
|
| 446 |
+
) -> None:
|
| 447 |
+
"""Prints concise human-readable Stage 1 discovery telemetry."""
|
| 448 |
+
is_preempt_rt = bool(report["preempt_rt_detected"])
|
| 449 |
+
rt_profile = report["realtime_profile"]
|
| 450 |
+
rt_summary = (
|
| 451 |
+
f"realtime={rt_profile.get('realtime_config', 'kEnforce')} "
|
| 452 |
+
"(PREEMPT_RT=True)"
|
| 453 |
+
if is_preempt_rt
|
| 454 |
+
else "realtime=kIgnore (PREEMPT_RT=False, non-RT OK)"
|
| 455 |
+
)
|
| 456 |
+
model_src = "menagerie"
|
| 457 |
+
serial_ports = report["serial_ports"]
|
| 458 |
+
uvc_devices = report["uvc_devices"]
|
| 459 |
+
print(
|
| 460 |
+
f"[{str(report['mode']).upper()}] Stage 1 FR3 Duo Discovery | "
|
| 461 |
+
f"model={model_src} | {rt_summary} | "
|
| 462 |
+
f"serial_ports={len(serial_ports)} | uvc_devices={len(uvc_devices)} | "
|
| 463 |
+
f"menagerie={menagerie_path is not None}"
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
arm_readout = report["arm_readout"]
|
| 467 |
+
fci_reachability = report["fci_targets"]
|
| 468 |
+
for arm in ("left", "right"):
|
| 469 |
+
rd = arm_readout[arm]
|
| 470 |
+
fci_info = fci_reachability.get(arm, {})
|
| 471 |
+
fci_reach = bool(fci_info.get("tcp_1337_reachable"))
|
| 472 |
+
fci_str = (
|
| 473 |
+
f"ip={fci_info.get('ip')} "
|
| 474 |
+
f"(tcp_1337={'reachable' if fci_reach else 'UNREACHABLE'})"
|
| 475 |
+
)
|
| 476 |
+
if rd.get("connected") is False:
|
| 477 |
+
print(
|
| 478 |
+
f" {arm:5s}: {fci_str} | status=NOT_CONNECTED | "
|
| 479 |
+
f"nominal_tcp_base={rd['tcp_pos_base_m']} m"
|
| 480 |
+
)
|
| 481 |
+
continue
|
| 482 |
+
da = rd.get("desk_audit") or {}
|
| 483 |
+
da_str = ""
|
| 484 |
+
if da.get("checked"):
|
| 485 |
+
da_str = (
|
| 486 |
+
f" | mode={da.get('robot_mode')} | m_total={da.get('m_total_kg')} "
|
| 487 |
+
f"kg | grav_err={da.get('gravity_angle_err_deg')} deg | "
|
| 488 |
+
f"fci_f_ext={da.get('fci_ext_force_norm_n')} N"
|
| 489 |
+
)
|
| 490 |
+
print(
|
| 491 |
+
f" {arm:5s}: {fci_str} | tcp_base={rd['tcp_pos_base_m']} m | "
|
| 492 |
+
f"fk_err={rd['fk_pos_error_m'] * 1000.0:.2f} mm | "
|
| 493 |
+
f"|f_ext|={rd['free_air_force_norm_n']:.2f} N{da_str}"
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
for idx, sp in enumerate(serial_ports):
|
| 497 |
+
role = str(sp.get("device_role_hint", "unknown_serial"))
|
| 498 |
+
path = str(sp.get("path", ""))
|
| 499 |
+
rpath = str(sp.get("resolved_path", path))
|
| 500 |
+
ser = str(sp.get("serial") or "n/a")
|
| 501 |
+
vid_pid = (
|
| 502 |
+
f"{sp.get('vendor_id')}:{sp.get('product_id')}"
|
| 503 |
+
if sp.get("vendor_id") and sp.get("product_id")
|
| 504 |
+
else "n/a"
|
| 505 |
+
)
|
| 506 |
+
side_str = f" side={sp['side_hint']}" if sp.get("side_hint") else ""
|
| 507 |
+
lat_str = (
|
| 508 |
+
f" latency={sp['latency_timer_ms']}ms"
|
| 509 |
+
if sp.get("latency_timer_ms") is not None
|
| 510 |
+
else ""
|
| 511 |
+
)
|
| 512 |
+
target_str = f" -> {rpath}" if rpath and rpath != path else ""
|
| 513 |
+
print(
|
| 514 |
+
f" serial[{idx}]: [{role}] {path}{target_str} | "
|
| 515 |
+
f"usb={vid_pid} serial={ser}{side_str}{lat_str}"
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
for idx, dev in enumerate(uvc_devices):
|
| 519 |
+
fam = str(dev.get("family", "uvc")).upper()
|
| 520 |
+
name = str(dev.get("name", "unknown"))
|
| 521 |
+
ser = str(dev.get("serial") or "n/a")
|
| 522 |
+
vnode = str(dev.get("video_node") or dev.get("device_path") or "n/a")
|
| 523 |
+
dpath = str(dev.get("device_path") or vnode)
|
| 524 |
+
speed = float(dev.get("usb_speed_mbps") or 0.0)
|
| 525 |
+
side_str = f" side={dev['side_hint']}" if dev.get("side_hint") else ""
|
| 526 |
+
speed_str = f" {speed:.0f}Mbps" if speed > 0 else ""
|
| 527 |
+
path_str = f" ({dpath})" if dpath and dpath != vnode else ""
|
| 528 |
+
print(
|
| 529 |
+
f" camera[{idx}]: [{fam}] {name} | serial={ser} | "
|
| 530 |
+
f"node={vnode}{path_str}{speed_str}{side_str}"
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
wrote_cfg_path = report.get("wrote_config")
|
| 534 |
+
if wrote_cfg_path is not None:
|
| 535 |
+
hs = cfg.cameras.head_stereo
|
| 536 |
+
wl = cfg.cameras.wrist_camera_left
|
| 537 |
+
wr = cfg.cameras.wrist_camera_right
|
| 538 |
+
gl = cfg.arms.left.gripper_port or "n/a"
|
| 539 |
+
gr = cfg.arms.right.gripper_port or "n/a"
|
| 540 |
+
print(
|
| 541 |
+
f" config : wrote {wrote_cfg_path} | "
|
| 542 |
+
f"head_stereo={hs.serial or 'n/a'} ({hs.device_path or 'n/a'}) | "
|
| 543 |
+
f"wrist_left={wl.serial or 'n/a'} ({wl.device_path or 'n/a'}) | "
|
| 544 |
+
f"wrist_right={wr.serial or 'n/a'} ({wr.device_path or 'n/a'}) | "
|
| 545 |
+
f"grippers=left:{gl}, right:{gr}"
|
| 546 |
+
)
|
| 547 |
+
for warning in report["warnings"]:
|
| 548 |
+
print(f" WARNING: {warning}")
|
| 549 |
+
for advisory in report["advisories"]:
|
| 550 |
+
print(f" ADVISORY: {advisory}")
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def run_discovery(
|
| 554 |
+
config: RobotConfig | Mapping[str, Any] | None = None,
|
| 555 |
+
*,
|
| 556 |
+
output_dir: Path | None = None,
|
| 557 |
+
output_json: Path | None = None,
|
| 558 |
+
write_config: Path | None = None,
|
| 559 |
+
read_only: bool = False,
|
| 560 |
+
realtime: str = "auto",
|
| 561 |
+
ping_timeout_sec: float = 0.25,
|
| 562 |
+
strict_preflight: bool = False,
|
| 563 |
+
rediscover: bool = False,
|
| 564 |
+
yes: bool = False,
|
| 565 |
+
input_fn: Callable[[str], str] | None = None,
|
| 566 |
+
) -> tuple[int, dict[str, Any]]:
|
| 567 |
+
"""Runs Stage 1 read-only hardware discovery and returns `(rc, report)`."""
|
| 568 |
+
cfg = normalize_robot_config(config)
|
| 569 |
+
is_preempt_rt = detect_preempt_rt()
|
| 570 |
+
realtime_error: str | None = None
|
| 571 |
+
try:
|
| 572 |
+
rt_profile = resolve_realtime_config(realtime, is_preempt_rt=is_preempt_rt)
|
| 573 |
+
except RuntimeError as exc:
|
| 574 |
+
realtime_error = str(exc)
|
| 575 |
+
rt_profile = resolve_realtime_config("auto", is_preempt_rt=is_preempt_rt)
|
| 576 |
+
|
| 577 |
+
serial_ports, gripper_selection, serial_perm_nodes = _discover_grippers(
|
| 578 |
+
cfg, rediscover=rediscover
|
| 579 |
+
)
|
| 580 |
+
uvc_devices = _discover_cameras(cfg, rediscover=rediscover)
|
| 581 |
+
usb_permissions = check_linux_usb_permissions(
|
| 582 |
+
uvc_devices, serial_ports=serial_perm_nodes
|
| 583 |
+
)
|
| 584 |
+
menagerie_path = find_menagerie_dir()
|
| 585 |
+
mj_model, _ = build_fr3_duo_mjcf(cfg, menagerie_dir=menagerie_path)
|
| 586 |
+
if menagerie_path is None:
|
| 587 |
+
menagerie_path = find_menagerie_dir()
|
| 588 |
+
|
| 589 |
+
nominal_fk: dict[str, Any] = {}
|
| 590 |
+
fci_reachability: dict[str, Any] = {}
|
| 591 |
+
for arm in ("left", "right"):
|
| 592 |
+
q_rest = cfg.arms[arm].rest_pose_rad
|
| 593 |
+
pos_b, rot_b = compute_arm_fk(mj_model, arm, q_rest)
|
| 594 |
+
nominal_fk[arm] = {
|
| 595 |
+
"rest_pose_rad": [round(float(v), 6) for v in q_rest],
|
| 596 |
+
"tcp_pos_base_m": [round(float(v), 5) for v in pos_b],
|
| 597 |
+
"tcp_z_axis_base": [round(float(v), 5) for v in rot_b[:, 2]],
|
| 598 |
+
}
|
| 599 |
+
ip = cfg.arms[arm].ip
|
| 600 |
+
fci_reachability[arm] = {
|
| 601 |
+
"ip": ip,
|
| 602 |
+
"tcp_1337_reachable": tcp_port_reachable(
|
| 603 |
+
ip, timeout_s=ping_timeout_sec
|
| 604 |
+
),
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
warnings_list: list[str] = list(gripper_selection.get("warnings", []))
|
| 608 |
+
advisories_list: list[str] = list(gripper_selection.get("advisories", []))
|
| 609 |
+
_append_usb_permission_warnings(usb_permissions, uvc_devices, warnings_list)
|
| 610 |
+
conflicting_processes = find_conflicting_hardware_processes(
|
| 611 |
+
serial_perm_nodes, uvc_devices
|
| 612 |
+
)
|
| 613 |
+
for proc_conflict in conflicting_processes:
|
| 614 |
+
warnings_list.append(
|
| 615 |
+
f"Process '{proc_conflict['process']}' (PID {proc_conflict['pid']}) "
|
| 616 |
+
f"already holds {proc_conflict['device_label']}; kill conflicting "
|
| 617 |
+
"camera/serial processes before continuing."
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
arm_readout: dict[str, Any] = {}
|
| 621 |
+
rt_cfg_name = str(rt_profile.get("realtime_config", "kIgnore"))
|
| 622 |
+
for arm in ("left", "right"):
|
| 623 |
+
arm_cfg = cfg.arms[arm]
|
| 624 |
+
arm_res = probe_arm_readonly(
|
| 625 |
+
arm,
|
| 626 |
+
arm_cfg.ip,
|
| 627 |
+
mj_model,
|
| 628 |
+
rest_pose_rad=arm_cfg.rest_pose_rad,
|
| 629 |
+
tcp_offset_z_m=cfg.tcp_offset_z_m,
|
| 630 |
+
realtime_cfg_name=rt_cfg_name,
|
| 631 |
+
timeout_s=ping_timeout_sec,
|
| 632 |
+
tcp_reachable=bool(fci_reachability[arm]["tcp_1337_reachable"]),
|
| 633 |
+
)
|
| 634 |
+
for w in arm_res.get("warnings", []):
|
| 635 |
+
if w not in warnings_list:
|
| 636 |
+
warnings_list.append(w)
|
| 637 |
+
if (
|
| 638 |
+
fci_reachability[arm]["tcp_1337_reachable"]
|
| 639 |
+
and not arm_res["connected"]
|
| 640 |
+
):
|
| 641 |
+
fci_conflict_hint = (
|
| 642 |
+
f"FR3 {arm} ({arm_cfg.ip}): TCP 1337 reachable but FCI probe "
|
| 643 |
+
"failed; kill any other process controlling the arm and verify "
|
| 644 |
+
"Desk FCI mode is active."
|
| 645 |
+
)
|
| 646 |
+
if fci_conflict_hint not in warnings_list:
|
| 647 |
+
warnings_list.append(fci_conflict_hint)
|
| 648 |
+
for adv in arm_res.get("advisories", []):
|
| 649 |
+
if adv not in advisories_list:
|
| 650 |
+
advisories_list.append(adv)
|
| 651 |
+
arm_readout[arm] = {
|
| 652 |
+
"connected": arm_res["connected"],
|
| 653 |
+
"connection_error": arm_res["connection_error"],
|
| 654 |
+
"q_rad": arm_res["q_rad"],
|
| 655 |
+
"tcp_pos_base_m": arm_res["tcp_pos_base_m"],
|
| 656 |
+
"fk_pos_error_m": arm_res["fk_pos_error_m"],
|
| 657 |
+
"free_air_force_norm_n": arm_res["free_air_force_norm_n"],
|
| 658 |
+
"gripper_ratio": 0.0,
|
| 659 |
+
"desk_audit": arm_res["desk_audit"],
|
| 660 |
+
}
|
| 661 |
+
|
| 662 |
+
auto_bound_wrists = _auto_bind_devices(cfg, gripper_selection, uvc_devices)
|
| 663 |
+
resolved_out_dir = resolve_stage_output_dir(
|
| 664 |
+
"stage1", output_dir, dry_run=False
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
wrist_confirmed = False
|
| 668 |
+
if auto_bound_wrists:
|
| 669 |
+
can_prompt = bool(
|
| 670 |
+
not yes
|
| 671 |
+
and write_config is not None
|
| 672 |
+
and not read_only
|
| 673 |
+
and (input_fn is not None or sys.stdin.isatty())
|
| 674 |
+
)
|
| 675 |
+
if can_prompt:
|
| 676 |
+
assert write_config is not None
|
| 677 |
+
preview_dir = (
|
| 678 |
+
resolved_out_dir
|
| 679 |
+
if resolved_out_dir is not None
|
| 680 |
+
else write_config.parent
|
| 681 |
+
)
|
| 682 |
+
wrist_confirmed = _confirm_wrist_camera_mapping(
|
| 683 |
+
cfg, preview_dir=preview_dir, input_fn=input_fn or input
|
| 684 |
+
)
|
| 685 |
+
if not wrist_confirmed:
|
| 686 |
+
adv_msg = (
|
| 687 |
+
"Auto-bound RealSense wrist camera(s) without udev side_hint: "
|
| 688 |
+
+ ", ".join(auto_bound_wrists)
|
| 689 |
+
+ ". Verify physical left/right wrist views in Stage 2 "
|
| 690 |
+
"(uv run scripts/bringup.py --step cameras) and swap in config if "
|
| 691 |
+
"reversed."
|
| 692 |
+
)
|
| 693 |
+
if adv_msg not in advisories_list:
|
| 694 |
+
advisories_list.append(adv_msg)
|
| 695 |
+
|
| 696 |
+
cfg.realtime_mode = "auto" if realtime_error else realtime
|
| 697 |
+
wrote_cfg_path: str | None = None
|
| 698 |
+
if write_config is not None and not read_only:
|
| 699 |
+
save_robot_config(cfg, write_config)
|
| 700 |
+
wrote_cfg_path = str(write_config)
|
| 701 |
+
|
| 702 |
+
report: dict[str, Any] = {
|
| 703 |
+
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
|
| 704 |
+
"stage": "stage1_discover_hardware",
|
| 705 |
+
"mode": "hardware_readonly",
|
| 706 |
+
"dry_run": False,
|
| 707 |
+
"read_only": bool(read_only or write_config is None),
|
| 708 |
+
"menagerie_found": menagerie_path is not None,
|
| 709 |
+
"menagerie_dir": (
|
| 710 |
+
str(menagerie_path) if menagerie_path is not None else None
|
| 711 |
+
),
|
| 712 |
+
"preempt_rt_detected": is_preempt_rt,
|
| 713 |
+
"realtime_profile": rt_profile,
|
| 714 |
+
"realtime_error": realtime_error,
|
| 715 |
+
"fci_targets": fci_reachability,
|
| 716 |
+
"serial_ports": serial_ports,
|
| 717 |
+
"gripper_selection": gripper_selection,
|
| 718 |
+
"uvc_devices": uvc_devices,
|
| 719 |
+
"usb_permissions": usb_permissions,
|
| 720 |
+
"conflicting_processes": conflicting_processes,
|
| 721 |
+
"nominal_fk": nominal_fk,
|
| 722 |
+
"arm_readout": arm_readout,
|
| 723 |
+
"warnings": warnings_list,
|
| 724 |
+
"advisories": advisories_list,
|
| 725 |
+
"wrote_config": wrote_cfg_path,
|
| 726 |
+
"wrist_mapping_confirmed": wrist_confirmed,
|
| 727 |
+
"discovered_config": cfg.to_dict(),
|
| 728 |
+
}
|
| 729 |
+
json_path = output_json or (
|
| 730 |
+
resolved_out_dir / "discovery_report.json"
|
| 731 |
+
if resolved_out_dir is not None
|
| 732 |
+
else None
|
| 733 |
+
)
|
| 734 |
+
if json_path is not None:
|
| 735 |
+
json_path.parent.mkdir(parents=True, exist_ok=True)
|
| 736 |
+
json_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
| 737 |
+
report["report_path"] = str(json_path)
|
| 738 |
+
|
| 739 |
+
_print_discovery_summary(
|
| 740 |
+
cfg=cfg, report=report, menagerie_path=menagerie_path
|
| 741 |
+
)
|
| 742 |
+
if realtime_error is not None:
|
| 743 |
+
print(f"ERROR: {realtime_error}", file=sys.stderr)
|
| 744 |
+
return 1, report
|
| 745 |
+
if strict_preflight and warnings_list:
|
| 746 |
+
print(
|
| 747 |
+
f"ERROR: --strict-preflight failed with {len(warnings_list)} "
|
| 748 |
+
"warning(s).",
|
| 749 |
+
file=sys.stderr,
|
| 750 |
+
)
|
| 751 |
+
return 2, report
|
| 752 |
+
return 0, report
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/fr3_arm_controller.py
ADDED
|
@@ -0,0 +1,1162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Franka Research 3 FCI controller, Desk audit, and 1 kHz worker process."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import collections
|
| 20 |
+
from collections.abc import Mapping, Sequence
|
| 21 |
+
import gc
|
| 22 |
+
import math
|
| 23 |
+
import multiprocessing as mp
|
| 24 |
+
import socket
|
| 25 |
+
from typing import Any
|
| 26 |
+
|
| 27 |
+
from fr3_config import (
|
| 28 |
+
RobotConfig,
|
| 29 |
+
normalize_robot_config,
|
| 30 |
+
resolve_realtime_config,
|
| 31 |
+
)
|
| 32 |
+
import fr3_kinematics
|
| 33 |
+
import fr3_mjcf
|
| 34 |
+
from fr3_safety import (
|
| 35 |
+
blend_start_pose_offset,
|
| 36 |
+
clamp_q_to_padded_limits,
|
| 37 |
+
compute_abort_deceleration_step,
|
| 38 |
+
limit_rate_joint_positions,
|
| 39 |
+
step_realtime_trajectory_index,
|
| 40 |
+
unpack_o_t_ee,
|
| 41 |
+
)
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
import mujoco # pytype: disable=import-error
|
| 46 |
+
except ImportError:
|
| 47 |
+
mujoco: Any = None
|
| 48 |
+
|
| 49 |
+
__all__ = [
|
| 50 |
+
"ArmWorkerProcess",
|
| 51 |
+
"audit_arm_desk_config",
|
| 52 |
+
"compute_ext_wrench_base_6d",
|
| 53 |
+
"compute_fk_pos_error_m",
|
| 54 |
+
"compute_link0_in_base_transform_for_model",
|
| 55 |
+
"disconnect_pylibfranka_robot",
|
| 56 |
+
"probe_arm_readonly",
|
| 57 |
+
"read_arm_joints_or_rest",
|
| 58 |
+
"read_pylibfranka_state",
|
| 59 |
+
"recover_pylibfranka_errors",
|
| 60 |
+
"tcp_port_reachable",
|
| 61 |
+
"validate_arm_readiness",
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _require_pylibfranka() -> Any:
|
| 66 |
+
"""Lazily imports Linux-only `pylibfranka` binding on demand."""
|
| 67 |
+
import pylibfranka # pytype: disable=import-error
|
| 68 |
+
|
| 69 |
+
return pylibfranka
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _open_pylibfranka_robot(
|
| 73 |
+
ip: str, realtime_cfg_name: str = "kIgnore"
|
| 74 |
+
) -> Any:
|
| 75 |
+
"""Opens a `pylibfranka.Robot` connection with the requested realtime mode."""
|
| 76 |
+
pylibfranka = _require_pylibfranka()
|
| 77 |
+
rt_enum = getattr(pylibfranka, "RealtimeConfig", None)
|
| 78 |
+
if rt_enum is not None:
|
| 79 |
+
rt_val = getattr(rt_enum, realtime_cfg_name, None)
|
| 80 |
+
if rt_val is not None:
|
| 81 |
+
return pylibfranka.Robot(ip, rt_val)
|
| 82 |
+
return pylibfranka.Robot(ip)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def tcp_port_reachable(
|
| 86 |
+
host: str, port: int = 1337, timeout_s: float = 0.25
|
| 87 |
+
) -> bool:
|
| 88 |
+
"""Checks whether TCP `host:port` accepts a connection within `timeout_s`."""
|
| 89 |
+
try:
|
| 90 |
+
with socket.create_connection((host, port), timeout=timeout_s):
|
| 91 |
+
return True
|
| 92 |
+
except OSError:
|
| 93 |
+
return False
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def disconnect_pylibfranka_robot(robot: Any) -> None:
|
| 97 |
+
"""Best-effort clean disconnect for a `pylibfranka.Robot` instance."""
|
| 98 |
+
if robot is None:
|
| 99 |
+
return
|
| 100 |
+
for method_name in ("stop", "close", "disconnect"):
|
| 101 |
+
fn = getattr(robot, method_name, None)
|
| 102 |
+
if callable(fn):
|
| 103 |
+
try:
|
| 104 |
+
fn()
|
| 105 |
+
except Exception: # pylint: disable=broad-exception-caught
|
| 106 |
+
pass
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _extract_pylibfranka_errors(raw_errors: Any) -> list[str]:
|
| 110 |
+
"""Extracts active errors from `pylibfranka.RobotState.current_errors`."""
|
| 111 |
+
if raw_errors is None:
|
| 112 |
+
return []
|
| 113 |
+
if isinstance(raw_errors, bool):
|
| 114 |
+
return ["unknown_error"] if raw_errors else []
|
| 115 |
+
if isinstance(raw_errors, str):
|
| 116 |
+
s = raw_errors.strip()
|
| 117 |
+
return [s] if s else []
|
| 118 |
+
if isinstance(raw_errors, Mapping):
|
| 119 |
+
return [
|
| 120 |
+
str(k).strip()
|
| 121 |
+
for k, v in raw_errors.items()
|
| 122 |
+
if bool(v) and str(k).strip()
|
| 123 |
+
]
|
| 124 |
+
if isinstance(raw_errors, (Sequence, set)) and not isinstance(
|
| 125 |
+
raw_errors, (str, bytes)
|
| 126 |
+
):
|
| 127 |
+
return [str(x).strip() for x in raw_errors if str(x).strip()]
|
| 128 |
+
|
| 129 |
+
found_flag = False
|
| 130 |
+
active: list[str] = []
|
| 131 |
+
for attr in dir(raw_errors):
|
| 132 |
+
if attr.startswith("_"):
|
| 133 |
+
continue
|
| 134 |
+
try:
|
| 135 |
+
val = getattr(raw_errors, attr)
|
| 136 |
+
except Exception: # pylint: disable=broad-exception-caught
|
| 137 |
+
continue
|
| 138 |
+
if callable(val):
|
| 139 |
+
continue
|
| 140 |
+
if isinstance(val, (bool, int)):
|
| 141 |
+
found_flag = True
|
| 142 |
+
if val:
|
| 143 |
+
active.append(attr)
|
| 144 |
+
if active:
|
| 145 |
+
return active
|
| 146 |
+
if found_flag:
|
| 147 |
+
return []
|
| 148 |
+
try:
|
| 149 |
+
has_truthy_bool = bool(raw_errors)
|
| 150 |
+
except Exception: # pylint: disable=broad-exception-caught
|
| 151 |
+
has_truthy_bool = False
|
| 152 |
+
if not has_truthy_bool:
|
| 153 |
+
return []
|
| 154 |
+
text = str(raw_errors).strip()
|
| 155 |
+
if text and not text.startswith("<") and text != "namespace()":
|
| 156 |
+
return [text]
|
| 157 |
+
return ["unknown_error"]
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _state_has_errors(state: Mapping[str, Any]) -> tuple[bool, list[str]]:
|
| 161 |
+
"""Returns `(has_error_or_reflex, current_errors)` for a state dict."""
|
| 162 |
+
errs = list(state.get("current_errors") or [])
|
| 163 |
+
mode = str(state.get("robot_mode") or "").strip().lower()
|
| 164 |
+
in_reflex = mode in (
|
| 165 |
+
"kreflex",
|
| 166 |
+
"reflex",
|
| 167 |
+
"kautomaticerrorrecovery",
|
| 168 |
+
"automaticerrorrecovery",
|
| 169 |
+
)
|
| 170 |
+
return bool(errs or in_reflex), errs
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _recovery_result(
|
| 174 |
+
*,
|
| 175 |
+
had_errors: bool = False,
|
| 176 |
+
errors_before: Sequence[str] = (),
|
| 177 |
+
recovered: bool = True,
|
| 178 |
+
errors_after: Sequence[str] = (),
|
| 179 |
+
error: str | None = None,
|
| 180 |
+
) -> dict[str, Any]:
|
| 181 |
+
"""Builds a uniform FCI error-recovery status payload."""
|
| 182 |
+
return {
|
| 183 |
+
"had_errors": had_errors,
|
| 184 |
+
"errors_before": list(errors_before),
|
| 185 |
+
"recovered": recovered,
|
| 186 |
+
"errors_after": list(errors_after),
|
| 187 |
+
"error": error,
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def read_pylibfranka_state(robot: Any) -> dict[str, Any]:
|
| 192 |
+
"""Reads one FCI state packet from a connected `pylibfranka.Robot`."""
|
| 193 |
+
state = robot.read_once()
|
| 194 |
+
q = [float(x) for x in getattr(state, "q")]
|
| 195 |
+
q_d = [float(x) for x in getattr(state, "q_d", q)]
|
| 196 |
+
dq = [float(x) for x in getattr(state, "dq", [0.0] * 7)]
|
| 197 |
+
dq_d = [float(x) for x in getattr(state, "dq_d", dq)]
|
| 198 |
+
ddq_d = [float(x) for x in getattr(state, "ddq_d", [0.0] * 7)]
|
| 199 |
+
tau_j = [float(x) for x in getattr(state, "tau_J", [0.0] * 7)]
|
| 200 |
+
o_t_ee = [
|
| 201 |
+
float(x)
|
| 202 |
+
for x in getattr(
|
| 203 |
+
state,
|
| 204 |
+
"O_T_EE",
|
| 205 |
+
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
|
| 206 |
+
)
|
| 207 |
+
]
|
| 208 |
+
|
| 209 |
+
raw_mode = getattr(state, "robot_mode", None)
|
| 210 |
+
if raw_mode is not None:
|
| 211 |
+
robot_mode = (
|
| 212 |
+
str(raw_mode.name)
|
| 213 |
+
if hasattr(raw_mode, "name")
|
| 214 |
+
else str(raw_mode).split(".")[-1]
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
robot_mode = ""
|
| 218 |
+
|
| 219 |
+
current_errors = _extract_pylibfranka_errors(
|
| 220 |
+
getattr(state, "current_errors", None)
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
m_ee_val = getattr(state, "m_ee", None)
|
| 224 |
+
m_ee = float(m_ee_val) if m_ee_val is not None else None
|
| 225 |
+
|
| 226 |
+
m_load_val = getattr(state, "m_load", None)
|
| 227 |
+
m_load = float(m_load_val) if m_load_val is not None else None
|
| 228 |
+
|
| 229 |
+
m_total_val = getattr(state, "m_total", None)
|
| 230 |
+
if m_total_val is not None:
|
| 231 |
+
m_total = float(m_total_val)
|
| 232 |
+
elif m_ee is not None:
|
| 233 |
+
m_total = float(m_ee + (m_load or 0.0))
|
| 234 |
+
else:
|
| 235 |
+
m_total = None
|
| 236 |
+
|
| 237 |
+
f_x_cee_val = getattr(state, "F_x_Cee", None)
|
| 238 |
+
f_x_cee = (
|
| 239 |
+
[float(x) for x in f_x_cee_val] if f_x_cee_val is not None else None
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
i_ee_val = getattr(state, "I_ee", None)
|
| 243 |
+
i_ee = [float(x) for x in i_ee_val] if i_ee_val is not None else None
|
| 244 |
+
|
| 245 |
+
f_t_ee_val = getattr(state, "F_T_EE", None)
|
| 246 |
+
f_t_ee = [float(x) for x in f_t_ee_val] if f_t_ee_val is not None else None
|
| 247 |
+
|
| 248 |
+
o_ddp_o_val = getattr(state, "O_ddP_O", None)
|
| 249 |
+
o_ddp_o = (
|
| 250 |
+
[float(x) for x in list(o_ddp_o_val)[:3]]
|
| 251 |
+
if o_ddp_o_val is not None
|
| 252 |
+
else None
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
o_f_ext_val = getattr(state, "O_F_ext_hat_K", None)
|
| 256 |
+
o_f_ext_hat_k = (
|
| 257 |
+
[float(x) for x in o_f_ext_val] if o_f_ext_val is not None else None
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
tau_ext_val = getattr(state, "tau_ext_hat_filtered", None)
|
| 261 |
+
tau_ext_hat_filtered = (
|
| 262 |
+
[float(x) for x in tau_ext_val] if tau_ext_val is not None else None
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
return {
|
| 266 |
+
"q": q,
|
| 267 |
+
"q_d": q_d,
|
| 268 |
+
"dq": dq,
|
| 269 |
+
"dq_d": dq_d,
|
| 270 |
+
"ddq_d": ddq_d,
|
| 271 |
+
"tau_j": tau_j,
|
| 272 |
+
"o_t_ee": o_t_ee,
|
| 273 |
+
"robot_mode": robot_mode,
|
| 274 |
+
"current_errors": current_errors,
|
| 275 |
+
"m_ee": m_ee,
|
| 276 |
+
"m_load": m_load,
|
| 277 |
+
"m_total": m_total,
|
| 278 |
+
"f_x_cee": f_x_cee,
|
| 279 |
+
"i_ee": i_ee,
|
| 280 |
+
"f_t_ee": f_t_ee,
|
| 281 |
+
"o_ddp_o": o_ddp_o,
|
| 282 |
+
"o_f_ext_hat_k": o_f_ext_hat_k,
|
| 283 |
+
"tau_ext_hat_filtered": tau_ext_hat_filtered,
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def recover_pylibfranka_errors(robot: Any) -> dict[str, Any]:
|
| 288 |
+
"""Checks FCI `current_errors`/reflex and runs `automatic_error_recovery`."""
|
| 289 |
+
has_err_before, before_errs = _state_has_errors(read_pylibfranka_state(robot))
|
| 290 |
+
if not has_err_before:
|
| 291 |
+
return _recovery_result()
|
| 292 |
+
|
| 293 |
+
recovery_fn = getattr(robot, "automatic_error_recovery", None)
|
| 294 |
+
if not callable(recovery_fn):
|
| 295 |
+
return _recovery_result(
|
| 296 |
+
had_errors=True,
|
| 297 |
+
errors_before=before_errs,
|
| 298 |
+
recovered=False,
|
| 299 |
+
errors_after=before_errs,
|
| 300 |
+
error="robot.automatic_error_recovery() is unavailable",
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
err_msg: str | None = None
|
| 304 |
+
try:
|
| 305 |
+
recovery_fn()
|
| 306 |
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
| 307 |
+
err_msg = str(exc)
|
| 308 |
+
|
| 309 |
+
try:
|
| 310 |
+
has_err_after, after_errs = _state_has_errors(read_pylibfranka_state(robot))
|
| 311 |
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
| 312 |
+
combined = f"{err_msg}; {exc}" if err_msg else str(exc)
|
| 313 |
+
return _recovery_result(
|
| 314 |
+
had_errors=True,
|
| 315 |
+
errors_before=before_errs,
|
| 316 |
+
recovered=False,
|
| 317 |
+
errors_after=before_errs,
|
| 318 |
+
error=combined,
|
| 319 |
+
)
|
| 320 |
+
return _recovery_result(
|
| 321 |
+
had_errors=True,
|
| 322 |
+
errors_before=before_errs,
|
| 323 |
+
recovered=(err_msg is None and not has_err_after),
|
| 324 |
+
errors_after=after_errs,
|
| 325 |
+
error=err_msg,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _audit_desk_gravity(
|
| 330 |
+
arm: str,
|
| 331 |
+
o_ddp_o: Sequence[float] | None,
|
| 332 |
+
exp_g_arr: np.ndarray,
|
| 333 |
+
expected_mount_tilt_deg: float,
|
| 334 |
+
gravity_tol_deg: float,
|
| 335 |
+
fci_ext_force_norm_n: float | None,
|
| 336 |
+
fci_tau_ext_norm_nm: float | None,
|
| 337 |
+
force_tol_n: float,
|
| 338 |
+
tau_tol_nm: float,
|
| 339 |
+
warnings: list[str],
|
| 340 |
+
advisories: list[str],
|
| 341 |
+
) -> float | None:
|
| 342 |
+
if o_ddp_o is None or len(o_ddp_o) < 3:
|
| 343 |
+
return None
|
| 344 |
+
v_meas = np.asarray(o_ddp_o[:3], dtype=np.float64)
|
| 345 |
+
norm_meas = float(np.linalg.norm(v_meas))
|
| 346 |
+
norm_exp = float(np.linalg.norm(exp_g_arr))
|
| 347 |
+
if norm_meas <= 1e-3 or norm_exp <= 1e-3:
|
| 348 |
+
return None
|
| 349 |
+
cos_ang = np.clip(
|
| 350 |
+
float(np.dot(v_meas, exp_g_arr) / (norm_meas * norm_exp)), -1.0, 1.0
|
| 351 |
+
)
|
| 352 |
+
gravity_angle_err_deg = float(math.degrees(math.acos(cos_ang)))
|
| 353 |
+
if gravity_angle_err_deg <= gravity_tol_deg:
|
| 354 |
+
return gravity_angle_err_deg
|
| 355 |
+
|
| 356 |
+
z_down_angle_deg = float(
|
| 357 |
+
math.degrees(math.acos(np.clip(float(-v_meas[2] / norm_meas), -1.0, 1.0)))
|
| 358 |
+
)
|
| 359 |
+
wrench_healthy = (
|
| 360 |
+
fci_ext_force_norm_n is not None
|
| 361 |
+
and fci_ext_force_norm_n <= force_tol_n
|
| 362 |
+
and (fci_tau_ext_norm_nm is None or fci_tau_ext_norm_nm <= tau_tol_nm)
|
| 363 |
+
)
|
| 364 |
+
meas_rounded = [round(float(x), 4) for x in v_meas]
|
| 365 |
+
exp_rounded = [round(float(x), 3) for x in exp_g_arr]
|
| 366 |
+
if z_down_angle_deg <= 2.0 and wrench_healthy:
|
| 367 |
+
advisories.append(
|
| 368 |
+
f"{arm}: RobotState.O_ddP_O={meas_rounded} differs by "
|
| 369 |
+
f"{gravity_angle_err_deg:.1f} deg from expected tilted mount gravity "
|
| 370 |
+
f"{exp_rounded} (tilt={expected_mount_tilt_deg:.1f} deg), but "
|
| 371 |
+
f"||O_F_ext_hat_K[:3]|| = {fci_ext_force_norm_n:.2f} N <= "
|
| 372 |
+
f"{force_tol_n:.2f} N (firmware reports nominal [0, 0, -9.81] while "
|
| 373 |
+
"Desk gravity compensation appears active)."
|
| 374 |
+
)
|
| 375 |
+
else:
|
| 376 |
+
warnings.append(
|
| 377 |
+
f"{arm}: RobotState.O_ddP_O={meas_rounded} differs by "
|
| 378 |
+
f"{gravity_angle_err_deg:.1f} deg from expected tilted mount gravity "
|
| 379 |
+
f"{exp_rounded} (tilt={expected_mount_tilt_deg:.1f} deg). Verify "
|
| 380 |
+
"tilted shoulder mounting angle in Franka Desk (note: older libfranka "
|
| 381 |
+
"builds may report static [0, 0, -9.81]; check fci_ext_force_norm_n)."
|
| 382 |
+
)
|
| 383 |
+
return gravity_angle_err_deg
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def audit_arm_desk_config(
|
| 387 |
+
arm: str,
|
| 388 |
+
hw_state: dict[str, Any] | None,
|
| 389 |
+
r_base_link0: np.ndarray,
|
| 390 |
+
*,
|
| 391 |
+
expected_mass_range_kg: tuple[float, float] = (0.5, 3.0),
|
| 392 |
+
gravity_tol_deg: float = 8.0,
|
| 393 |
+
force_tol_n: float = 6.5,
|
| 394 |
+
tau_tol_nm: float = 4.5,
|
| 395 |
+
) -> dict[str, Any]:
|
| 396 |
+
"""Audits Franka Desk configuration (mode, payload, tilted mount, wrench)."""
|
| 397 |
+
r_mat = np.asarray(r_base_link0, dtype=np.float64)
|
| 398 |
+
exp_g_arr = r_mat.T @ np.array([0.0, 0.0, -9.81], dtype=np.float64)
|
| 399 |
+
expected_mount_tilt_deg = math.degrees(
|
| 400 |
+
math.acos(np.clip(float(r_mat[2, 2]), -1.0, 1.0))
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
if hw_state is None:
|
| 404 |
+
return {
|
| 405 |
+
"checked": False,
|
| 406 |
+
"fci_connected": False,
|
| 407 |
+
"robot_mode": "",
|
| 408 |
+
"m_ee_kg": None,
|
| 409 |
+
"m_total_kg": None,
|
| 410 |
+
"f_x_cee_m": None,
|
| 411 |
+
"i_ee_trace_kgm2": None,
|
| 412 |
+
"o_ddp_o": None,
|
| 413 |
+
"expected_o_ddp_o": [round(float(x), 4) for x in exp_g_arr],
|
| 414 |
+
"expected_mount_tilt_deg": round(float(expected_mount_tilt_deg), 2),
|
| 415 |
+
"gravity_angle_err_deg": None,
|
| 416 |
+
"fci_ext_force_norm_n": None,
|
| 417 |
+
"fci_tau_ext_norm_nm": None,
|
| 418 |
+
"ok": True,
|
| 419 |
+
"warnings": [],
|
| 420 |
+
"advisories": [],
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
warnings: list[str] = []
|
| 424 |
+
advisories: list[str] = []
|
| 425 |
+
|
| 426 |
+
robot_mode = str(hw_state.get("robot_mode") or "").strip()
|
| 427 |
+
if robot_mode and robot_mode not in ("kIdle", "Idle", "IDLE"):
|
| 428 |
+
warnings.append(
|
| 429 |
+
f"{arm}: FCI RobotState.robot_mode is {robot_mode!r} (expected 'kIdle'"
|
| 430 |
+
" with joints unlocked and E-stop released)."
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
m_ee = hw_state.get("m_ee")
|
| 434 |
+
m_total = hw_state.get("m_total")
|
| 435 |
+
if m_total is not None:
|
| 436 |
+
lo, hi = expected_mass_range_kg
|
| 437 |
+
if not (lo <= float(m_total) <= hi):
|
| 438 |
+
warnings.append(
|
| 439 |
+
f"{arm}: Franka Desk m_total={float(m_total):.3f} kg outside expected"
|
| 440 |
+
f" [{lo:.2f}, {hi:.2f}] kg for Robotiq 2F-85 + coupling + wrist"
|
| 441 |
+
" camera (is Desk EE payload still 0 kg?)."
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
f_x_cee = hw_state.get("f_x_cee")
|
| 445 |
+
if f_x_cee is not None:
|
| 446 |
+
if float(np.linalg.norm(np.asarray(f_x_cee, dtype=np.float64))) < 0.005:
|
| 447 |
+
warnings.append(
|
| 448 |
+
f"{arm}: Franka Desk F_x_Cee={list(f_x_cee)} m is near zero"
|
| 449 |
+
" (configure Robotiq + wrist camera CoM in Desk)."
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
i_ee = hw_state.get("i_ee")
|
| 453 |
+
i_ee_trace: float | None = None
|
| 454 |
+
if i_ee is not None and len(i_ee) == 9:
|
| 455 |
+
i_ee_trace = float(abs(i_ee[0]) + abs(i_ee[4]) + abs(i_ee[8]))
|
| 456 |
+
if i_ee_trace <= 1e-5:
|
| 457 |
+
warnings.append(
|
| 458 |
+
f"{arm}: Franka Desk rotational inertia I_ee trace is ~0 kg*m^2"
|
| 459 |
+
" (configure EE inertia in Desk)."
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
o_f_ext_hat_k = hw_state.get("o_f_ext_hat_k")
|
| 463 |
+
fci_ext_force_norm_n: float | None = None
|
| 464 |
+
if o_f_ext_hat_k is not None and len(o_f_ext_hat_k) >= 3:
|
| 465 |
+
fci_ext_force_norm_n = float(
|
| 466 |
+
np.linalg.norm(np.asarray(o_f_ext_hat_k[:3], dtype=np.float64))
|
| 467 |
+
)
|
| 468 |
+
if fci_ext_force_norm_n > force_tol_n:
|
| 469 |
+
warnings.append(
|
| 470 |
+
f"{arm}: Franka controller external force residual"
|
| 471 |
+
f" ||O_F_ext_hat_K[:3]|| = {fci_ext_force_norm_n:.2f} N exceeds"
|
| 472 |
+
f" tolerance {force_tol_n:.2f} N (indicates unmodeled payload mass"
|
| 473 |
+
" or tilted mount mismatch)."
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
tau_ext_hat_filtered = hw_state.get("tau_ext_hat_filtered")
|
| 477 |
+
fci_tau_ext_norm_nm: float | None = None
|
| 478 |
+
if tau_ext_hat_filtered is not None and len(tau_ext_hat_filtered) >= 7:
|
| 479 |
+
fci_tau_ext_norm_nm = float(
|
| 480 |
+
np.linalg.norm(np.asarray(tau_ext_hat_filtered, dtype=np.float64))
|
| 481 |
+
)
|
| 482 |
+
if fci_tau_ext_norm_nm > tau_tol_nm:
|
| 483 |
+
warnings.append(
|
| 484 |
+
f"{arm}: Franka controller external torque residual"
|
| 485 |
+
f" ||tau_ext_hat_filtered|| = {fci_tau_ext_norm_nm:.2f} Nm exceeds"
|
| 486 |
+
f" tolerance {tau_tol_nm:.2f} Nm."
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
o_ddp_o = hw_state.get("o_ddp_o")
|
| 490 |
+
gravity_angle_err_deg = _audit_desk_gravity(
|
| 491 |
+
arm,
|
| 492 |
+
o_ddp_o,
|
| 493 |
+
exp_g_arr,
|
| 494 |
+
expected_mount_tilt_deg,
|
| 495 |
+
gravity_tol_deg,
|
| 496 |
+
fci_ext_force_norm_n,
|
| 497 |
+
fci_tau_ext_norm_nm,
|
| 498 |
+
force_tol_n,
|
| 499 |
+
tau_tol_nm,
|
| 500 |
+
warnings,
|
| 501 |
+
advisories,
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
return {
|
| 505 |
+
"checked": True,
|
| 506 |
+
"fci_connected": True,
|
| 507 |
+
"robot_mode": robot_mode,
|
| 508 |
+
"m_ee_kg": float(m_ee) if m_ee is not None else None,
|
| 509 |
+
"m_total_kg": float(m_total) if m_total is not None else None,
|
| 510 |
+
"f_x_cee_m": [float(x) for x in f_x_cee] if f_x_cee is not None else None,
|
| 511 |
+
"i_ee_trace_kgm2": (
|
| 512 |
+
round(float(i_ee_trace), 6) if i_ee_trace is not None else None
|
| 513 |
+
),
|
| 514 |
+
"o_ddp_o": (
|
| 515 |
+
[round(float(x), 4) for x in o_ddp_o[:3]]
|
| 516 |
+
if o_ddp_o is not None
|
| 517 |
+
else None
|
| 518 |
+
),
|
| 519 |
+
"expected_o_ddp_o": [round(float(x), 4) for x in exp_g_arr],
|
| 520 |
+
"expected_mount_tilt_deg": round(float(expected_mount_tilt_deg), 2),
|
| 521 |
+
"gravity_angle_err_deg": (
|
| 522 |
+
round(float(gravity_angle_err_deg), 2)
|
| 523 |
+
if gravity_angle_err_deg is not None
|
| 524 |
+
else None
|
| 525 |
+
),
|
| 526 |
+
"fci_ext_force_norm_n": (
|
| 527 |
+
round(float(fci_ext_force_norm_n), 3)
|
| 528 |
+
if fci_ext_force_norm_n is not None
|
| 529 |
+
else None
|
| 530 |
+
),
|
| 531 |
+
"fci_tau_ext_norm_nm": (
|
| 532 |
+
round(float(fci_tau_ext_norm_nm), 3)
|
| 533 |
+
if fci_tau_ext_norm_nm is not None
|
| 534 |
+
else None
|
| 535 |
+
),
|
| 536 |
+
"ok": len(warnings) == 0,
|
| 537 |
+
"warnings": warnings,
|
| 538 |
+
"advisories": advisories,
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def compute_link0_in_base_transform_for_model(
|
| 543 |
+
mj_model: Any, side: str, mj_data: Any = None
|
| 544 |
+
) -> np.ndarray:
|
| 545 |
+
"""Computes `T_base_link0` 4x4 transform for `side` from an MjModel."""
|
| 546 |
+
if mujoco is None:
|
| 547 |
+
raise RuntimeError(
|
| 548 |
+
"`mujoco` is required to compute T_base_link0 from an MjModel."
|
| 549 |
+
)
|
| 550 |
+
data = mj_data if mj_data is not None else mujoco.MjData(mj_model)
|
| 551 |
+
if mj_data is None:
|
| 552 |
+
data.qpos[:] = mj_model.qpos0
|
| 553 |
+
mujoco.mj_forward(mj_model, data)
|
| 554 |
+
|
| 555 |
+
link0_id = int(
|
| 556 |
+
mujoco.mj_name2id(
|
| 557 |
+
mj_model, mujoco.mjtObj.mjOBJ_BODY, f"{side}/fr3_link0"
|
| 558 |
+
)
|
| 559 |
+
)
|
| 560 |
+
t_base_link0 = np.eye(4, dtype=np.float64)
|
| 561 |
+
if link0_id >= 0:
|
| 562 |
+
t_base_link0[:3, :3] = np.asarray(
|
| 563 |
+
data.xmat[link0_id], dtype=np.float64
|
| 564 |
+
).reshape(3, 3)
|
| 565 |
+
t_base_link0[:3, 3] = np.asarray(data.xpos[link0_id], dtype=np.float64)
|
| 566 |
+
return t_base_link0
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def compute_fk_pos_error_m(
|
| 570 |
+
tcp_pos_base: np.ndarray,
|
| 571 |
+
t_base_link0: np.ndarray,
|
| 572 |
+
o_t_ee_4x4: np.ndarray,
|
| 573 |
+
tcp_offset_z_m: float,
|
| 574 |
+
raw_f_t_ee: Sequence[float] | None,
|
| 575 |
+
*,
|
| 576 |
+
mj_model: Any = None,
|
| 577 |
+
side: str = "",
|
| 578 |
+
q_rad: Sequence[float] | None = None,
|
| 579 |
+
) -> float:
|
| 580 |
+
"""Returns min Euclidean discrepancy (m) between MuJoCo FK and FCI O_T_EE."""
|
| 581 |
+
rq_pinch_from_flange = None
|
| 582 |
+
if mj_model is not None and side and q_rad is not None:
|
| 583 |
+
try:
|
| 584 |
+
rq_pinch_from_flange = fr3_kinematics.compute_arm_pinch_from_flange(
|
| 585 |
+
mj_model, side, q_rad
|
| 586 |
+
)
|
| 587 |
+
except (ValueError, KeyError, RuntimeError):
|
| 588 |
+
rq_pinch_from_flange = None
|
| 589 |
+
if rq_pinch_from_flange is None:
|
| 590 |
+
rq_pinch_from_flange = np.array(
|
| 591 |
+
[0.0, 0.0, 0.0108 + float(tcp_offset_z_m), 1.0], dtype=np.float64
|
| 592 |
+
)
|
| 593 |
+
candidate_errs = [
|
| 594 |
+
float(np.linalg.norm(tcp_pos_base - (t_base_link0 @ o_t_ee_4x4)[:3, 3])),
|
| 595 |
+
float(
|
| 596 |
+
np.linalg.norm(
|
| 597 |
+
tcp_pos_base
|
| 598 |
+
- (t_base_link0 @ o_t_ee_4x4 @ rq_pinch_from_flange)[:3]
|
| 599 |
+
)
|
| 600 |
+
),
|
| 601 |
+
]
|
| 602 |
+
if raw_f_t_ee is not None and len(raw_f_t_ee) == 16:
|
| 603 |
+
try:
|
| 604 |
+
f_t_ee_4x4 = unpack_o_t_ee(raw_f_t_ee)
|
| 605 |
+
o_t_f = o_t_ee_4x4 @ np.linalg.inv(f_t_ee_4x4)
|
| 606 |
+
fci_from_flange = (t_base_link0 @ o_t_f @ rq_pinch_from_flange)[:3]
|
| 607 |
+
candidate_errs.append(
|
| 608 |
+
float(np.linalg.norm(tcp_pos_base - fci_from_flange))
|
| 609 |
+
)
|
| 610 |
+
except np.linalg.LinAlgError:
|
| 611 |
+
pass
|
| 612 |
+
return min(candidate_errs)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def compute_ext_wrench_base_6d(
|
| 616 |
+
hw: Mapping[str, Any] | None,
|
| 617 |
+
mj_model: Any,
|
| 618 |
+
side: str,
|
| 619 |
+
q_rad: np.ndarray,
|
| 620 |
+
tau_j: np.ndarray,
|
| 621 |
+
r_base_link0: np.ndarray,
|
| 622 |
+
) -> np.ndarray:
|
| 623 |
+
"""Resolves 6-D external wrench in Duo `base` frame from FCI or MJCF SVD."""
|
| 624 |
+
raw_f_ext = hw.get("o_f_ext_hat_k") if hw is not None else None
|
| 625 |
+
if raw_f_ext is not None and len(raw_f_ext) >= 6:
|
| 626 |
+
w_o = -np.asarray(raw_f_ext[:6], dtype=np.float64)
|
| 627 |
+
return np.concatenate(
|
| 628 |
+
[r_base_link0 @ w_o[:3], r_base_link0 @ w_o[3:6]]
|
| 629 |
+
).astype(np.float64)
|
| 630 |
+
return fr3_kinematics.estimate_external_wrench_base(
|
| 631 |
+
mj_model, side, q_rad, tau_j
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def validate_arm_readiness(
|
| 636 |
+
arm: str, arm_state: Mapping[str, Any]
|
| 637 |
+
) -> list[str]:
|
| 638 |
+
"""Returns FK discrepancy, free-air force, and Desk config warnings."""
|
| 639 |
+
warnings: list[str] = []
|
| 640 |
+
desk_audit = arm_state.get("desk_audit")
|
| 641 |
+
if isinstance(desk_audit, Mapping) and desk_audit.get("warnings"):
|
| 642 |
+
for w in desk_audit["warnings"]:
|
| 643 |
+
if w not in warnings:
|
| 644 |
+
warnings.append(str(w))
|
| 645 |
+
|
| 646 |
+
fk_err_m = float(arm_state.get("fk_pos_error_m", 0.0))
|
| 647 |
+
if fk_err_m > 0.005:
|
| 648 |
+
warnings.append(
|
| 649 |
+
f"{arm}: O_T_EE vs MJCF FK discrepancy {fk_err_m * 1000.0:.2f} mm > 5.0"
|
| 650 |
+
" mm."
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
if "tau_ext_base_6d" in arm_state:
|
| 654 |
+
force_norm_n = float(
|
| 655 |
+
np.linalg.norm(
|
| 656 |
+
np.asarray(arm_state["tau_ext_base_6d"], dtype=np.float64)[:3]
|
| 657 |
+
)
|
| 658 |
+
)
|
| 659 |
+
else:
|
| 660 |
+
force_norm_n = float(arm_state.get("free_air_force_norm_n", 0.0))
|
| 661 |
+
if force_norm_n > 6.5:
|
| 662 |
+
warnings.append(
|
| 663 |
+
f"{arm}: free-air tau_ext force norm {force_norm_n:.2f} N > 6.5 N "
|
| 664 |
+
"(verify tilted Duo mounting gravity and EE payload in Franka Desk)."
|
| 665 |
+
)
|
| 666 |
+
cur_errs = arm_state.get("current_errors") or []
|
| 667 |
+
if cur_errs:
|
| 668 |
+
warnings.append(
|
| 669 |
+
f"{arm}: active FCI current_errors: "
|
| 670 |
+
f"{', '.join(str(e) for e in cur_errs)}."
|
| 671 |
+
)
|
| 672 |
+
return warnings
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def probe_arm_readonly(
|
| 676 |
+
side: str,
|
| 677 |
+
ip: str,
|
| 678 |
+
mj_model: Any,
|
| 679 |
+
*,
|
| 680 |
+
rest_pose_rad: Sequence[float] | None = None,
|
| 681 |
+
tcp_offset_z_m: float = 0.145,
|
| 682 |
+
realtime_cfg_name: str = "kIgnore",
|
| 683 |
+
timeout_s: float = 0.25,
|
| 684 |
+
tcp_reachable: bool | None = None,
|
| 685 |
+
) -> dict[str, Any]:
|
| 686 |
+
"""Probes one FR3 arm read-only via pylibfranka, falling back to rest FK."""
|
| 687 |
+
reachable = (
|
| 688 |
+
tcp_port_reachable(ip, timeout_s=timeout_s)
|
| 689 |
+
if tcp_reachable is None
|
| 690 |
+
else bool(tcp_reachable)
|
| 691 |
+
)
|
| 692 |
+
q_fallback = np.asarray(
|
| 693 |
+
rest_pose_rad
|
| 694 |
+
if rest_pose_rad is not None
|
| 695 |
+
else fr3_mjcf.DEFAULT_REST_POSE_RAD[side],
|
| 696 |
+
dtype=np.float64,
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
if not reachable:
|
| 700 |
+
tcp_pos, _ = fr3_kinematics.compute_arm_fk(mj_model, side, q_fallback)
|
| 701 |
+
err_msg = f"FR3 {side} arm ({ip}): TCP port 1337 unreachable."
|
| 702 |
+
return {
|
| 703 |
+
"connected": False,
|
| 704 |
+
"connection_error": err_msg,
|
| 705 |
+
"q_rad": [round(float(x), 6) for x in q_fallback],
|
| 706 |
+
"tcp_pos_base_m": [round(float(x), 5) for x in tcp_pos],
|
| 707 |
+
"fk_pos_error_m": 0.0,
|
| 708 |
+
"free_air_force_norm_n": 0.0,
|
| 709 |
+
"current_errors": [],
|
| 710 |
+
"desk_audit": None,
|
| 711 |
+
"warnings": [err_msg],
|
| 712 |
+
"advisories": [],
|
| 713 |
+
}
|
| 714 |
+
|
| 715 |
+
robot: Any = None
|
| 716 |
+
try:
|
| 717 |
+
robot = _open_pylibfranka_robot(ip, realtime_cfg_name)
|
| 718 |
+
hw = read_pylibfranka_state(robot)
|
| 719 |
+
q_rad = np.asarray(hw["q"], dtype=np.float64)
|
| 720 |
+
tau_j = np.asarray(hw["tau_j"], dtype=np.float64)
|
| 721 |
+
o_t_ee_4x4 = unpack_o_t_ee(hw["o_t_ee"])
|
| 722 |
+
|
| 723 |
+
t_base_link0 = compute_link0_in_base_transform_for_model(mj_model, side)
|
| 724 |
+
r_base_link0 = t_base_link0[:3, :3]
|
| 725 |
+
tcp_pos_base, _ = fr3_kinematics.compute_arm_fk(mj_model, side, q_rad)
|
| 726 |
+
fk_err_m = compute_fk_pos_error_m(
|
| 727 |
+
tcp_pos_base,
|
| 728 |
+
t_base_link0,
|
| 729 |
+
o_t_ee_4x4,
|
| 730 |
+
tcp_offset_z_m,
|
| 731 |
+
hw.get("f_t_ee"),
|
| 732 |
+
mj_model=mj_model,
|
| 733 |
+
side=side,
|
| 734 |
+
q_rad=q_rad,
|
| 735 |
+
)
|
| 736 |
+
wrench_6d = compute_ext_wrench_base_6d(
|
| 737 |
+
hw, mj_model, side, q_rad, tau_j, r_base_link0
|
| 738 |
+
)
|
| 739 |
+
force_norm_n = float(np.linalg.norm(wrench_6d[:3]))
|
| 740 |
+
desk_audit = audit_arm_desk_config(side, hw, r_base_link0)
|
| 741 |
+
readout = {
|
| 742 |
+
"connected": True,
|
| 743 |
+
"connection_error": None,
|
| 744 |
+
"q_rad": [round(float(x), 6) for x in q_rad],
|
| 745 |
+
"tcp_pos_base_m": [round(float(x), 5) for x in tcp_pos_base],
|
| 746 |
+
"fk_pos_error_m": round(fk_err_m, 6),
|
| 747 |
+
"free_air_force_norm_n": round(force_norm_n, 3),
|
| 748 |
+
"current_errors": list(hw.get("current_errors") or []),
|
| 749 |
+
"desk_audit": desk_audit,
|
| 750 |
+
"advisories": list((desk_audit or {}).get("advisories") or []),
|
| 751 |
+
}
|
| 752 |
+
readout["warnings"] = validate_arm_readiness(side, readout)
|
| 753 |
+
return readout
|
| 754 |
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
| 755 |
+
tcp_pos, _ = fr3_kinematics.compute_arm_fk(mj_model, side, q_fallback)
|
| 756 |
+
err_msg = str(exc)
|
| 757 |
+
return {
|
| 758 |
+
"connected": False,
|
| 759 |
+
"connection_error": err_msg,
|
| 760 |
+
"q_rad": [round(float(x), 6) for x in q_fallback],
|
| 761 |
+
"tcp_pos_base_m": [round(float(x), 5) for x in tcp_pos],
|
| 762 |
+
"fk_pos_error_m": 0.0,
|
| 763 |
+
"free_air_force_norm_n": 0.0,
|
| 764 |
+
"current_errors": [],
|
| 765 |
+
"desk_audit": None,
|
| 766 |
+
"warnings": [err_msg],
|
| 767 |
+
"advisories": [],
|
| 768 |
+
}
|
| 769 |
+
finally:
|
| 770 |
+
disconnect_pylibfranka_robot(robot)
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def read_arm_joints_or_rest(
|
| 774 |
+
config: RobotConfig | Mapping[str, Any],
|
| 775 |
+
*,
|
| 776 |
+
realtime_mode: str = "auto",
|
| 777 |
+
timeout_s: float = 0.25,
|
| 778 |
+
) -> tuple[list[float], list[float], list[str]]:
|
| 779 |
+
"""Reads live joint angles per reachable arm, else `rest_pose_rad`."""
|
| 780 |
+
cfg = normalize_robot_config(config)
|
| 781 |
+
rt_info = resolve_realtime_config(realtime_mode)
|
| 782 |
+
rt_name = str(rt_info["realtime_config"])
|
| 783 |
+
out_q: dict[str, list[float]] = {}
|
| 784 |
+
warnings: list[str] = []
|
| 785 |
+
|
| 786 |
+
for side in ("left", "right"):
|
| 787 |
+
arm_cfg = cfg.arms[side]
|
| 788 |
+
fallback = list(arm_cfg.rest_pose_rad)
|
| 789 |
+
if not arm_cfg.enabled:
|
| 790 |
+
out_q[side] = fallback
|
| 791 |
+
continue
|
| 792 |
+
if not tcp_port_reachable(arm_cfg.ip, timeout_s=timeout_s):
|
| 793 |
+
warnings.append(
|
| 794 |
+
f"{side} ({arm_cfg.ip}): TCP port 1337 unreachable; using rest pose"
|
| 795 |
+
)
|
| 796 |
+
out_q[side] = fallback
|
| 797 |
+
continue
|
| 798 |
+
robot: Any = None
|
| 799 |
+
try:
|
| 800 |
+
robot = _open_pylibfranka_robot(arm_cfg.ip, rt_name)
|
| 801 |
+
hw = read_pylibfranka_state(robot)
|
| 802 |
+
out_q[side] = [float(x) for x in hw["q"]]
|
| 803 |
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
| 804 |
+
warnings.append(f"{side} ({arm_cfg.ip}): {exc}; using rest pose")
|
| 805 |
+
out_q[side] = fallback
|
| 806 |
+
finally:
|
| 807 |
+
disconnect_pylibfranka_robot(robot)
|
| 808 |
+
|
| 809 |
+
return out_q["left"], out_q["right"], warnings
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
def _read_ctrl_state(
|
| 813 |
+
st: Any,
|
| 814 |
+
fallback_q: np.ndarray,
|
| 815 |
+
fallback_dq: np.ndarray,
|
| 816 |
+
fallback_ddq: np.ndarray,
|
| 817 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 818 |
+
return (
|
| 819 |
+
np.asarray(getattr(st, "q_d", fallback_q), dtype=np.float64),
|
| 820 |
+
np.asarray(getattr(st, "dq_d", fallback_dq), dtype=np.float64),
|
| 821 |
+
np.asarray(getattr(st, "ddq_d", fallback_ddq), dtype=np.float64),
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
def _handle_worker_abort(
|
| 826 |
+
ctrl: Any,
|
| 827 |
+
pylibfranka: Any,
|
| 828 |
+
ref_q: np.ndarray,
|
| 829 |
+
ref_dq: np.ndarray,
|
| 830 |
+
ref_ddq: np.ndarray,
|
| 831 |
+
) -> np.ndarray:
|
| 832 |
+
"""Executes 250 ms Hermite deceleration and settling to zero velocity."""
|
| 833 |
+
stop_steps = 250
|
| 834 |
+
hermite_q = ref_q.copy()
|
| 835 |
+
dq_at_abort = ref_dq.copy()
|
| 836 |
+
cur_q, cur_dq, cur_ddq = ref_q.copy(), ref_dq.copy(), ref_ddq.copy()
|
| 837 |
+
for s_idx in range(1, stop_steps + 1):
|
| 838 |
+
if s_idx > 1:
|
| 839 |
+
abort_state, _ = ctrl.readOnce()
|
| 840 |
+
cur_q, cur_dq, cur_ddq = _read_ctrl_state(
|
| 841 |
+
abort_state, cur_q, cur_dq, cur_ddq
|
| 842 |
+
)
|
| 843 |
+
hermite_q, hermite_dq = compute_abort_deceleration_step(
|
| 844 |
+
hermite_q,
|
| 845 |
+
dq_at_abort,
|
| 846 |
+
s_idx,
|
| 847 |
+
stop_steps=stop_steps,
|
| 848 |
+
dt_s=0.001,
|
| 849 |
+
)
|
| 850 |
+
cmd_q, cur_dq, cur_ddq = limit_rate_joint_positions(
|
| 851 |
+
hermite_q,
|
| 852 |
+
cur_q,
|
| 853 |
+
cur_dq,
|
| 854 |
+
cur_ddq,
|
| 855 |
+
dq_ff=hermite_dq,
|
| 856 |
+
dt_s=0.001,
|
| 857 |
+
)
|
| 858 |
+
cur_q = cmd_q
|
| 859 |
+
ctrl.writeOnce(pylibfranka.JointPositions(cmd_q.tolist()))
|
| 860 |
+
|
| 861 |
+
q_hold = cur_q.copy()
|
| 862 |
+
for settle_idx in range(250):
|
| 863 |
+
settle_state, _ = ctrl.readOnce()
|
| 864 |
+
cur_q, cur_dq, cur_ddq = _read_ctrl_state(
|
| 865 |
+
settle_state, cur_q, cur_dq, cur_ddq
|
| 866 |
+
)
|
| 867 |
+
if (
|
| 868 |
+
float(np.max(np.abs(cur_dq))) <= 1e-5
|
| 869 |
+
and float(np.max(np.abs(cur_ddq))) <= 1e-2
|
| 870 |
+
):
|
| 871 |
+
jp_done = pylibfranka.JointPositions(cur_q.tolist())
|
| 872 |
+
jp_done.motion_finished = True
|
| 873 |
+
ctrl.writeOnce(jp_done)
|
| 874 |
+
break
|
| 875 |
+
cmd_q, cur_dq, cur_ddq = limit_rate_joint_positions(
|
| 876 |
+
q_hold,
|
| 877 |
+
cur_q,
|
| 878 |
+
cur_dq,
|
| 879 |
+
cur_ddq,
|
| 880 |
+
dq_ff=np.zeros(7, dtype=np.float64),
|
| 881 |
+
dt_s=0.001,
|
| 882 |
+
)
|
| 883 |
+
cur_q = cmd_q
|
| 884 |
+
jp = pylibfranka.JointPositions(cmd_q.tolist())
|
| 885 |
+
if settle_idx == 249:
|
| 886 |
+
jp.motion_finished = True
|
| 887 |
+
ctrl.writeOnce(jp)
|
| 888 |
+
return cur_q
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
def _run_worker_trajectory(
|
| 892 |
+
robot: Any,
|
| 893 |
+
pylibfranka: Any,
|
| 894 |
+
traj_raw: np.ndarray,
|
| 895 |
+
abort_event: Any,
|
| 896 |
+
) -> dict[str, Any]:
|
| 897 |
+
"""Streams one `(N, 7)` spline over 1 kHz FCI with abort decel & trace."""
|
| 898 |
+
travelled: list[list[float]] = []
|
| 899 |
+
aborted = False
|
| 900 |
+
tick_trace: collections.deque[str] = collections.deque(maxlen=8)
|
| 901 |
+
gc.disable()
|
| 902 |
+
try:
|
| 903 |
+
coll_fn = getattr(robot, "set_collision_behavior", None)
|
| 904 |
+
if callable(coll_fn):
|
| 905 |
+
coll_fn([20.0] * 7, [20.0] * 7, [20.0] * 6, [20.0] * 6)
|
| 906 |
+
|
| 907 |
+
ctrl = robot.start_joint_position_control(
|
| 908 |
+
pylibfranka.ControllerMode.JointImpedance
|
| 909 |
+
)
|
| 910 |
+
n_total = int(traj_raw.shape[0])
|
| 911 |
+
traj_exec = traj_raw
|
| 912 |
+
time_elapsed_s = 0.0
|
| 913 |
+
is_first_tick = True
|
| 914 |
+
prev_q = traj_raw[0].copy()
|
| 915 |
+
prev_dq = np.zeros(7, dtype=np.float64)
|
| 916 |
+
prev_ddq = np.zeros(7, dtype=np.float64)
|
| 917 |
+
tick_num = 0
|
| 918 |
+
|
| 919 |
+
while True:
|
| 920 |
+
state, duration = ctrl.readOnce()
|
| 921 |
+
tick_num += 1
|
| 922 |
+
dur_ms = (
|
| 923 |
+
float(duration.to_sec()) * 1000.0
|
| 924 |
+
if hasattr(duration, "to_sec")
|
| 925 |
+
else 1.0
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
if is_first_tick:
|
| 929 |
+
q_anchor = getattr(state, "q_d", getattr(state, "q", traj_raw[0]))
|
| 930 |
+
traj_exec = blend_start_pose_offset(traj_raw, q_anchor)
|
| 931 |
+
prev_q = np.asarray(q_anchor, dtype=np.float64).copy()
|
| 932 |
+
prev_dq = np.asarray(
|
| 933 |
+
getattr(state, "dq_d", np.zeros(7)), dtype=np.float64
|
| 934 |
+
).copy()
|
| 935 |
+
prev_ddq = np.asarray(
|
| 936 |
+
getattr(state, "ddq_d", np.zeros(7)), dtype=np.float64
|
| 937 |
+
).copy()
|
| 938 |
+
|
| 939 |
+
time_elapsed_s, idx, _ = step_realtime_trajectory_index(
|
| 940 |
+
time_elapsed_s,
|
| 941 |
+
duration,
|
| 942 |
+
is_first_tick=is_first_tick,
|
| 943 |
+
n_total=n_total,
|
| 944 |
+
dt_s=0.001,
|
| 945 |
+
)
|
| 946 |
+
is_first_tick = False
|
| 947 |
+
|
| 948 |
+
if idx % 25 == 0 or idx == n_total - 1:
|
| 949 |
+
travelled.append(clamp_q_to_padded_limits(prev_q).tolist())
|
| 950 |
+
|
| 951 |
+
ref_q, ref_dq, ref_ddq = _read_ctrl_state(
|
| 952 |
+
state, prev_q, prev_dq, prev_ddq
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
if abort_event.is_set():
|
| 956 |
+
aborted = True
|
| 957 |
+
prev_q = _handle_worker_abort(ctrl, pylibfranka, ref_q, ref_dq, ref_ddq)
|
| 958 |
+
travelled.append(clamp_q_to_padded_limits(prev_q).tolist())
|
| 959 |
+
break
|
| 960 |
+
|
| 961 |
+
target_q = traj_exec[idx]
|
| 962 |
+
target_dq_ff = (
|
| 963 |
+
(traj_exec[idx] - traj_exec[idx - 1]) / 0.001
|
| 964 |
+
if 0 < idx < n_total - 1
|
| 965 |
+
else np.zeros(7, dtype=np.float64)
|
| 966 |
+
)
|
| 967 |
+
cmd_q, prev_dq, prev_ddq = limit_rate_joint_positions(
|
| 968 |
+
target_q, ref_q, ref_dq, ref_ddq, dq_ff=target_dq_ff, dt_s=0.001
|
| 969 |
+
)
|
| 970 |
+
prev_q = cmd_q
|
| 971 |
+
at_goal = (
|
| 972 |
+
idx >= n_total - 1
|
| 973 |
+
and float(np.max(np.abs(ref_q - traj_exec[-1]))) <= 1e-4
|
| 974 |
+
and float(np.max(np.abs(ref_dq))) <= 1e-5
|
| 975 |
+
and float(np.max(np.abs(prev_dq))) <= 1e-5
|
| 976 |
+
and float(np.max(np.abs(ref_ddq))) <= 1e-2
|
| 977 |
+
)
|
| 978 |
+
if at_goal or time_elapsed_s >= (n_total * 0.001 + 5.0):
|
| 979 |
+
jp = pylibfranka.JointPositions(ref_q.tolist())
|
| 980 |
+
jp.motion_finished = True
|
| 981 |
+
tick_trace.append(
|
| 982 |
+
f"t={tick_num} idx={idx}/{n_total} dur={dur_ms:.2f}ms "
|
| 983 |
+
f"FIN d_q={float(np.max(np.abs(cmd_q - ref_q))):.2e} "
|
| 984 |
+
f"ref_dq={float(np.max(np.abs(ref_dq))):.2e} "
|
| 985 |
+
f"ref_ddq={float(np.max(np.abs(ref_ddq))):.2e}"
|
| 986 |
+
)
|
| 987 |
+
ctrl.writeOnce(jp)
|
| 988 |
+
break
|
| 989 |
+
tick_trace.append(
|
| 990 |
+
f"t={tick_num} idx={idx}/{n_total} dur={dur_ms:.2f}ms "
|
| 991 |
+
f"d_q={float(np.max(np.abs(cmd_q - ref_q))):.2e} "
|
| 992 |
+
f"ref_dq={float(np.max(np.abs(ref_dq))):.2e} "
|
| 993 |
+
f"cmd_dq={float(np.max(np.abs(prev_dq))):.2e} "
|
| 994 |
+
f"ref_ddq={float(np.max(np.abs(ref_ddq))):.2e} "
|
| 995 |
+
f"cmd_ddq={float(np.max(np.abs(prev_ddq))):.2e}"
|
| 996 |
+
)
|
| 997 |
+
ctrl.writeOnce(pylibfranka.JointPositions(cmd_q.tolist()))
|
| 998 |
+
|
| 999 |
+
final_state = read_pylibfranka_state(robot)
|
| 1000 |
+
return {
|
| 1001 |
+
"ok": True,
|
| 1002 |
+
"aborted": aborted,
|
| 1003 |
+
"travelled": travelled,
|
| 1004 |
+
"state": final_state,
|
| 1005 |
+
}
|
| 1006 |
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
| 1007 |
+
trace_tail = " | ".join(tick_trace)
|
| 1008 |
+
err_str = f"{exc} [trace: {trace_tail}]" if trace_tail else str(exc)
|
| 1009 |
+
return {"ok": False, "error": err_str, "travelled": travelled}
|
| 1010 |
+
finally:
|
| 1011 |
+
gc.enable()
|
| 1012 |
+
gc.collect()
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def _arm_worker_loop(
|
| 1016 |
+
ip: str,
|
| 1017 |
+
realtime_cfg_name: str,
|
| 1018 |
+
cmd_conn: Any,
|
| 1019 |
+
abort_event: Any,
|
| 1020 |
+
) -> None:
|
| 1021 |
+
"""Dedicated 1 kHz `pylibfranka` child process avoiding GIL contention."""
|
| 1022 |
+
robot: Any = None
|
| 1023 |
+
try:
|
| 1024 |
+
pylibfranka = _require_pylibfranka()
|
| 1025 |
+
robot = _open_pylibfranka_robot(ip, realtime_cfg_name)
|
| 1026 |
+
|
| 1027 |
+
# Initial worker spawn only opens pylibfranka; callers send op="recover"
|
| 1028 |
+
# explicitly when clearing FCI errors before actuation.
|
| 1029 |
+
cmd_conn.send({"ok": True})
|
| 1030 |
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
| 1031 |
+
disconnect_pylibfranka_robot(robot)
|
| 1032 |
+
cmd_conn.send({"ok": False, "error": str(exc)})
|
| 1033 |
+
return
|
| 1034 |
+
|
| 1035 |
+
try:
|
| 1036 |
+
while True:
|
| 1037 |
+
msg = cmd_conn.recv()
|
| 1038 |
+
op = msg.get("op")
|
| 1039 |
+
if op == "close":
|
| 1040 |
+
disconnect_pylibfranka_robot(robot)
|
| 1041 |
+
robot = None
|
| 1042 |
+
cmd_conn.send({"ok": True})
|
| 1043 |
+
break
|
| 1044 |
+
if op in ("read", "recover"):
|
| 1045 |
+
try:
|
| 1046 |
+
if op == "read":
|
| 1047 |
+
cmd_conn.send({"ok": True, "state": read_pylibfranka_state(robot)})
|
| 1048 |
+
else:
|
| 1049 |
+
cmd_conn.send(
|
| 1050 |
+
{"ok": True, "result": recover_pylibfranka_errors(robot)}
|
| 1051 |
+
)
|
| 1052 |
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
| 1053 |
+
cmd_conn.send({"ok": False, "error": str(exc)})
|
| 1054 |
+
continue
|
| 1055 |
+
if op == "trajectory":
|
| 1056 |
+
traj_raw = np.asarray(msg["traj"], dtype=np.float64)
|
| 1057 |
+
cmd_conn.send(
|
| 1058 |
+
_run_worker_trajectory(robot, pylibfranka, traj_raw, abort_event)
|
| 1059 |
+
)
|
| 1060 |
+
finally:
|
| 1061 |
+
disconnect_pylibfranka_robot(robot)
|
| 1062 |
+
robot = None
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
class ArmWorkerProcess:
|
| 1066 |
+
"""Parent-side handle to a dedicated 1 kHz per-arm child process."""
|
| 1067 |
+
|
| 1068 |
+
def __init__(self, arm: str, ip: str, realtime_cfg_name: str) -> None:
|
| 1069 |
+
"""Configures IPC pipe and abort event for one arm worker process."""
|
| 1070 |
+
self.arm = arm
|
| 1071 |
+
self.ip = ip
|
| 1072 |
+
self.realtime_cfg_name = realtime_cfg_name
|
| 1073 |
+
self._ctx = mp.get_context("spawn")
|
| 1074 |
+
self._parent_conn: Any = None
|
| 1075 |
+
self._proc: Any = None
|
| 1076 |
+
self._abort_event = self._ctx.Event()
|
| 1077 |
+
|
| 1078 |
+
def start(self, timeout_s: float = 10.0) -> None:
|
| 1079 |
+
"""Spawns the 1 kHz child process and waits for FCI connection."""
|
| 1080 |
+
parent_conn, child_conn = self._ctx.Pipe()
|
| 1081 |
+
self._parent_conn = parent_conn
|
| 1082 |
+
self._proc = self._ctx.Process(
|
| 1083 |
+
target=_arm_worker_loop,
|
| 1084 |
+
args=(self.ip, self.realtime_cfg_name, child_conn, self._abort_event),
|
| 1085 |
+
daemon=True,
|
| 1086 |
+
)
|
| 1087 |
+
self._proc.start()
|
| 1088 |
+
if not parent_conn.poll(timeout_s):
|
| 1089 |
+
self.stop()
|
| 1090 |
+
raise TimeoutError(
|
| 1091 |
+
f"Timed out connecting to FR3 {self.arm} arm at {self.ip}"
|
| 1092 |
+
)
|
| 1093 |
+
reply = parent_conn.recv()
|
| 1094 |
+
if not reply.get("ok"):
|
| 1095 |
+
self.stop()
|
| 1096 |
+
raise RuntimeError(
|
| 1097 |
+
f"Failed to initialize FR3 {self.arm} arm ({self.ip}): "
|
| 1098 |
+
f"{reply.get('error')}"
|
| 1099 |
+
)
|
| 1100 |
+
|
| 1101 |
+
def _send_rpc(self, op: str, action: str) -> dict[str, Any]:
|
| 1102 |
+
self._parent_conn.send({"op": op})
|
| 1103 |
+
reply = self._parent_conn.recv()
|
| 1104 |
+
if not reply.get("ok"):
|
| 1105 |
+
raise RuntimeError(
|
| 1106 |
+
f"FR3 {self.arm} {action} failed: {reply.get('error')}"
|
| 1107 |
+
)
|
| 1108 |
+
return reply
|
| 1109 |
+
|
| 1110 |
+
def read_state(self) -> dict[str, Any]:
|
| 1111 |
+
"""Requests one read-only FCI state snapshot from the worker."""
|
| 1112 |
+
return self._send_rpc("read", "state read")["state"]
|
| 1113 |
+
|
| 1114 |
+
def recover_errors(self) -> dict[str, Any]:
|
| 1115 |
+
"""Checks FCI errors/reflex and runs automatic recovery if needed."""
|
| 1116 |
+
return self._send_rpc("recover", "error recovery")["result"]
|
| 1117 |
+
|
| 1118 |
+
def send_trajectory_async(self, traj: np.ndarray) -> None:
|
| 1119 |
+
"""Clears the abort flag and sends a 1 kHz joint spline to execute."""
|
| 1120 |
+
self._abort_event.clear()
|
| 1121 |
+
self._parent_conn.send({"op": "trajectory", "traj": traj})
|
| 1122 |
+
|
| 1123 |
+
def signal_abort(self) -> None:
|
| 1124 |
+
"""Signals the active worker loop to decelerate smoothly and stop."""
|
| 1125 |
+
self._abort_event.set()
|
| 1126 |
+
|
| 1127 |
+
def poll_done(self, timeout_s: float = 0.005) -> dict[str, Any] | None:
|
| 1128 |
+
"""Polls for trajectory completion and returns the worker reply if ready."""
|
| 1129 |
+
if self._parent_conn.poll(timeout_s):
|
| 1130 |
+
return self._parent_conn.recv()
|
| 1131 |
+
return None
|
| 1132 |
+
|
| 1133 |
+
def stop(self) -> None:
|
| 1134 |
+
"""Aborts any motion, closes the worker process, and cleans up IPC."""
|
| 1135 |
+
try:
|
| 1136 |
+
if self._proc is not None and self._proc.is_alive():
|
| 1137 |
+
try:
|
| 1138 |
+
self._abort_event.set()
|
| 1139 |
+
if self._parent_conn is not None:
|
| 1140 |
+
self._parent_conn.send({"op": "close"})
|
| 1141 |
+
if self._parent_conn.poll(1.0):
|
| 1142 |
+
self._parent_conn.recv()
|
| 1143 |
+
except (OSError, EOFError):
|
| 1144 |
+
# Ignore broken/closed pipe errors when worker has already exited.
|
| 1145 |
+
pass
|
| 1146 |
+
self._proc.join(timeout=1.5)
|
| 1147 |
+
if self._proc.is_alive():
|
| 1148 |
+
self._proc.terminate()
|
| 1149 |
+
self._proc.join(timeout=0.5)
|
| 1150 |
+
finally:
|
| 1151 |
+
if self._parent_conn is not None:
|
| 1152 |
+
try:
|
| 1153 |
+
self._parent_conn.close()
|
| 1154 |
+
except OSError:
|
| 1155 |
+
pass
|
| 1156 |
+
self._parent_conn = None
|
| 1157 |
+
if self._proc is not None:
|
| 1158 |
+
try:
|
| 1159 |
+
self._proc.close()
|
| 1160 |
+
except (OSError, ValueError):
|
| 1161 |
+
pass
|
| 1162 |
+
self._proc = None
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/fr3_camera_controller.py
ADDED
|
@@ -0,0 +1,1131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Linux V4L2 / OpenCV camera rig layer for the Franka Research 3 Duo platform.
|
| 16 |
+
|
| 17 |
+
Supports:
|
| 18 |
+
- ZED Mini side-by-side stereo UVC capture (`2560x720` -> `head_camera_left` &
|
| 19 |
+
`head_camera_right` `1280x720` RGB views) + factory `.conf` rectification.
|
| 20 |
+
- Dual wrist RealSense D405 RGB UVC capture (`wrist_camera_left` &
|
| 21 |
+
`wrist_camera_right`) resolved by USB serial or `/dev/v4l/by-id/`.
|
| 22 |
+
- In-process MuJoCo rendering via `Fr3DuoRobot.render_sim_cameras(...)`
|
| 23 |
+
and `--dry-run` synthetic frames.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
from collections.abc import Mapping, Sequence
|
| 29 |
+
import configparser
|
| 30 |
+
from dataclasses import dataclass
|
| 31 |
+
import os
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
import time
|
| 34 |
+
from typing import Any
|
| 35 |
+
|
| 36 |
+
import numpy as np
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
import cv2 # pytype: disable=import-error
|
| 40 |
+
except ImportError:
|
| 41 |
+
cv2: Any = None
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
import grp # pytype: disable=import-error
|
| 45 |
+
except ImportError:
|
| 46 |
+
grp: Any = None
|
| 47 |
+
|
| 48 |
+
CANONICAL_CAMERAS = (
|
| 49 |
+
"head_camera_left",
|
| 50 |
+
"head_camera_right",
|
| 51 |
+
"wrist_camera_left",
|
| 52 |
+
"wrist_camera_right",
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
ZED_VENDOR_ID = "2b03"
|
| 56 |
+
INTEL_VENDOR_ID = "8086"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def require_cv2() -> Any:
|
| 60 |
+
"""Returns the imported `cv2` module or raises `RuntimeError` if absent."""
|
| 61 |
+
if cv2 is None:
|
| 62 |
+
raise RuntimeError(
|
| 63 |
+
"opencv-python is required for camera/video operations. "
|
| 64 |
+
"Install with: pip install opencv-python"
|
| 65 |
+
)
|
| 66 |
+
return cv2
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@dataclass
|
| 70 |
+
class CameraFrame:
|
| 71 |
+
"""Single RGB camera frame with monotonic capture timestamp."""
|
| 72 |
+
|
| 73 |
+
name: str
|
| 74 |
+
rgb: np.ndarray
|
| 75 |
+
timestamp_s: float
|
| 76 |
+
width: int
|
| 77 |
+
height: int
|
| 78 |
+
backend: str
|
| 79 |
+
|
| 80 |
+
def age_s(self, now_s: float | None = None) -> float:
|
| 81 |
+
"""Returns frame age in seconds relative to `now_s` or monotonic time."""
|
| 82 |
+
ref_s = time.monotonic() if now_s is None else float(now_s)
|
| 83 |
+
return float(ref_s - float(self.timestamp_s))
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def brightness_mean(self) -> float:
|
| 87 |
+
"""Mean pixel intensity in [0.0, 255.0]."""
|
| 88 |
+
return float(np.mean(self.rgb)) if self.rgb.size else 0.0
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def pixel_std(self) -> float:
|
| 92 |
+
"""Standard deviation of pixel intensities across the RGB frame."""
|
| 93 |
+
return float(np.std(self.rgb)) if self.rgb.size else 0.0
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@dataclass
|
| 97 |
+
class CameraStreamSpec:
|
| 98 |
+
"""Configuration for one logical or stereo camera stream."""
|
| 99 |
+
|
| 100 |
+
role: str
|
| 101 |
+
serial: str = ""
|
| 102 |
+
device_path: str = ""
|
| 103 |
+
width: int = 1280
|
| 104 |
+
height: int = 720
|
| 105 |
+
fps: int = 30
|
| 106 |
+
zed_conf_path: str = ""
|
| 107 |
+
|
| 108 |
+
@classmethod
|
| 109 |
+
def from_mapping(
|
| 110 |
+
cls, role: str, data: CameraStreamSpec | Mapping[str, Any]
|
| 111 |
+
) -> CameraStreamSpec:
|
| 112 |
+
"""Builds a `CameraStreamSpec` from an existing spec or mapping."""
|
| 113 |
+
if isinstance(data, CameraStreamSpec):
|
| 114 |
+
return data
|
| 115 |
+
return cls(
|
| 116 |
+
role=str(data.get("role", role)),
|
| 117 |
+
serial=str(data.get("serial", "")),
|
| 118 |
+
device_path=str(data.get("device_path", "")),
|
| 119 |
+
width=int(data.get("width", 1280)),
|
| 120 |
+
height=int(data.get("height", 720)),
|
| 121 |
+
fps=int(data.get("fps", 30)),
|
| 122 |
+
zed_conf_path=str(data.get("zed_conf_path", "")),
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _read_sysfs_text(path: Path) -> str:
|
| 127 |
+
try:
|
| 128 |
+
return path.read_text(encoding="utf-8", errors="ignore").strip()
|
| 129 |
+
except OSError:
|
| 130 |
+
return ""
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _valid_usb_serial(raw: str) -> str:
|
| 134 |
+
if ":" in raw or raw.lower() in ("", "unknown", "none", "null", "0", "ov580"):
|
| 135 |
+
return ""
|
| 136 |
+
return raw
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _inspect_usb_ancestors(sys_video_dir: Path) -> dict[str, str]:
|
| 140 |
+
"""Reads USB attributes from sysfs ancestors of a video4linux node."""
|
| 141 |
+
info = {
|
| 142 |
+
"vendor_id": "",
|
| 143 |
+
"product_id": "",
|
| 144 |
+
"serial": "",
|
| 145 |
+
"speed_mbps": "",
|
| 146 |
+
"interface": "",
|
| 147 |
+
"busnum": "",
|
| 148 |
+
"power_control": "",
|
| 149 |
+
}
|
| 150 |
+
try:
|
| 151 |
+
dev_dir = sys_video_dir / "device"
|
| 152 |
+
info["interface"] = _read_sysfs_text(dev_dir / "interface")
|
| 153 |
+
info["power_control"] = _read_sysfs_text(dev_dir / "power" / "control")
|
| 154 |
+
cur = dev_dir.resolve()
|
| 155 |
+
info["interface"] = info["interface"] or _read_sysfs_text(cur / "interface")
|
| 156 |
+
info["power_control"] = info["power_control"] or _read_sysfs_text(
|
| 157 |
+
cur / "power" / "control"
|
| 158 |
+
)
|
| 159 |
+
except OSError:
|
| 160 |
+
return info
|
| 161 |
+
|
| 162 |
+
for _ in range(6):
|
| 163 |
+
found_usb = (cur / "idVendor").is_file() or (cur / "idProduct").is_file()
|
| 164 |
+
if not info["vendor_id"] and (cur / "idVendor").is_file():
|
| 165 |
+
info["vendor_id"] = _read_sysfs_text(cur / "idVendor").lower()
|
| 166 |
+
if not info["product_id"] and (cur / "idProduct").is_file():
|
| 167 |
+
info["product_id"] = _read_sysfs_text(cur / "idProduct").lower()
|
| 168 |
+
if not info["serial"] and (cur / "serial").is_file():
|
| 169 |
+
info["serial"] = _valid_usb_serial(_read_sysfs_text(cur / "serial"))
|
| 170 |
+
if not info["speed_mbps"] and (cur / "speed").is_file():
|
| 171 |
+
info["speed_mbps"] = _read_sysfs_text(cur / "speed")
|
| 172 |
+
if not info["busnum"] and (cur / "busnum").is_file():
|
| 173 |
+
info["busnum"] = _read_sysfs_text(cur / "busnum")
|
| 174 |
+
if not info["power_control"] and (cur / "power" / "control").is_file():
|
| 175 |
+
info["power_control"] = _read_sysfs_text(cur / "power" / "control")
|
| 176 |
+
if found_usb:
|
| 177 |
+
# ZED Mini OV580 video interfaces often omit iSerialNumber while the
|
| 178 |
+
# companion ZED HID MCU (2b03) exposes the factory serial on the same bus.
|
| 179 |
+
if info["vendor_id"] == ZED_VENDOR_ID and not info["serial"]:
|
| 180 |
+
search_dirs: list[Path] = []
|
| 181 |
+
if cur.parent != cur:
|
| 182 |
+
search_dirs.extend(sorted(cur.parent.iterdir(), key=lambda p: p.name))
|
| 183 |
+
if cur.parent.parent != cur.parent:
|
| 184 |
+
search_dirs.extend(
|
| 185 |
+
sorted(cur.parent.parent.glob("usb*/*"), key=lambda p: p.name)
|
| 186 |
+
)
|
| 187 |
+
if (
|
| 188 |
+
str(sys_video_dir).startswith("/sys")
|
| 189 |
+
and Path("/sys/bus/usb/devices").is_dir()
|
| 190 |
+
):
|
| 191 |
+
search_dirs.extend(
|
| 192 |
+
sorted(
|
| 193 |
+
Path("/sys/bus/usb/devices").iterdir(), key=lambda p: p.name
|
| 194 |
+
)
|
| 195 |
+
)
|
| 196 |
+
for sib in search_dirs:
|
| 197 |
+
if sib == cur or not sib.is_dir():
|
| 198 |
+
continue
|
| 199 |
+
if _read_sysfs_text(sib / "idVendor").lower() == ZED_VENDOR_ID:
|
| 200 |
+
sib_ser = _valid_usb_serial(_read_sysfs_text(sib / "serial"))
|
| 201 |
+
if sib_ser:
|
| 202 |
+
info["serial"] = sib_ser
|
| 203 |
+
break
|
| 204 |
+
break
|
| 205 |
+
if cur.parent == cur:
|
| 206 |
+
break
|
| 207 |
+
cur = cur.parent
|
| 208 |
+
|
| 209 |
+
return info
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _classify_camera_family(name: str, vendor_id: str) -> str | None:
|
| 213 |
+
lowered = name.lower()
|
| 214 |
+
vid = vendor_id.lower().removeprefix("0x")
|
| 215 |
+
if vid == ZED_VENDOR_ID or (not vid and "zed" in lowered):
|
| 216 |
+
return "zed"
|
| 217 |
+
if vid == INTEL_VENDOR_ID or (not vid and "realsense" in lowered):
|
| 218 |
+
return "realsense"
|
| 219 |
+
return None
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _collect_symlink_map(symlink_dir: Path) -> dict[str, str]:
|
| 223 |
+
mapping: dict[str, str] = {}
|
| 224 |
+
if not symlink_dir.is_dir():
|
| 225 |
+
return mapping
|
| 226 |
+
for symlink in sorted(symlink_dir.iterdir(), key=lambda p: p.name):
|
| 227 |
+
try:
|
| 228 |
+
resolved = os.path.realpath(str(symlink))
|
| 229 |
+
except OSError:
|
| 230 |
+
continue
|
| 231 |
+
if resolved not in mapping or "video-index0" in symlink.name:
|
| 232 |
+
mapping[resolved] = str(symlink)
|
| 233 |
+
return mapping
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def discover_uvc_devices(
|
| 237 |
+
*,
|
| 238 |
+
sys_v4l: Path = Path("/sys/class/video4linux"),
|
| 239 |
+
v4l_by_id: Path = Path("/dev/v4l/by-id"),
|
| 240 |
+
v4l_by_path: Path = Path("/dev/v4l/by-path"),
|
| 241 |
+
dev_root: Path = Path("/dev"),
|
| 242 |
+
) -> list[dict[str, Any]]:
|
| 243 |
+
"""Discovers ZED Mini and RealSense RGB V4L2 camera nodes on Linux."""
|
| 244 |
+
if not sys_v4l.is_dir():
|
| 245 |
+
return []
|
| 246 |
+
|
| 247 |
+
by_id_map = _collect_symlink_map(v4l_by_id)
|
| 248 |
+
by_path_map = _collect_symlink_map(v4l_by_path)
|
| 249 |
+
|
| 250 |
+
udev_aliases_by_resolved: dict[str, list[str]] = {}
|
| 251 |
+
if dev_root.is_dir():
|
| 252 |
+
for entry in sorted(dev_root.iterdir(), key=lambda p: p.name):
|
| 253 |
+
try:
|
| 254 |
+
if entry.is_symlink() and entry.name.lower().startswith(
|
| 255 |
+
("realsense", "zed")
|
| 256 |
+
):
|
| 257 |
+
udev_aliases_by_resolved.setdefault(
|
| 258 |
+
os.path.realpath(str(entry)), []
|
| 259 |
+
).append(str(entry))
|
| 260 |
+
except OSError:
|
| 261 |
+
continue
|
| 262 |
+
|
| 263 |
+
raw_v4l: list[dict[str, Any]] = []
|
| 264 |
+
rs_group_indices: dict[str, set[str]] = {}
|
| 265 |
+
rs_group_explicit_rgb: dict[str, bool] = {}
|
| 266 |
+
|
| 267 |
+
for vdir in sorted(sys_v4l.iterdir(), key=lambda p: p.name):
|
| 268 |
+
node_index = _read_sysfs_text(vdir / "index")
|
| 269 |
+
name = _read_sysfs_text(vdir / "name") or vdir.name
|
| 270 |
+
usb_info = _inspect_usb_ancestors(vdir)
|
| 271 |
+
family = _classify_camera_family(name, usb_info["vendor_id"])
|
| 272 |
+
if family is None:
|
| 273 |
+
continue
|
| 274 |
+
if node_index:
|
| 275 |
+
if family == "realsense":
|
| 276 |
+
try:
|
| 277 |
+
if int(node_index) % 2 != 0:
|
| 278 |
+
continue
|
| 279 |
+
except ValueError:
|
| 280 |
+
if node_index != "0":
|
| 281 |
+
continue
|
| 282 |
+
elif node_index != "0":
|
| 283 |
+
continue
|
| 284 |
+
|
| 285 |
+
cand_node = dev_root / vdir.name
|
| 286 |
+
dev_node = str(cand_node) if cand_node.exists() else f"/dev/{vdir.name}"
|
| 287 |
+
resolved_dev = os.path.realpath(dev_node)
|
| 288 |
+
try:
|
| 289 |
+
speed_val = (
|
| 290 |
+
float(usb_info["speed_mbps"]) if usb_info["speed_mbps"] else 0.0
|
| 291 |
+
)
|
| 292 |
+
except ValueError:
|
| 293 |
+
speed_val = 0.0
|
| 294 |
+
|
| 295 |
+
id_symlink = by_id_map.get(resolved_dev)
|
| 296 |
+
if id_symlink and os.path.realpath(id_symlink) == resolved_dev:
|
| 297 |
+
device_path = id_symlink
|
| 298 |
+
else:
|
| 299 |
+
device_path = by_path_map.get(resolved_dev, dev_node)
|
| 300 |
+
|
| 301 |
+
group_key = usb_info["serial"] or resolved_dev
|
| 302 |
+
if family == "realsense":
|
| 303 |
+
if node_index:
|
| 304 |
+
rs_group_indices.setdefault(group_key, set()).add(node_index)
|
| 305 |
+
combined_lower = f"{name} {usb_info['interface']}".lower()
|
| 306 |
+
if "rgb" in combined_lower or "color" in combined_lower:
|
| 307 |
+
rs_group_explicit_rgb[group_key] = True
|
| 308 |
+
|
| 309 |
+
raw_v4l.append({
|
| 310 |
+
"name": name,
|
| 311 |
+
"node_index": node_index,
|
| 312 |
+
"group_key": group_key,
|
| 313 |
+
"dev_node": dev_node,
|
| 314 |
+
"resolved_dev": resolved_dev,
|
| 315 |
+
"device_path": device_path,
|
| 316 |
+
"usb_info": usb_info,
|
| 317 |
+
"speed_val": speed_val,
|
| 318 |
+
"family": family,
|
| 319 |
+
})
|
| 320 |
+
|
| 321 |
+
devices: list[dict[str, Any]] = []
|
| 322 |
+
for item in raw_v4l:
|
| 323 |
+
usb_info = item["usb_info"]
|
| 324 |
+
ser = usb_info["serial"]
|
| 325 |
+
g_key = item["group_key"]
|
| 326 |
+
if item["family"] == "realsense":
|
| 327 |
+
# RGB-only: drop RealSense depth and IR nodes (D405 exposes index=0
|
| 328 |
+
# depth, index=2 RGB, index=4 IR).
|
| 329 |
+
combined = f"{item['name']} {usb_info['interface']}".lower()
|
| 330 |
+
has_rgb = "rgb" in combined or "color" in combined
|
| 331 |
+
if rs_group_explicit_rgb.get(g_key, False) or has_rgb:
|
| 332 |
+
if not has_rgb:
|
| 333 |
+
continue
|
| 334 |
+
elif "2" in rs_group_indices.get(g_key, set()):
|
| 335 |
+
if item["node_index"] != "2":
|
| 336 |
+
continue
|
| 337 |
+
elif any(
|
| 338 |
+
tok in usb_info["interface"].lower()
|
| 339 |
+
for tok in ("depth", "ir", "infra")
|
| 340 |
+
):
|
| 341 |
+
continue
|
| 342 |
+
|
| 343 |
+
item_aliases = list(udev_aliases_by_resolved.get(item["resolved_dev"], []))
|
| 344 |
+
side_hint = ""
|
| 345 |
+
if item["family"] == "realsense":
|
| 346 |
+
for alias in item_aliases:
|
| 347 |
+
alias_lower = Path(alias).name.lower()
|
| 348 |
+
if "left" in alias_lower:
|
| 349 |
+
side_hint = "left"
|
| 350 |
+
break
|
| 351 |
+
if "right" in alias_lower:
|
| 352 |
+
side_hint = "right"
|
| 353 |
+
break
|
| 354 |
+
|
| 355 |
+
v4l2_rw_ok = (
|
| 356 |
+
os.access(item["dev_node"], os.R_OK | os.W_OK)
|
| 357 |
+
if Path(item["dev_node"]).exists()
|
| 358 |
+
else None
|
| 359 |
+
)
|
| 360 |
+
devices.append({
|
| 361 |
+
"name": item["name"],
|
| 362 |
+
"family": item["family"],
|
| 363 |
+
"device_path": item["device_path"],
|
| 364 |
+
"video_node": item["dev_node"],
|
| 365 |
+
"serial": ser,
|
| 366 |
+
"vendor_id": usb_info["vendor_id"],
|
| 367 |
+
"product_id": usb_info["product_id"],
|
| 368 |
+
"busnum": usb_info["busnum"],
|
| 369 |
+
"usb_speed_mbps": item["speed_val"],
|
| 370 |
+
"is_usb3": bool(item["speed_val"] >= 5000.0),
|
| 371 |
+
"interface": usb_info["interface"],
|
| 372 |
+
"power_control": usb_info["power_control"],
|
| 373 |
+
"udev_aliases": item_aliases,
|
| 374 |
+
"side_hint": side_hint,
|
| 375 |
+
"v4l2_rw_ok": v4l2_rw_ok,
|
| 376 |
+
})
|
| 377 |
+
|
| 378 |
+
return devices
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def check_linux_usb_permissions(
|
| 382 |
+
uvc_devices: list[dict[str, Any]] | None = None,
|
| 383 |
+
*,
|
| 384 |
+
serial_ports: list[dict[str, Any]] | None = None,
|
| 385 |
+
group_names_override: set[str] | None = None,
|
| 386 |
+
) -> dict[str, Any]:
|
| 387 |
+
"""Checks Linux `video`/`dialout` group membership and device R/W access."""
|
| 388 |
+
if group_names_override is not None:
|
| 389 |
+
group_set = set(group_names_override)
|
| 390 |
+
else:
|
| 391 |
+
group_set = set()
|
| 392 |
+
if grp is not None:
|
| 393 |
+
try:
|
| 394 |
+
gids = set(os.getgroups()) | {os.getegid(), os.getgid()}
|
| 395 |
+
for gid in gids:
|
| 396 |
+
try:
|
| 397 |
+
group_set.add(grp.getgrgid(gid).gr_name)
|
| 398 |
+
except (KeyError, OverflowError):
|
| 399 |
+
# Ignore numeric GIDs without a local /etc/group entry.
|
| 400 |
+
pass
|
| 401 |
+
except OSError:
|
| 402 |
+
# Process group inspection may be restricted in sandboxed envs.
|
| 403 |
+
pass
|
| 404 |
+
|
| 405 |
+
if uvc_devices is None:
|
| 406 |
+
uvc_devices = discover_uvc_devices()
|
| 407 |
+
|
| 408 |
+
v4l2_issues = [
|
| 409 |
+
d
|
| 410 |
+
for d in uvc_devices
|
| 411 |
+
if str(d.get("family", "")).lower() in ("zed", "realsense")
|
| 412 |
+
and d.get("v4l2_rw_ok") is False
|
| 413 |
+
]
|
| 414 |
+
serial_issues = [
|
| 415 |
+
s
|
| 416 |
+
for s in (serial_ports or [])
|
| 417 |
+
if str(s.get("device_role_hint", "")) != "teleop_or_ft232h"
|
| 418 |
+
and s.get("serial_rw_ok") is False
|
| 419 |
+
]
|
| 420 |
+
return {
|
| 421 |
+
"groups": sorted(group_set),
|
| 422 |
+
"in_video_group": "video" in group_set,
|
| 423 |
+
"in_dialout_group": "dialout" in group_set,
|
| 424 |
+
"v4l2_access_issues": v4l2_issues,
|
| 425 |
+
"serial_access_issues": serial_issues,
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def resolve_zed_conf_path(
|
| 430 |
+
serial: str = "",
|
| 431 |
+
explicit_path: str | Path = "",
|
| 432 |
+
search_dirs: Sequence[str | Path] | None = None,
|
| 433 |
+
*,
|
| 434 |
+
env: Mapping[str, str] | None = None,
|
| 435 |
+
) -> Path | None:
|
| 436 |
+
"""Locates factory ZED `SN<serial>.conf` file across standard search paths."""
|
| 437 |
+
if explicit_path:
|
| 438 |
+
p = Path(explicit_path)
|
| 439 |
+
if p.is_file():
|
| 440 |
+
return p
|
| 441 |
+
|
| 442 |
+
env_map = os.environ if env is None else env
|
| 443 |
+
candidate_dirs: list[Path] = [
|
| 444 |
+
Path(part.strip())
|
| 445 |
+
for part in env_map.get("ZED_SETTINGS_DIR", "").split(os.pathsep)
|
| 446 |
+
if part.strip()
|
| 447 |
+
]
|
| 448 |
+
if search_dirs:
|
| 449 |
+
candidate_dirs.extend(
|
| 450 |
+
Path(sdir) for sdir in search_dirs if str(sdir).strip()
|
| 451 |
+
)
|
| 452 |
+
candidate_dirs.extend([
|
| 453 |
+
Path("/usr/local/zed/settings"),
|
| 454 |
+
Path.home() / "zed" / "settings",
|
| 455 |
+
])
|
| 456 |
+
existing_dirs = [d for d in candidate_dirs if d.is_dir()]
|
| 457 |
+
|
| 458 |
+
clean_serial = str(serial).strip()
|
| 459 |
+
if clean_serial:
|
| 460 |
+
target_name = f"sn{clean_serial.lower()}.conf"
|
| 461 |
+
for d in existing_dirs:
|
| 462 |
+
for f in d.iterdir():
|
| 463 |
+
if f.is_file() and f.name.lower() == target_name:
|
| 464 |
+
return f
|
| 465 |
+
return None
|
| 466 |
+
|
| 467 |
+
for d in existing_dirs:
|
| 468 |
+
confs = [
|
| 469 |
+
f
|
| 470 |
+
for f in d.iterdir()
|
| 471 |
+
if f.is_file()
|
| 472 |
+
and f.name.lower().startswith("sn")
|
| 473 |
+
and f.name.lower().endswith(".conf")
|
| 474 |
+
]
|
| 475 |
+
if len(confs) == 1:
|
| 476 |
+
return confs[0]
|
| 477 |
+
return None
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def split_zed_sbs_frame(
|
| 481 |
+
frame: np.ndarray, *, is_bgr: bool = False
|
| 482 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 483 |
+
"""Splits a ZED side-by-side stereo frame into `(left, right)` RGB."""
|
| 484 |
+
arr = np.asarray(frame)
|
| 485 |
+
if arr.ndim != 3 or arr.shape[2] != 3:
|
| 486 |
+
raise ValueError(
|
| 487 |
+
f"Expected 3-channel (H, W, 3) stereo frame, got shape {arr.shape}"
|
| 488 |
+
)
|
| 489 |
+
height, width, _ = arr.shape
|
| 490 |
+
if height <= 0 or width < 2 or (width % 2) != 0:
|
| 491 |
+
raise ValueError(
|
| 492 |
+
"Expected positive even stereo width for side-by-side split, got"
|
| 493 |
+
f" {arr.shape}"
|
| 494 |
+
)
|
| 495 |
+
if arr.dtype != np.uint8:
|
| 496 |
+
arr = np.clip(arr, 0, 255).astype(np.uint8)
|
| 497 |
+
if is_bgr:
|
| 498 |
+
arr = arr[:, :, ::-1]
|
| 499 |
+
mid = width // 2
|
| 500 |
+
return (
|
| 501 |
+
np.ascontiguousarray(arr[:, :mid, :]),
|
| 502 |
+
np.ascontiguousarray(arr[:, mid:, :]),
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def _parse_zed_cam_section(sec: configparser.SectionProxy) -> dict[str, Any]:
|
| 507 |
+
fx = float(sec.get("fx", 0.0))
|
| 508 |
+
fy = float(sec.get("fy", 0.0))
|
| 509 |
+
cx = float(sec.get("cx", 0.0))
|
| 510 |
+
cy = float(sec.get("cy", 0.0))
|
| 511 |
+
k1 = float(sec.get("k1", 0.0))
|
| 512 |
+
k2 = float(sec.get("k2", 0.0))
|
| 513 |
+
p1 = float(sec.get("p1", 0.0))
|
| 514 |
+
p2 = float(sec.get("p2", 0.0))
|
| 515 |
+
k3 = float(sec.get("k3", 0.0))
|
| 516 |
+
return {
|
| 517 |
+
"fx": fx,
|
| 518 |
+
"fy": fy,
|
| 519 |
+
"cx": cx,
|
| 520 |
+
"cy": cy,
|
| 521 |
+
"k1": k1,
|
| 522 |
+
"k2": k2,
|
| 523 |
+
"p1": p1,
|
| 524 |
+
"p2": p2,
|
| 525 |
+
"k3": k3,
|
| 526 |
+
"K": [[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]],
|
| 527 |
+
"dist_coeffs": [k1, k2, p1, p2, k3],
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def parse_zed_conf(
|
| 532 |
+
conf_path: str | Path, resolution: str = "HD720"
|
| 533 |
+
) -> dict[str, Any]:
|
| 534 |
+
"""Parses a Stereolabs ZED factory calibration `.conf` INI file."""
|
| 535 |
+
path = Path(conf_path)
|
| 536 |
+
if not path.is_file():
|
| 537 |
+
raise FileNotFoundError(f"ZED calibration file not found: {path}")
|
| 538 |
+
|
| 539 |
+
res = resolution.strip().upper()
|
| 540 |
+
parser = configparser.ConfigParser(strict=False)
|
| 541 |
+
parser.read(path, encoding="utf-8")
|
| 542 |
+
|
| 543 |
+
left_sec_name = f"LEFT_CAM_{res}"
|
| 544 |
+
right_sec_name = f"RIGHT_CAM_{res}"
|
| 545 |
+
if left_sec_name not in parser or right_sec_name not in parser:
|
| 546 |
+
raise ValueError(
|
| 547 |
+
f"Sections [{left_sec_name}] / [{right_sec_name}] missing in {path} "
|
| 548 |
+
f"(available: {parser.sections()})"
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
stereo_sec = parser["STEREO"] if "STEREO" in parser else {}
|
| 552 |
+
baseline_mm = float(
|
| 553 |
+
stereo_sec.get("baseline", stereo_sec.get("Baseline", 63.0))
|
| 554 |
+
if stereo_sec
|
| 555 |
+
else 63.0
|
| 556 |
+
)
|
| 557 |
+
return {
|
| 558 |
+
"resolution": res,
|
| 559 |
+
"left": _parse_zed_cam_section(parser[left_sec_name]),
|
| 560 |
+
"right": _parse_zed_cam_section(parser[right_sec_name]),
|
| 561 |
+
"stereo": {
|
| 562 |
+
"baseline_mm": baseline_mm,
|
| 563 |
+
"baseline_m": baseline_mm / 1000.0,
|
| 564 |
+
"ty_mm": float(stereo_sec.get("ty", 0.0)) if stereo_sec else 0.0,
|
| 565 |
+
"tz_mm": float(stereo_sec.get("tz", 0.0)) if stereo_sec else 0.0,
|
| 566 |
+
"rx": (
|
| 567 |
+
float(stereo_sec.get(f"rx_{res.lower()}", 0.0))
|
| 568 |
+
if stereo_sec
|
| 569 |
+
else 0.0
|
| 570 |
+
),
|
| 571 |
+
"cv": (
|
| 572 |
+
float(stereo_sec.get(f"cv_{res.lower()}", 0.0))
|
| 573 |
+
if stereo_sec
|
| 574 |
+
else 0.0
|
| 575 |
+
),
|
| 576 |
+
"rz": (
|
| 577 |
+
float(stereo_sec.get(f"rz_{res.lower()}", 0.0))
|
| 578 |
+
if stereo_sec
|
| 579 |
+
else 0.0
|
| 580 |
+
),
|
| 581 |
+
},
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def _is_sbs_stereo_spec(spec: CameraStreamSpec) -> bool:
|
| 586 |
+
"""Returns True when `spec` dimensions encode a side-by-side stereo frame."""
|
| 587 |
+
return spec.height > 0 and (float(spec.width) / float(spec.height)) >= 2.2
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def _zed_res_name_for_size(width: int, height: int) -> str:
|
| 591 |
+
if height >= 1200 or width >= 1920:
|
| 592 |
+
return "HD1080" if height <= 1080 else "HD2K"
|
| 593 |
+
if height >= 720:
|
| 594 |
+
return "HD720"
|
| 595 |
+
return "VGA"
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
class V4L2Camera:
|
| 599 |
+
"""OpenCV V4L2 (`cv2.CAP_V4L2`) capture handle."""
|
| 600 |
+
|
| 601 |
+
def __init__(self, spec: CameraStreamSpec, width: int, height: int) -> None:
|
| 602 |
+
"""Opens a V4L2 video stream matching `spec` at `(width, height)`."""
|
| 603 |
+
cv2_mod = require_cv2()
|
| 604 |
+
candidates: list[str] = []
|
| 605 |
+
if spec.device_path and os.path.exists(spec.device_path):
|
| 606 |
+
candidates.append(spec.device_path)
|
| 607 |
+
|
| 608 |
+
if not candidates:
|
| 609 |
+
is_zed_role = spec.role == "head_stereo"
|
| 610 |
+
matching = [
|
| 611 |
+
d
|
| 612 |
+
for d in discover_uvc_devices()
|
| 613 |
+
if d.get("device_path")
|
| 614 |
+
and (
|
| 615 |
+
(spec.serial and d.get("serial") == spec.serial)
|
| 616 |
+
or (is_zed_role and d.get("family") == "zed")
|
| 617 |
+
)
|
| 618 |
+
]
|
| 619 |
+
matching.sort(key=lambda d: str(d.get("video_node", "")))
|
| 620 |
+
for d in matching:
|
| 621 |
+
cand = str(d["device_path"])
|
| 622 |
+
if cand not in candidates:
|
| 623 |
+
candidates.append(cand)
|
| 624 |
+
|
| 625 |
+
if not candidates:
|
| 626 |
+
raise RuntimeError(
|
| 627 |
+
f"No V4L2 device_path resolved for camera role={spec.role!r} "
|
| 628 |
+
f"(serial={spec.serial!r})"
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
self._cv2 = cv2_mod
|
| 632 |
+
self._cap = None
|
| 633 |
+
for cand_path in candidates:
|
| 634 |
+
real_dev = os.path.realpath(cand_path)
|
| 635 |
+
cap = cv2_mod.VideoCapture(real_dev, cv2_mod.CAP_V4L2)
|
| 636 |
+
if cap.isOpened():
|
| 637 |
+
self._cap = cap
|
| 638 |
+
break
|
| 639 |
+
cap.release()
|
| 640 |
+
|
| 641 |
+
if self._cap is None or not self._cap.isOpened():
|
| 642 |
+
raise RuntimeError(
|
| 643 |
+
f"Failed to open V4L2 camera at {candidates!r} "
|
| 644 |
+
f"for role={spec.role!r}"
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
self._cap.set(cv2_mod.CAP_PROP_BUFFERSIZE, 1)
|
| 648 |
+
self._cap.set(cv2_mod.CAP_PROP_FRAME_WIDTH, int(width))
|
| 649 |
+
self._cap.set(cv2_mod.CAP_PROP_FRAME_HEIGHT, int(height))
|
| 650 |
+
self._cap.set(cv2_mod.CAP_PROP_FPS, int(spec.fps))
|
| 651 |
+
|
| 652 |
+
def capture_rgb(self) -> tuple[np.ndarray, float]:
|
| 653 |
+
"""Reads one frame from V4L2 and returns `(rgb_uint8, monotonic_ts)`."""
|
| 654 |
+
ok, bgr = self._cap.read()
|
| 655 |
+
ts = time.monotonic()
|
| 656 |
+
if not ok or bgr is None:
|
| 657 |
+
raise RuntimeError("V4L2 frame read failed")
|
| 658 |
+
rgb = self._cv2.cvtColor(
|
| 659 |
+
np.asarray(bgr, dtype=np.uint8), self._cv2.COLOR_BGR2RGB
|
| 660 |
+
)
|
| 661 |
+
return np.ascontiguousarray(rgb, dtype=np.uint8), ts
|
| 662 |
+
|
| 663 |
+
def close(self) -> None:
|
| 664 |
+
"""Releases the underlying OpenCV `VideoCapture` handle."""
|
| 665 |
+
if self._cap is not None:
|
| 666 |
+
self._cap.release()
|
| 667 |
+
self._cap = None
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def _read_override_frame(source: Any) -> tuple[np.ndarray, float, str]:
|
| 671 |
+
"""Reads `(rgb, timestamp_s, backend)` from a test override handle."""
|
| 672 |
+
raw = (
|
| 673 |
+
source.capture()
|
| 674 |
+
if hasattr(source, "capture")
|
| 675 |
+
else (source.read() if hasattr(source, "read") else source())
|
| 676 |
+
)
|
| 677 |
+
if isinstance(raw, CameraFrame):
|
| 678 |
+
return (
|
| 679 |
+
np.ascontiguousarray(raw.rgb, dtype=np.uint8),
|
| 680 |
+
float(raw.timestamp_s),
|
| 681 |
+
str(raw.backend or "override"),
|
| 682 |
+
)
|
| 683 |
+
if (
|
| 684 |
+
isinstance(raw, tuple)
|
| 685 |
+
and len(raw) == 2
|
| 686 |
+
and isinstance(raw[0], (bool, np.bool_))
|
| 687 |
+
):
|
| 688 |
+
if not raw[0] or raw[1] is None:
|
| 689 |
+
raise RuntimeError("Camera override returned failed read")
|
| 690 |
+
return (
|
| 691 |
+
np.ascontiguousarray(np.asarray(raw[1], dtype=np.uint8)[:, :, ::-1]),
|
| 692 |
+
time.monotonic(),
|
| 693 |
+
"override",
|
| 694 |
+
)
|
| 695 |
+
if (
|
| 696 |
+
isinstance(raw, tuple)
|
| 697 |
+
and len(raw) >= 2
|
| 698 |
+
and isinstance(raw[0], np.ndarray)
|
| 699 |
+
):
|
| 700 |
+
return (
|
| 701 |
+
np.ascontiguousarray(raw[0], dtype=np.uint8),
|
| 702 |
+
float(raw[1]),
|
| 703 |
+
str(raw[2]) if len(raw) >= 3 else "override",
|
| 704 |
+
)
|
| 705 |
+
raise TypeError(f"Unsupported camera override payload: {type(raw)!r}")
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
class Fr3DuoCameraController:
|
| 709 |
+
"""Unified 4-camera capture controller for Franka Research 3 Duo."""
|
| 710 |
+
|
| 711 |
+
def __init__(
|
| 712 |
+
self,
|
| 713 |
+
specs: Any = None,
|
| 714 |
+
*,
|
| 715 |
+
sim_robot: Any = None,
|
| 716 |
+
backend_overrides: dict[str, Any] | None = None,
|
| 717 |
+
dry_run: bool = False,
|
| 718 |
+
) -> None:
|
| 719 |
+
"""Initializes stream specs and optional sim, override, or dry-run mode."""
|
| 720 |
+
self.specs: dict[str, CameraStreamSpec] = {}
|
| 721 |
+
if specs is None:
|
| 722 |
+
self.specs["head_stereo"] = CameraStreamSpec(
|
| 723 |
+
role="head_stereo", width=2560, height=720
|
| 724 |
+
)
|
| 725 |
+
for cam_name in ("wrist_camera_left", "wrist_camera_right"):
|
| 726 |
+
self.specs[cam_name] = CameraStreamSpec(role=cam_name)
|
| 727 |
+
else:
|
| 728 |
+
spec_map = specs.as_spec_map() if hasattr(specs, "as_spec_map") else specs
|
| 729 |
+
for key, val in spec_map.items():
|
| 730 |
+
self.specs[key] = CameraStreamSpec.from_mapping(key, val)
|
| 731 |
+
|
| 732 |
+
self.sim_robot = sim_robot
|
| 733 |
+
self.backend_overrides = (
|
| 734 |
+
dict(backend_overrides) if backend_overrides else {}
|
| 735 |
+
)
|
| 736 |
+
self.dry_run = bool(dry_run)
|
| 737 |
+
self._opened = False
|
| 738 |
+
self._handles: dict[str, tuple[Any, str, tuple[str, ...]]] = {}
|
| 739 |
+
self._zed_rectify_cache: dict[
|
| 740 |
+
tuple[str, int, int], tuple[Any, Any, Any, Any]
|
| 741 |
+
] = {}
|
| 742 |
+
self._frame_seq = 0
|
| 743 |
+
|
| 744 |
+
def _resolve_zed_conf_for_pair(self) -> str:
|
| 745 |
+
sp = self.specs.get("head_stereo")
|
| 746 |
+
return sp.zed_conf_path if (sp is not None and sp.zed_conf_path) else ""
|
| 747 |
+
|
| 748 |
+
def _maybe_rectify_zed_pair(
|
| 749 |
+
self, left_rgb: np.ndarray, right_rgb: np.ndarray
|
| 750 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 751 |
+
conf_path = self._resolve_zed_conf_for_pair()
|
| 752 |
+
if not conf_path or not Path(conf_path).is_file():
|
| 753 |
+
return left_rgb, right_rgb
|
| 754 |
+
cv2_mod = require_cv2()
|
| 755 |
+
h, w = int(left_rgb.shape[0]), int(left_rgb.shape[1])
|
| 756 |
+
cache_key = (conf_path, w, h)
|
| 757 |
+
if cache_key not in self._zed_rectify_cache:
|
| 758 |
+
parsed = parse_zed_conf(conf_path, _zed_res_name_for_size(w, h))
|
| 759 |
+
k_l = np.asarray(parsed["left"]["K"], dtype=np.float64)
|
| 760 |
+
d_l = np.asarray(parsed["left"]["dist_coeffs"], dtype=np.float64)
|
| 761 |
+
k_r = np.asarray(parsed["right"]["K"], dtype=np.float64)
|
| 762 |
+
d_r = np.asarray(parsed["right"]["dist_coeffs"], dtype=np.float64)
|
| 763 |
+
st = parsed["stereo"]
|
| 764 |
+
r_mat, _ = cv2_mod.Rodrigues(
|
| 765 |
+
np.array([st["rx"], st["cv"], st["rz"]], dtype=np.float64)
|
| 766 |
+
)
|
| 767 |
+
t_vec = np.array(
|
| 768 |
+
[-st["baseline_m"], st["ty_mm"] / 1000.0, st["tz_mm"] / 1000.0],
|
| 769 |
+
dtype=np.float64,
|
| 770 |
+
)
|
| 771 |
+
r1, r2, p1, p2, _, _, _ = cv2_mod.stereoRectify(
|
| 772 |
+
k_l, d_l, k_r, d_r, (w, h), r_mat, t_vec, alpha=0
|
| 773 |
+
)
|
| 774 |
+
self._zed_rectify_cache[cache_key] = (
|
| 775 |
+
*cv2_mod.initUndistortRectifyMap(
|
| 776 |
+
k_l, d_l, r1, p1, (w, h), cv2_mod.CV_16SC2
|
| 777 |
+
),
|
| 778 |
+
*cv2_mod.initUndistortRectifyMap(
|
| 779 |
+
k_r, d_r, r2, p2, (w, h), cv2_mod.CV_16SC2
|
| 780 |
+
),
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
m1_l, m2_l, m1_r, m2_r = self._zed_rectify_cache[cache_key]
|
| 784 |
+
return (
|
| 785 |
+
np.ascontiguousarray(
|
| 786 |
+
cv2_mod.remap(left_rgb, m1_l, m2_l, cv2_mod.INTER_LINEAR)
|
| 787 |
+
),
|
| 788 |
+
np.ascontiguousarray(
|
| 789 |
+
cv2_mod.remap(right_rgb, m1_r, m2_r, cv2_mod.INTER_LINEAR)
|
| 790 |
+
),
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
def open(self) -> None:
|
| 794 |
+
"""Opens configured camera streams."""
|
| 795 |
+
if self._opened:
|
| 796 |
+
return
|
| 797 |
+
self._handles.clear()
|
| 798 |
+
|
| 799 |
+
if self.sim_robot is not None or (
|
| 800 |
+
self.dry_run and not self.backend_overrides
|
| 801 |
+
):
|
| 802 |
+
self._opened = True
|
| 803 |
+
return
|
| 804 |
+
|
| 805 |
+
if self.backend_overrides:
|
| 806 |
+
for key, source in self.backend_overrides.items():
|
| 807 |
+
targets = (
|
| 808 |
+
("head_camera_left", "head_camera_right")
|
| 809 |
+
if key == "head_stereo"
|
| 810 |
+
else (key,)
|
| 811 |
+
)
|
| 812 |
+
self._handles[key] = (source, "override", targets)
|
| 813 |
+
self._opened = True
|
| 814 |
+
return
|
| 815 |
+
|
| 816 |
+
for role, sp in self.specs.items():
|
| 817 |
+
if role == "head_stereo":
|
| 818 |
+
cap_w = sp.width if _is_sbs_stereo_spec(sp) else sp.width * 2
|
| 819 |
+
self._handles[role] = (
|
| 820 |
+
V4L2Camera(sp, cap_w, sp.height),
|
| 821 |
+
"v4l2",
|
| 822 |
+
("head_camera_left", "head_camera_right"),
|
| 823 |
+
)
|
| 824 |
+
else:
|
| 825 |
+
self._handles[role] = (
|
| 826 |
+
V4L2Camera(sp, sp.width, sp.height),
|
| 827 |
+
"v4l2",
|
| 828 |
+
(role,),
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
self._opened = True
|
| 832 |
+
|
| 833 |
+
def close(self) -> None:
|
| 834 |
+
"""Releases any opened physical or mock capture handles."""
|
| 835 |
+
for handle, _, _ in self._handles.values():
|
| 836 |
+
close_fn = getattr(handle, "close", None) or getattr(
|
| 837 |
+
handle, "release", None
|
| 838 |
+
)
|
| 839 |
+
if callable(close_fn):
|
| 840 |
+
close_fn()
|
| 841 |
+
self._handles.clear()
|
| 842 |
+
self._opened = False
|
| 843 |
+
|
| 844 |
+
def __enter__(self) -> Fr3DuoCameraController:
|
| 845 |
+
"""Opens camera streams when entering a context manager."""
|
| 846 |
+
self.open()
|
| 847 |
+
return self
|
| 848 |
+
|
| 849 |
+
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
| 850 |
+
"""Closes camera streams when exiting a context manager."""
|
| 851 |
+
self.close()
|
| 852 |
+
|
| 853 |
+
def _synthesize_dry_run_frame(
|
| 854 |
+
self, cam_idx: int, role: str, ts: float
|
| 855 |
+
) -> CameraFrame:
|
| 856 |
+
spec = self.specs.get(role, CameraStreamSpec(role=role))
|
| 857 |
+
w, h = int(spec.width), int(spec.height)
|
| 858 |
+
xs = np.linspace(24, 220, w, dtype=np.uint8)
|
| 859 |
+
ys = np.linspace(32, 210, h, dtype=np.uint8)
|
| 860 |
+
shift = (self._frame_seq * 7 + cam_idx * 37) % 64
|
| 861 |
+
r = np.broadcast_to(
|
| 862 |
+
((ys[:, None].astype(np.uint16) + shift) % 256).astype(np.uint8),
|
| 863 |
+
(h, w),
|
| 864 |
+
)
|
| 865 |
+
g = np.broadcast_to(xs[None, :], (h, w))
|
| 866 |
+
b = np.full((h, w), 60 + cam_idx * 40, dtype=np.uint8)
|
| 867 |
+
rgb = np.ascontiguousarray(np.stack([r, g, b], axis=-1), dtype=np.uint8)
|
| 868 |
+
return CameraFrame(
|
| 869 |
+
name=role,
|
| 870 |
+
rgb=rgb,
|
| 871 |
+
timestamp_s=ts,
|
| 872 |
+
width=w,
|
| 873 |
+
height=h,
|
| 874 |
+
backend="dry_run",
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
def capture_all(self) -> dict[str, CameraFrame]:
|
| 878 |
+
"""Captures RGB frames across all configured cameras."""
|
| 879 |
+
if not self._opened:
|
| 880 |
+
self.open()
|
| 881 |
+
self._frame_seq += 1
|
| 882 |
+
|
| 883 |
+
if self.sim_robot is not None:
|
| 884 |
+
ref_spec = (
|
| 885 |
+
self.specs.get("wrist_camera_left")
|
| 886 |
+
or self.specs.get("wrist_camera_right")
|
| 887 |
+
or next(iter(self.specs.values()), CameraStreamSpec(role="sim"))
|
| 888 |
+
)
|
| 889 |
+
sim_w = (
|
| 890 |
+
int(ref_spec.width) // 2
|
| 891 |
+
if ref_spec.role == "head_stereo" and _is_sbs_stereo_spec(ref_spec)
|
| 892 |
+
else int(ref_spec.width)
|
| 893 |
+
)
|
| 894 |
+
rendered = self.sim_robot.render_sim_cameras(
|
| 895 |
+
width=sim_w, height=int(ref_spec.height)
|
| 896 |
+
)
|
| 897 |
+
ts = time.monotonic()
|
| 898 |
+
return {
|
| 899 |
+
cam_name: CameraFrame(
|
| 900 |
+
name=cam_name,
|
| 901 |
+
rgb=np.ascontiguousarray(rendered[cam_name], dtype=np.uint8),
|
| 902 |
+
timestamp_s=ts,
|
| 903 |
+
width=int(rendered[cam_name].shape[1]),
|
| 904 |
+
height=int(rendered[cam_name].shape[0]),
|
| 905 |
+
backend="mujoco_sim",
|
| 906 |
+
)
|
| 907 |
+
for cam_name in CANONICAL_CAMERAS
|
| 908 |
+
}
|
| 909 |
+
|
| 910 |
+
if self.dry_run and not self._handles:
|
| 911 |
+
ts = time.monotonic()
|
| 912 |
+
return {
|
| 913 |
+
cam_name: self._synthesize_dry_run_frame(idx, cam_name, ts)
|
| 914 |
+
for idx, cam_name in enumerate(CANONICAL_CAMERAS)
|
| 915 |
+
}
|
| 916 |
+
|
| 917 |
+
frames: dict[str, CameraFrame] = {}
|
| 918 |
+
for handle, default_backend, targets in self._handles.values():
|
| 919 |
+
if hasattr(handle, "capture_rgb"):
|
| 920 |
+
rgb_raw, ts = handle.capture_rgb()
|
| 921 |
+
backend = default_backend
|
| 922 |
+
else:
|
| 923 |
+
rgb_raw, ts, backend = _read_override_frame(handle)
|
| 924 |
+
|
| 925 |
+
if len(targets) == 2:
|
| 926 |
+
t_left, t_right = targets
|
| 927 |
+
stereo_spec = self.specs.get("head_stereo")
|
| 928 |
+
raw_h, raw_w = int(rgb_raw.shape[0]), int(rgb_raw.shape[1])
|
| 929 |
+
expected_sbs_w: int | None = None
|
| 930 |
+
if stereo_spec is not None:
|
| 931 |
+
expected_sbs_w = (
|
| 932 |
+
int(stereo_spec.width)
|
| 933 |
+
if _is_sbs_stereo_spec(stereo_spec)
|
| 934 |
+
else int(stereo_spec.width) * 2
|
| 935 |
+
)
|
| 936 |
+
is_sbs_frame = (
|
| 937 |
+
raw_w >= 2
|
| 938 |
+
and (raw_w % 2) == 0
|
| 939 |
+
and (
|
| 940 |
+
(expected_sbs_w is not None and raw_w == expected_sbs_w)
|
| 941 |
+
or (raw_h > 0 and (float(raw_w) / float(raw_h)) >= 2.2)
|
| 942 |
+
)
|
| 943 |
+
)
|
| 944 |
+
if is_sbs_frame:
|
| 945 |
+
left_rgb, right_rgb = self._maybe_rectify_zed_pair(
|
| 946 |
+
*split_zed_sbs_frame(rgb_raw, is_bgr=False)
|
| 947 |
+
)
|
| 948 |
+
else:
|
| 949 |
+
left_rgb, right_rgb = rgb_raw, rgb_raw.copy()
|
| 950 |
+
for t_name, view_rgb in ((t_left, left_rgb), (t_right, right_rgb)):
|
| 951 |
+
oriented = np.ascontiguousarray(view_rgb, dtype=np.uint8)
|
| 952 |
+
frames[t_name] = CameraFrame(
|
| 953 |
+
name=t_name,
|
| 954 |
+
rgb=oriented,
|
| 955 |
+
timestamp_s=ts,
|
| 956 |
+
width=int(oriented.shape[1]),
|
| 957 |
+
height=int(oriented.shape[0]),
|
| 958 |
+
backend=backend,
|
| 959 |
+
)
|
| 960 |
+
else:
|
| 961 |
+
role = targets[0]
|
| 962 |
+
oriented = np.ascontiguousarray(rgb_raw, dtype=np.uint8)
|
| 963 |
+
frames[role] = CameraFrame(
|
| 964 |
+
name=role,
|
| 965 |
+
rgb=oriented,
|
| 966 |
+
timestamp_s=ts,
|
| 967 |
+
width=int(oriented.shape[1]),
|
| 968 |
+
height=int(oriented.shape[0]),
|
| 969 |
+
backend=backend,
|
| 970 |
+
)
|
| 971 |
+
return frames
|
| 972 |
+
|
| 973 |
+
def check_freshness(
|
| 974 |
+
self,
|
| 975 |
+
*,
|
| 976 |
+
max_age_s: float = 0.30,
|
| 977 |
+
num_reads: int = 3,
|
| 978 |
+
interval_s: float = 0.05,
|
| 979 |
+
) -> dict[str, Any]:
|
| 980 |
+
"""Verifies frame age (`<= max_age_s`), timestamps, and pixel variance."""
|
| 981 |
+
rounds = max(1, int(num_reads))
|
| 982 |
+
history: dict[str, list[tuple[CameraFrame, float]]] = {}
|
| 983 |
+
|
| 984 |
+
if (
|
| 985 |
+
not self.dry_run
|
| 986 |
+
and self.sim_robot is None
|
| 987 |
+
and not self.backend_overrides
|
| 988 |
+
):
|
| 989 |
+
self.capture_all()
|
| 990 |
+
if interval_s > 0.0:
|
| 991 |
+
time.sleep(float(interval_s))
|
| 992 |
+
|
| 993 |
+
for idx in range(rounds):
|
| 994 |
+
if idx > 0 and interval_s > 0.0:
|
| 995 |
+
time.sleep(float(interval_s))
|
| 996 |
+
batch = self.capture_all()
|
| 997 |
+
now_s = time.monotonic()
|
| 998 |
+
for name, frame in batch.items():
|
| 999 |
+
history.setdefault(name, []).append((frame, frame.age_s(now_s)))
|
| 1000 |
+
|
| 1001 |
+
errors: list[str] = []
|
| 1002 |
+
cam_reports: dict[str, Any] = {}
|
| 1003 |
+
if not history:
|
| 1004 |
+
return {
|
| 1005 |
+
"ok": False,
|
| 1006 |
+
"cameras": {},
|
| 1007 |
+
"errors": ["No camera frames captured."],
|
| 1008 |
+
}
|
| 1009 |
+
|
| 1010 |
+
has_full_physical_rig = {
|
| 1011 |
+
"head_stereo",
|
| 1012 |
+
"wrist_camera_left",
|
| 1013 |
+
"wrist_camera_right",
|
| 1014 |
+
}.issubset(set(self.specs.keys()))
|
| 1015 |
+
if has_full_physical_rig:
|
| 1016 |
+
for req_cam in CANONICAL_CAMERAS:
|
| 1017 |
+
if req_cam not in history:
|
| 1018 |
+
errors.append(f"Missing canonical camera stream: {req_cam}")
|
| 1019 |
+
|
| 1020 |
+
for name, samples in history.items():
|
| 1021 |
+
ages = [age for _f, age in samples]
|
| 1022 |
+
timestamps = [f.timestamp_s for f, _age in samples]
|
| 1023 |
+
last_frame = samples[-1][0]
|
| 1024 |
+
max_observed_age = max(ages)
|
| 1025 |
+
ts_advancing = len(timestamps) < 2 or timestamps[-1] > timestamps[0]
|
| 1026 |
+
pixels_changing = True
|
| 1027 |
+
if len(samples) >= 2 and last_frame.backend not in (
|
| 1028 |
+
"mujoco_sim",
|
| 1029 |
+
"dry_run",
|
| 1030 |
+
):
|
| 1031 |
+
first_rgb = samples[0][0].rgb
|
| 1032 |
+
pixels_changing = any(
|
| 1033 |
+
not np.array_equal(first_rgb, frm.rgb) for frm, _ in samples[1:]
|
| 1034 |
+
)
|
| 1035 |
+
mean_val = last_frame.brightness_mean
|
| 1036 |
+
std_val = last_frame.pixel_std
|
| 1037 |
+
|
| 1038 |
+
cam_ok = True
|
| 1039 |
+
if max_observed_age > float(max_age_s):
|
| 1040 |
+
cam_ok = False
|
| 1041 |
+
errors.append(
|
| 1042 |
+
f"{name}: stale frame age {max_observed_age:.3f}s >"
|
| 1043 |
+
f" {max_age_s:.3f}s"
|
| 1044 |
+
)
|
| 1045 |
+
if not ts_advancing:
|
| 1046 |
+
cam_ok = False
|
| 1047 |
+
errors.append(f"{name}: frozen timestamp ({timestamps[-1]:.6f})")
|
| 1048 |
+
if not pixels_changing:
|
| 1049 |
+
cam_ok = False
|
| 1050 |
+
errors.append(
|
| 1051 |
+
f"{name}: frozen pixel buffer across {len(samples)} reads"
|
| 1052 |
+
)
|
| 1053 |
+
if std_val <= 0.5 or mean_val <= 1.0 or mean_val >= 254.5:
|
| 1054 |
+
cam_ok = False
|
| 1055 |
+
errors.append(
|
| 1056 |
+
f"{name}: degenerate image statistics "
|
| 1057 |
+
f"(mean={mean_val:.2f}, std={std_val:.2f})"
|
| 1058 |
+
)
|
| 1059 |
+
|
| 1060 |
+
cam_reports[name] = {
|
| 1061 |
+
"ok": cam_ok,
|
| 1062 |
+
"max_age_s": float(max_observed_age),
|
| 1063 |
+
"timestamps_advancing": ts_advancing,
|
| 1064 |
+
"pixels_changing": pixels_changing,
|
| 1065 |
+
"brightness_mean": mean_val,
|
| 1066 |
+
"pixel_std": std_val,
|
| 1067 |
+
"width": last_frame.width,
|
| 1068 |
+
"height": last_frame.height,
|
| 1069 |
+
"backend": last_frame.backend,
|
| 1070 |
+
}
|
| 1071 |
+
|
| 1072 |
+
return {"ok": len(errors) == 0, "cameras": cam_reports, "errors": errors}
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
def render_contact_sheet(
|
| 1076 |
+
frames: Mapping[str, CameraFrame | np.ndarray],
|
| 1077 |
+
) -> np.ndarray:
|
| 1078 |
+
"""Renders a labeled 2x2 RGB mosaic of the 4 canonical Duo cameras."""
|
| 1079 |
+
cv2_mod = require_cv2()
|
| 1080 |
+
tile_w, tile_h = 640, 360
|
| 1081 |
+
|
| 1082 |
+
def _unpack(
|
| 1083 |
+
item: CameraFrame | np.ndarray | None,
|
| 1084 |
+
) -> tuple[np.ndarray | None, int, int, str]:
|
| 1085 |
+
if item is None:
|
| 1086 |
+
return None, 0, 0, ""
|
| 1087 |
+
if isinstance(item, np.ndarray):
|
| 1088 |
+
h = int(item.shape[0]) if item.ndim >= 2 else 0
|
| 1089 |
+
w = int(item.shape[1]) if item.ndim >= 2 else 0
|
| 1090 |
+
return item, w, h, "rgb"
|
| 1091 |
+
return item.rgb, int(item.width), int(item.height), str(item.backend)
|
| 1092 |
+
|
| 1093 |
+
for candidate in frames.values():
|
| 1094 |
+
_, w0, h0, _ = _unpack(candidate)
|
| 1095 |
+
if w0 > 0 and h0 > 0:
|
| 1096 |
+
tile_w = min(640, w0)
|
| 1097 |
+
tile_h = max(120, int(round(tile_w * h0 / w0)))
|
| 1098 |
+
break
|
| 1099 |
+
|
| 1100 |
+
tiles: list[np.ndarray] = []
|
| 1101 |
+
for cam_name in CANONICAL_CAMERAS:
|
| 1102 |
+
rgb_arr, width, height, backend = _unpack(frames.get(cam_name))
|
| 1103 |
+
if rgb_arr is None or rgb_arr.size == 0:
|
| 1104 |
+
tile = np.full((tile_h, tile_w, 3), 28, dtype=np.uint8)
|
| 1105 |
+
label = f"{cam_name}: MISSING"
|
| 1106 |
+
else:
|
| 1107 |
+
if rgb_arr.shape[0] != tile_h or rgb_arr.shape[1] != tile_w:
|
| 1108 |
+
tile = cv2_mod.resize(
|
| 1109 |
+
rgb_arr, (tile_w, tile_h), interpolation=cv2_mod.INTER_AREA
|
| 1110 |
+
)
|
| 1111 |
+
else:
|
| 1112 |
+
tile = rgb_arr.copy()
|
| 1113 |
+
label = f"{cam_name} {width}x{height} {backend}".strip()
|
| 1114 |
+
|
| 1115 |
+
banner_h = min(tile_h, 26)
|
| 1116 |
+
tile[:banner_h] = (tile[:banner_h].astype(np.uint16) // 4).astype(np.uint8)
|
| 1117 |
+
cv2_mod.putText(
|
| 1118 |
+
tile,
|
| 1119 |
+
label,
|
| 1120 |
+
(10, banner_h - 6),
|
| 1121 |
+
cv2_mod.FONT_HERSHEY_SIMPLEX,
|
| 1122 |
+
0.55,
|
| 1123 |
+
(245, 248, 255),
|
| 1124 |
+
1,
|
| 1125 |
+
cv2_mod.LINE_AA,
|
| 1126 |
+
)
|
| 1127 |
+
tiles.append(tile)
|
| 1128 |
+
|
| 1129 |
+
top_row = np.concatenate([tiles[0], tiles[1]], axis=1)
|
| 1130 |
+
bottom_row = np.concatenate([tiles[2], tiles[3]], axis=1)
|
| 1131 |
+
return np.ascontiguousarray(np.concatenate([top_row, bottom_row], axis=0))
|
tasks/belt-pick/environment/world/skills/fr3-duo-control/scripts/fr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|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Configuration schema, PREEMPT_RT detection, and output helpers for FR3 Duo.
|
| 16 |
+
|
| 17 |
+
Provides:
|
| 18 |
+
- Config dataclasses (`ArmConfig`, `ArmsConfig`, `CamerasConfig`, `RobotConfig`)
|
| 19 |
+
- Geometry constants & helpers (`BASE_WORLD_Z_M`, `BRACKET_UNDERSIDE_FRONT_X_M`,
|
| 20 |
+
`table_box_bounds`, `validate_robot_config_complete`)
|
| 21 |
+
- Config helpers (`DEFAULT_CONFIG_PATH`, `default_robot_config`,
|
| 22 |
+
`normalize_robot_config`, `load_robot_config`, `save_robot_config`)
|
| 23 |
+
- PREEMPT_RT auto-detection and `pylibfranka` `RealtimeConfig` resolution
|
| 24 |
+
- Stage output path resolution and RGB PNG / MP4 writer utilities
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
from collections.abc import Mapping, Sequence
|
| 30 |
+
import copy
|
| 31 |
+
from dataclasses import asdict, dataclass, field
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
import tempfile
|
| 37 |
+
from typing import Any
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
import fr3_camera_controller
|
| 42 |
+
import fr3_mjcf
|
| 43 |
+
import robotiq_gripper_controller
|
| 44 |
+
|
| 45 |
+
DEFAULT_CONFIG_PATH = "config/robot_config.json"
|
| 46 |
+
MIN_INTER_ARM_CLEARANCE_M = 0.030
|
| 47 |
+
BASE_WORLD_Z_M = 0.163887
|
| 48 |
+
BRACKET_UNDERSIDE_FRONT_X_M = 0.08437
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclass
|
| 52 |
+
class ArmConfig:
|
| 53 |
+
"""Configuration for one 7-DOF FR3 arm and its Robotiq RS-485 gripper."""
|
| 54 |
+
|
| 55 |
+
ip: str = "172.16.0.2"
|
| 56 |
+
enabled: bool = True
|
| 57 |
+
rest_pose_rad: list[float] = field(
|
| 58 |
+
default_factory=lambda: list(fr3_mjcf.DEFAULT_REST_POSE_RAD["left"])
|
| 59 |
+
)
|
| 60 |
+
gripper_port: str = ""
|
| 61 |
+
gripper_slave_id: int = robotiq_gripper_controller.DEFAULT_SLAVE_ID
|
| 62 |
+
gripper_baudrate: int = robotiq_gripper_controller.DEFAULT_BAUDRATE
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclass
|
| 66 |
+
class ArmsConfig:
|
| 67 |
+
"""Pair of left and right arm configurations."""
|
| 68 |
+
|
| 69 |
+
left: ArmConfig = field(
|
| 70 |
+
default_factory=lambda: ArmConfig(
|
| 71 |
+
ip="172.16.0.2",
|
| 72 |
+
rest_pose_rad=list(fr3_mjcf.DEFAULT_REST_POSE_RAD["left"]),
|
| 73 |
+
)
|
| 74 |
+
)
|
| 75 |
+
right: ArmConfig = field(
|
| 76 |
+
default_factory=lambda: ArmConfig(
|
| 77 |
+
ip="172.16.1.2",
|
| 78 |
+
rest_pose_rad=list(fr3_mjcf.DEFAULT_REST_POSE_RAD["right"]),
|
| 79 |
+
)
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
def __getitem__(self, side: str) -> ArmConfig:
|
| 83 |
+
"""Returns the `ArmConfig` for `'left'` or `'right'`."""
|
| 84 |
+
if side == "left":
|
| 85 |
+
return self.left
|
| 86 |
+
if side == "right":
|
| 87 |
+
return self.right
|
| 88 |
+
raise KeyError(side)
|
| 89 |
+
|
| 90 |
+
def items(self) -> tuple[tuple[str, ArmConfig], ...]:
|
| 91 |
+
"""Returns `((side, ArmConfig), ...)` for both arms."""
|
| 92 |
+
return (("left", self.left), ("right", self.right))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@dataclass
|
| 96 |
+
class CamerasConfig:
|
| 97 |
+
"""Physical camera configurations (1 stereo head ZED + 2 wrist RealSense)."""
|
| 98 |
+
|
| 99 |
+
head_stereo: fr3_camera_controller.CameraStreamSpec = field(
|
| 100 |
+
default_factory=lambda: fr3_camera_controller.CameraStreamSpec(
|
| 101 |
+
role="head_stereo", width=2560, height=720
|
| 102 |
+
)
|
| 103 |
+
)
|
| 104 |
+
wrist_camera_left: fr3_camera_controller.CameraStreamSpec = field(
|
| 105 |
+
default_factory=lambda: fr3_camera_controller.CameraStreamSpec(
|
| 106 |
+
role="wrist_camera_left"
|
| 107 |
+
)
|
| 108 |
+
)
|
| 109 |
+
wrist_camera_right: fr3_camera_controller.CameraStreamSpec = field(
|
| 110 |
+
default_factory=lambda: fr3_camera_controller.CameraStreamSpec(
|
| 111 |
+
role="wrist_camera_right"
|
| 112 |
+
)
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def as_spec_map(self) -> dict[str, fr3_camera_controller.CameraStreamSpec]:
|
| 116 |
+
"""Returns a role-keyed dictionary of camera stream specifications."""
|
| 117 |
+
return {
|
| 118 |
+
"head_stereo": self.head_stereo,
|
| 119 |
+
"wrist_camera_left": self.wrist_camera_left,
|
| 120 |
+
"wrist_camera_right": self.wrist_camera_right,
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
def __getitem__(self, role: str) -> fr3_camera_controller.CameraStreamSpec:
|
| 124 |
+
"""Returns the `CameraStreamSpec` for a canonical camera role."""
|
| 125 |
+
if role in ("head_stereo", "wrist_camera_left", "wrist_camera_right"):
|
| 126 |
+
return getattr(self, role)
|
| 127 |
+
raise KeyError(role)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@dataclass
|
| 131 |
+
class RobotConfig:
|
| 132 |
+
"""Canonical configuration schema for a Franka Research 3 Duo cell."""
|
| 133 |
+
|
| 134 |
+
platform: str = "franka_research_3_duo"
|
| 135 |
+
base_height_m: float = 0.913887
|
| 136 |
+
table_height_m: float = 0.75
|
| 137 |
+
table_front_offset_m: float = 0.25
|
| 138 |
+
table_width_m: float = 1.22
|
| 139 |
+
table_depth_m: float = 0.74
|
| 140 |
+
geometry_confirmed: bool = False
|
| 141 |
+
min_inter_arm_clearance_m: float = MIN_INTER_ARM_CLEARANCE_M
|
| 142 |
+
tcp_offset_z_m: float = 0.145
|
| 143 |
+
realtime_mode: str = "auto"
|
| 144 |
+
zed_settings_dir: str = ""
|
| 145 |
+
max_joint_speed_deg_s: float | None = None
|
| 146 |
+
arms: ArmsConfig = field(default_factory=ArmsConfig)
|
| 147 |
+
cameras: CamerasConfig = field(default_factory=CamerasConfig)
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def z_table_m(self) -> float:
|
| 151 |
+
"""Derived tabletop Z in Duo `base` frame from floor heights."""
|
| 152 |
+
delta_h = float(self.base_height_m) - float(self.table_height_m)
|
| 153 |
+
return round(BASE_WORLD_Z_M - delta_h, 6)
|
| 154 |
+
|
| 155 |
+
def table_box_bounds(self) -> tuple[list[float], list[float]]:
|
| 156 |
+
"""Returns `(center, half_extents)` for the configured tabletop box."""
|
| 157 |
+
table_thickness = 0.04
|
| 158 |
+
x_front = BRACKET_UNDERSIDE_FRONT_X_M + float(self.table_front_offset_m)
|
| 159 |
+
center = [
|
| 160 |
+
round(x_front + 0.5 * float(self.table_depth_m), 6),
|
| 161 |
+
0.0,
|
| 162 |
+
round(float(self.z_table_m) - 0.5 * table_thickness, 6),
|
| 163 |
+
]
|
| 164 |
+
half_extents = [
|
| 165 |
+
round(0.5 * float(self.table_depth_m), 6),
|
| 166 |
+
round(0.5 * float(self.table_width_m), 6),
|
| 167 |
+
round(0.5 * table_thickness, 6),
|
| 168 |
+
]
|
| 169 |
+
return center, half_extents
|
| 170 |
+
|
| 171 |
+
def to_dict(self) -> dict[str, Any]:
|
| 172 |
+
"""Serializes to a clean JSON-ready dictionary without redundant nulls."""
|
| 173 |
+
data = asdict(self)
|
| 174 |
+
if data.get("max_joint_speed_deg_s") is None:
|
| 175 |
+
data.pop("max_joint_speed_deg_s", None)
|
| 176 |
+
return data
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _overlay_arm_config(arm: ArmConfig, raw: Mapping[str, Any]) -> None:
|
| 180 |
+
if "ip" in raw:
|
| 181 |
+
arm.ip = "" if raw["ip"] is None else str(raw["ip"]).strip()
|
| 182 |
+
if "enabled" in raw and raw["enabled"] is not None:
|
| 183 |
+
arm.enabled = bool(raw["enabled"])
|
| 184 |
+
raw_rest = raw.get("rest_pose_rad")
|
| 185 |
+
if (
|
| 186 |
+
isinstance(raw_rest, (Sequence, np.ndarray))
|
| 187 |
+
and not isinstance(raw_rest, (str, bytes))
|
| 188 |
+
and len(raw_rest) == 7
|
| 189 |
+
):
|
| 190 |
+
arm.rest_pose_rad = [float(x) for x in raw_rest]
|
| 191 |
+
if "gripper_port" in raw and raw["gripper_port"] is not None:
|
| 192 |
+
arm.gripper_port = str(raw["gripper_port"])
|
| 193 |
+
if "gripper_slave_id" in raw and raw["gripper_slave_id"] is not None:
|
| 194 |
+
arm.gripper_slave_id = int(raw["gripper_slave_id"])
|
| 195 |
+
if "gripper_baudrate" in raw and raw["gripper_baudrate"] is not None:
|
| 196 |
+
arm.gripper_baudrate = int(raw["gripper_baudrate"])
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _overlay_camera_spec(
|
| 200 |
+
base: fr3_camera_controller.CameraStreamSpec, raw: Mapping[str, Any]
|
| 201 |
+
) -> fr3_camera_controller.CameraStreamSpec:
|
| 202 |
+
merged = {
|
| 203 |
+
"role": base.role,
|
| 204 |
+
"serial": base.serial,
|
| 205 |
+
"device_path": base.device_path,
|
| 206 |
+
"width": base.width,
|
| 207 |
+
"height": base.height,
|
| 208 |
+
"fps": base.fps,
|
| 209 |
+
"zed_conf_path": base.zed_conf_path,
|
| 210 |
+
}
|
| 211 |
+
for key, val in raw.items():
|
| 212 |
+
if val is not None:
|
| 213 |
+
merged[key] = val
|
| 214 |
+
return fr3_camera_controller.CameraStreamSpec.from_mapping(
|
| 215 |
+
base.role, merged
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def default_robot_config() -> RobotConfig:
|
| 220 |
+
"""Returns the canonical default `RobotConfig` for an FR3 Duo cell."""
|
| 221 |
+
return RobotConfig()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def normalize_robot_config(
|
| 225 |
+
updates: RobotConfig | Mapping[str, Any] | None = None,
|
| 226 |
+
) -> RobotConfig:
|
| 227 |
+
"""Merges partial `updates` (or copies `RobotConfig`) onto defaults.
|
| 228 |
+
|
| 229 |
+
`z_table_m` is derived from `base_height_m` and `table_height_m`. Legacy
|
| 230 |
+
mappings supplying only `z_table_m` (without raw floor heights) adjust
|
| 231 |
+
`base_height_m` so the derived `z_table_m` property matches cleanly.
|
| 232 |
+
"""
|
| 233 |
+
if isinstance(updates, RobotConfig):
|
| 234 |
+
return copy.deepcopy(updates)
|
| 235 |
+
|
| 236 |
+
raw = dict(updates) if isinstance(updates, Mapping) else {}
|
| 237 |
+
cfg = default_robot_config()
|
| 238 |
+
|
| 239 |
+
for str_key in (
|
| 240 |
+
"platform",
|
| 241 |
+
"realtime_mode",
|
| 242 |
+
"zed_settings_dir",
|
| 243 |
+
):
|
| 244 |
+
if str_key in raw and raw[str_key] is not None:
|
| 245 |
+
setattr(cfg, str_key, str(raw[str_key]))
|
| 246 |
+
|
| 247 |
+
for float_key in (
|
| 248 |
+
"base_height_m",
|
| 249 |
+
"table_height_m",
|
| 250 |
+
"table_front_offset_m",
|
| 251 |
+
"table_width_m",
|
| 252 |
+
"table_depth_m",
|
| 253 |
+
"min_inter_arm_clearance_m",
|
| 254 |
+
"tcp_offset_z_m",
|
| 255 |
+
):
|
| 256 |
+
if float_key in raw and raw[float_key] is not None:
|
| 257 |
+
setattr(cfg, float_key, float(raw[float_key]))
|
| 258 |
+
|
| 259 |
+
if "geometry_confirmed" in raw and raw["geometry_confirmed"] is not None:
|
| 260 |
+
cfg.geometry_confirmed = bool(raw["geometry_confirmed"])
|
| 261 |
+
|
| 262 |
+
has_raw_heights = (
|
| 263 |
+
raw.get("base_height_m") is not None
|
| 264 |
+
or raw.get("table_height_m") is not None
|
| 265 |
+
)
|
| 266 |
+
if raw.get("z_table_m") is not None and not has_raw_heights:
|
| 267 |
+
cfg.base_height_m = round(
|
| 268 |
+
BASE_WORLD_Z_M + float(cfg.table_height_m) - float(raw["z_table_m"]), 6
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
if raw.get("max_joint_speed_deg_s") is not None:
|
| 272 |
+
cfg.max_joint_speed_deg_s = float(raw["max_joint_speed_deg_s"])
|
| 273 |
+
|
| 274 |
+
raw_arms = raw.get("arms")
|
| 275 |
+
if isinstance(raw_arms, Mapping):
|
| 276 |
+
for side in ("left", "right"):
|
| 277 |
+
raw_arm = raw_arms.get(side)
|
| 278 |
+
if isinstance(raw_arm, Mapping):
|
| 279 |
+
_overlay_arm_config(cfg.arms[side], raw_arm)
|
| 280 |
+
|
| 281 |
+
raw_cams = raw.get("cameras")
|
| 282 |
+
if isinstance(raw_cams, Mapping):
|
| 283 |
+
for role in ("head_stereo", "wrist_camera_left", "wrist_camera_right"):
|
| 284 |
+
raw_cam = raw_cams.get(role)
|
| 285 |
+
if isinstance(raw_cam, fr3_camera_controller.CameraStreamSpec):
|
| 286 |
+
setattr(cfg.cameras, role, copy.deepcopy(raw_cam))
|
| 287 |
+
elif isinstance(raw_cam, Mapping):
|
| 288 |
+
setattr(
|
| 289 |
+
cfg.cameras,
|
| 290 |
+
role,
|
| 291 |
+
_overlay_camera_spec(cfg.cameras[role], raw_cam),
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
return cfg
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def table_box_bounds(
|
| 298 |
+
config: RobotConfig | Mapping[str, Any] | None = None,
|
| 299 |
+
) -> tuple[list[float], list[float]]:
|
| 300 |
+
"""Returns `(center, half_extents)` for the configured tabletop box."""
|
| 301 |
+
cfg = (
|
| 302 |
+
config
|
| 303 |
+
if isinstance(config, RobotConfig)
|
| 304 |
+
else normalize_robot_config(config)
|
| 305 |
+
)
|
| 306 |
+
return cfg.table_box_bounds()
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _is_camera_bound(cam: Any) -> bool:
|
| 310 |
+
return bool(
|
| 311 |
+
str(getattr(cam, "device_path", "") or "").strip()
|
| 312 |
+
or str(getattr(cam, "serial", "") or "").strip()
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _is_valid_geom_number(value: Any, *, allow_zero: bool) -> bool:
|
| 317 |
+
try:
|
| 318 |
+
fval = float(value)
|
| 319 |
+
except (TypeError, ValueError):
|
| 320 |
+
return False
|
| 321 |
+
if not math.isfinite(fval):
|
| 322 |
+
return False
|
| 323 |
+
return fval >= 0.0 if allow_zero else fval > 0.0
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def validate_robot_config_complete(
|
| 327 |
+
config: RobotConfig | Mapping[str, Any],
|
| 328 |
+
) -> list[str]:
|
| 329 |
+
"""Returns missing or unconfirmed config fields required for live hardware."""
|
| 330 |
+
cfg = normalize_robot_config(config)
|
| 331 |
+
missing: list[str] = []
|
| 332 |
+
|
| 333 |
+
for side in ("left", "right"):
|
| 334 |
+
arm_cfg = cfg.arms[side]
|
| 335 |
+
if not str(arm_cfg.ip or "").strip():
|
| 336 |
+
missing.append(f"arms.{side}.ip")
|
| 337 |
+
if not str(arm_cfg.gripper_port or "").strip():
|
| 338 |
+
missing.append(f"arms.{side}.gripper_port")
|
| 339 |
+
|
| 340 |
+
for role in ("head_stereo", "wrist_camera_left", "wrist_camera_right"):
|
| 341 |
+
if not _is_camera_bound(cfg.cameras[role]):
|
| 342 |
+
missing.append(f"cameras.{role}")
|
| 343 |
+
|
| 344 |
+
geom_rules = (
|
| 345 |
+
("base_height_m", False),
|
| 346 |
+
("table_height_m", True),
|
| 347 |
+
("table_front_offset_m", True),
|
| 348 |
+
("table_width_m", False),
|
| 349 |
+
("table_depth_m", False),
|
| 350 |
+
("tcp_offset_z_m", False),
|
| 351 |
+
)
|
| 352 |
+
for field_name, allow_zero in geom_rules:
|
| 353 |
+
if not _is_valid_geom_number(
|
| 354 |
+
getattr(cfg, field_name), allow_zero=allow_zero
|
| 355 |
+
):
|
| 356 |
+
missing.append(field_name)
|
| 357 |
+
|
| 358 |
+
if not bool(cfg.geometry_confirmed):
|
| 359 |
+
missing.append("geometry_confirmed")
|
| 360 |
+
|
| 361 |
+
return missing
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def load_robot_config(path: str | Path | None = None) -> RobotConfig:
|
| 365 |
+
"""Loads `robot_config.json`, merging values onto `default_robot_config()`."""
|
| 366 |
+
target = Path(DEFAULT_CONFIG_PATH) if path is None else Path(path)
|
| 367 |
+
if not target.is_file():
|
| 368 |
+
if path is None or target.as_posix().endswith(DEFAULT_CONFIG_PATH):
|
| 369 |
+
return default_robot_config()
|
| 370 |
+
raise FileNotFoundError(f"Robot config file not found: {target}")
|
| 371 |
+
loaded = json.loads(target.read_text(encoding="utf-8"))
|
| 372 |
+
if not isinstance(loaded, dict):
|
| 373 |
+
raise ValueError(f"Expected JSON object in {target}, got {type(loaded)!r}")
|
| 374 |
+
return normalize_robot_config(loaded)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def save_robot_config(
|
| 378 |
+
config: RobotConfig | Mapping[str, Any], path: str | Path
|
| 379 |
+
) -> None:
|
| 380 |
+
"""Writes `config` as formatted JSON."""
|
| 381 |
+
target = Path(path)
|
| 382 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 383 |
+
norm = normalize_robot_config(config)
|
| 384 |
+
serialized = json.dumps(norm.to_dict(), indent=2, sort_keys=False) + "\n"
|
| 385 |
+
target.write_text(serialized, encoding="utf-8")
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def resolve_stage_output_dir(
|
| 389 |
+
stage_name: str, explicit_dir: Path | None, *, dry_run: bool
|
| 390 |
+
) -> Path | None:
|
| 391 |
+
"""Resolves stage log directory while keeping source trees clean."""
|
| 392 |
+
if explicit_dir is not None:
|
| 393 |
+
return explicit_dir
|
| 394 |
+
if dry_run:
|
| 395 |
+
return None
|
| 396 |
+
cwd = Path.cwd()
|
| 397 |
+
if os.environ.get("TEST_TMPDIR") or any(
|
| 398 |
+
(p / "WORKSPACE").is_file() for p in (cwd, *cwd.parents)
|
| 399 |
+
):
|
| 400 |
+
return Path(tempfile.gettempdir()) / "fr3_duo_logs" / stage_name
|
| 401 |
+
return Path("logs") / stage_name
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def save_rgb_png(rgb: np.ndarray, out_path: Path) -> None:
|
| 405 |
+
"""Saves an `(H, W, 3)` uint8 RGB image to `out_path` via OpenCV."""
|
| 406 |
+
cv2 = fr3_camera_controller.require_cv2()
|
| 407 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 408 |
+
arr = np.ascontiguousarray(rgb, dtype=np.uint8)
|
| 409 |
+
bgr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
|
| 410 |
+
if not cv2.imwrite(str(out_path), bgr):
|
| 411 |
+
raise RuntimeError(f"cv2.imwrite failed for {out_path}")
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def open_mp4_writer(
|
| 415 |
+
mp4_path: Path, width: int, height: int, fps: float
|
| 416 |
+
) -> Any:
|
| 417 |
+
"""Opens an OpenCV `cv2.VideoWriter` for `.mp4` output."""
|
| 418 |
+
cv2 = fr3_camera_controller.require_cv2()
|
| 419 |
+
mp4_path.parent.mkdir(parents=True, exist_ok=True)
|
| 420 |
+
for fourcc_str in ("mp4v", "avc1"):
|
| 421 |
+
writer = cv2.VideoWriter(
|
| 422 |
+
str(mp4_path),
|
| 423 |
+
cv2.VideoWriter_fourcc(*fourcc_str),
|
| 424 |
+
float(fps),
|
| 425 |
+
(int(width), int(height)),
|
| 426 |
+
)
|
| 427 |
+
if writer.isOpened():
|
| 428 |
+
return writer
|
| 429 |
+
writer.release()
|
| 430 |
+
raise RuntimeError(f"Failed to open cv2.VideoWriter for {mp4_path}")
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def detect_preempt_rt() -> bool:
|
| 434 |
+
"""Returns True when running on a Linux `PREEMPT_RT` real-time kernel."""
|
| 435 |
+
rt_sysfs = Path("/sys/kernel/realtime")
|
| 436 |
+
try:
|
| 437 |
+
if (
|
| 438 |
+
rt_sysfs.is_file()
|
| 439 |
+
and rt_sysfs.read_text(encoding="utf-8").strip() == "1"
|
| 440 |
+
):
|
| 441 |
+
return True
|
| 442 |
+
except OSError:
|
| 443 |
+
# Non-Linux or restricted sysfs environments fall back to uname inspection.
|
| 444 |
+
pass
|
| 445 |
+
try:
|
| 446 |
+
uname_ver = os.uname().version.upper()
|
| 447 |
+
if "PREEMPT_RT" in uname_ver or "PREEMPT RT" in uname_ver:
|
| 448 |
+
return True
|
| 449 |
+
except AttributeError:
|
| 450 |
+
# `os.uname` is absent on non-POSIX platforms.
|
| 451 |
+
pass
|
| 452 |
+
return False
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def resolve_realtime_config(
|
| 456 |
+
mode: str = "auto", *, is_preempt_rt: bool | None = None
|
| 457 |
+
) -> dict[str, Any]:
|
| 458 |
+
"""Resolves `pylibfranka` `RealtimeConfig` and safe joint speed/accel caps."""
|
| 459 |
+
normalized = mode.strip().lower()
|
| 460 |
+
if normalized not in ("auto", "enforce", "ignore"):
|
| 461 |
+
raise ValueError(
|
| 462 |
+
f"Invalid realtime mode={mode!r}; "
|
| 463 |
+
"expected 'auto', 'enforce', or 'ignore'"
|
| 464 |
+
)
|
| 465 |
+
rt_active = (
|
| 466 |
+
detect_preempt_rt() if is_preempt_rt is None else bool(is_preempt_rt)
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
if normalized == "enforce":
|
| 470 |
+
if not rt_active:
|
| 471 |
+
raise RuntimeError(
|
| 472 |
+
"PREEMPT_RT kernel is required for `--realtime enforce`, but the "
|
| 473 |
+
"current kernel is not real-time patched. Boot a PREEMPT_RT kernel "
|
| 474 |
+
"or pass `--realtime auto`."
|
| 475 |
+
)
|
| 476 |
+
return {
|
| 477 |
+
"mode": "enforce",
|
| 478 |
+
"is_preempt_rt": True,
|
| 479 |
+
"realtime_config": "kEnforce",
|
| 480 |
+
"max_joint_speed_deg_s": 45.0,
|
| 481 |
+
"max_joint_acc_rad_s2": 5.0,
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
if normalized == "auto" and rt_active:
|
| 485 |
+
return {
|
| 486 |
+
"mode": "auto",
|
| 487 |
+
"is_preempt_rt": True,
|
| 488 |
+
"realtime_config": "kEnforce",
|
| 489 |
+
"max_joint_speed_deg_s": 30.0,
|
| 490 |
+
"max_joint_acc_rad_s2": 3.5,
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
return {
|
| 494 |
+
"mode": normalized,
|
| 495 |
+
"is_preempt_rt": rt_active,
|
| 496 |
+
"realtime_config": "kIgnore",
|
| 497 |
+
"max_joint_speed_deg_s": 15.0,
|
| 498 |
+
"max_joint_acc_rad_s2": 2.0,
|
| 499 |
+
}
|