nablaengine 1.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nablaengine/__init__.py +4 -0
- nablaengine/_fixtures/README.md +19 -0
- nablaengine/_fixtures/data/mf_s0.npz +0 -0
- nablaengine/_fixtures/mjlab/LICENSE +27 -0
- nablaengine/_fixtures/mjlab/README.md +113 -0
- nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
- nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
- nablaengine/_optional.py +30 -0
- nablaengine/_paths.py +38 -0
- nablaengine/actuators/__init__.py +169 -0
- nablaengine/actuators/bam.py +306 -0
- nablaengine/actuators/bam_params/LICENSE +202 -0
- nablaengine/actuators/bam_params/xl330/m6.json +19 -0
- nablaengine/boxbox.py +259 -0
- nablaengine/ccd.py +1122 -0
- nablaengine/checks.py +376 -0
- nablaengine/cuda.py +483 -0
- nablaengine/dist_query.py +628 -0
- nablaengine/dual.py +223 -0
- nablaengine/dyn_query.py +685 -0
- nablaengine/engines.py +114 -0
- nablaengine/envs/__init__.py +24 -0
- nablaengine/envs/brax.py +165 -0
- nablaengine/envs/convert.py +771 -0
- nablaengine/envs/dmc.py +523 -0
- nablaengine/envs/env.py +233 -0
- nablaengine/envs/kin.py +371 -0
- nablaengine/envs/ops.py +134 -0
- nablaengine/envs/rewards.py +57 -0
- nablaengine/fixtures.py +243 -0
- nablaengine/forest_engine/__init__.py +0 -0
- nablaengine/forest_engine/adjoint.py +1726 -0
- nablaengine/forest_engine/adjoint_contact.py +493 -0
- nablaengine/forest_engine/bam_hooks.py +248 -0
- nablaengine/forest_engine/body_params.py +1007 -0
- nablaengine/forest_engine/capacity_diag.py +116 -0
- nablaengine/forest_engine/ccd_coop.py +250 -0
- nablaengine/forest_engine/chol_blk.py +80 -0
- nablaengine/forest_engine/contact_forces.py +142 -0
- nablaengine/forest_engine/contact_vjp.py +462 -0
- nablaengine/forest_engine/convex.py +1331 -0
- nablaengine/forest_engine/cylinder.py +73 -0
- nablaengine/forest_engine/dist_device.py +923 -0
- nablaengine/forest_engine/dyn_device.py +696 -0
- nablaengine/forest_engine/ellipsoid.py +179 -0
- nablaengine/forest_engine/elliptic.py +272 -0
- nablaengine/forest_engine/equality.py +842 -0
- nablaengine/forest_engine/floss.py +148 -0
- nablaengine/forest_engine/foot_offset.py +368 -0
- nablaengine/forest_engine/free_gyro.py +288 -0
- nablaengine/forest_engine/host.py +530 -0
- nablaengine/forest_engine/kdof64.py +127 -0
- nablaengine/forest_engine/kinematics.py +320 -0
- nablaengine/forest_engine/margin.py +167 -0
- nablaengine/forest_engine/margin_convex.py +326 -0
- nablaengine/forest_engine/midphase.py +439 -0
- nablaengine/forest_engine/model_hooks.py +913 -0
- nablaengine/forest_engine/motor_hooks.py +50 -0
- nablaengine/forest_engine/muscle.py +485 -0
- nablaengine/forest_engine/nb128.py +118 -0
- nablaengine/forest_engine/nb64.py +163 -0
- nablaengine/forest_engine/noslip.py +1124 -0
- nablaengine/forest_engine/nv128.py +1944 -0
- nablaengine/forest_engine/object_size.py +283 -0
- nablaengine/forest_engine/replay_guard.py +40 -0
- nablaengine/forest_engine/root_spread.py +126 -0
- nablaengine/forest_engine/solref.py +74 -0
- nablaengine/forest_engine/source.py +1464 -0
- nablaengine/forest_engine/sparse_pattern.py +527 -0
- nablaengine/forest_engine/spatial.py +1045 -0
- nablaengine/forest_engine/step.py +3083 -0
- nablaengine/forest_engine/surrogate.py +498 -0
- nablaengine/forest_engine/tape.py +199 -0
- nablaengine/forest_engine/tendon.py +845 -0
- nablaengine/forest_engine/terrain.py +1059 -0
- nablaengine/forest_engine/world_forces.py +166 -0
- nablaengine/forest_engine/world_params.py +230 -0
- nablaengine/g1_engine/__init__.py +0 -0
- nablaengine/g1_engine/adjoint.py +1661 -0
- nablaengine/g1_engine/adjoint_contact.py +577 -0
- nablaengine/g1_engine/bam_hooks.py +596 -0
- nablaengine/g1_engine/condim4.py +245 -0
- nablaengine/g1_engine/contact_forces.py +500 -0
- nablaengine/g1_engine/cylccd.py +1158 -0
- nablaengine/g1_engine/cylinder.py +216 -0
- nablaengine/g1_engine/elliptic.py +565 -0
- nablaengine/g1_engine/exact_replay.py +61 -0
- nablaengine/g1_engine/host.py +358 -0
- nablaengine/g1_engine/kinematics.py +320 -0
- nablaengine/g1_engine/mesh.py +305 -0
- nablaengine/g1_engine/mesh_tables.py +79 -0
- nablaengine/g1_engine/model_hooks.py +919 -0
- nablaengine/g1_engine/motor_hooks.py +70 -0
- nablaengine/g1_engine/replay_guard.py +55 -0
- nablaengine/g1_engine/source.py +1107 -0
- nablaengine/g1_engine/sphbox.py +93 -0
- nablaengine/g1_engine/step.py +3716 -0
- nablaengine/g1_engine/tape.py +173 -0
- nablaengine/g1_engine/world_params.py +447 -0
- nablaengine/identity.py +401 -0
- nablaengine/jax_ffi.py +2536 -0
- nablaengine/model/__init__.py +1 -0
- nablaengine/model/capability.py +694 -0
- nablaengine/model/fields.py +317 -0
- nablaengine/model/gravcomp.py +64 -0
- nablaengine/model/invweight.py +145 -0
- nablaengine/motor.py +143 -0
- nablaengine/object_geometry.py +609 -0
- nablaengine/params.py +258 -0
- nablaengine/provenance.py +196 -0
- nablaengine/reference/__init__.py +0 -0
- nablaengine/reference/adjoint_groups.py +226 -0
- nablaengine/reference/jax64.py +690 -0
- nablaengine/reference/warp_physics.py +262 -0
- nablaengine/sensors/__init__.py +4 -0
- nablaengine/sensors/cameras.py +285 -0
- nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
- nablaengine/sensors/data/livox_mid360.npz +0 -0
- nablaengine/sensors/g1.py +521 -0
- nablaengine/sensors/jax_rays.py +364 -0
- nablaengine/sensors/optix_rays.py +725 -0
- nablaengine/sensors/raycore.py +630 -0
- nablaengine/sensors/raygrad.py +374 -0
- nablaengine/sensors/raygrad_cuda.py +191 -0
- nablaengine/sensors/robot_mesh.py +273 -0
- nablaengine/sensors/torch_rays.py +275 -0
- nablaengine/terrain.py +424 -0
- nablaengine/torch_ffi.py +1328 -0
- nablaengine/workdir.py +37 -0
- nablaengine-1.0.2.dist-info/METADATA +236 -0
- nablaengine-1.0.2.dist-info/RECORD +136 -0
- nablaengine-1.0.2.dist-info/WHEEL +5 -0
- nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
- nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
- nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
- nablaengine-1.0.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
"""Per-world object geometry: the poses, sizes, velocities and face tables of a scene's objects and terrain, read from
|
|
2
|
+
the engine's state, in the world frame (docs/sensors.md, "Object geometry")."""
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
FACE_WORDS = 16
|
|
8
|
+
CLASS_TOP, CLASS_SIDE, CLASS_BOTTOM = 0, 1, 2
|
|
9
|
+
CLASS_NAMES = ("top", "side", "bottom")
|
|
10
|
+
COS_CLASS = math.cos(math.radians(45.0))
|
|
11
|
+
SRC_TERRAIN = -2
|
|
12
|
+
KIND_BODY, KIND_STATIC, KIND_SLOT = 0, 1, 2
|
|
13
|
+
ROW_WORDS = 7
|
|
14
|
+
_UPRIGHT_TOL = 1e-6
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _hi():
|
|
18
|
+
import jax
|
|
19
|
+
return jax.lax.Precision.HIGHEST
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _einsum(*args):
|
|
23
|
+
import jax.numpy as jnp
|
|
24
|
+
return jnp.einsum(*args, precision=_hi())
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def geom_world_pose(xpos, xquat, body, pos, rot, geom_offset=None):
|
|
28
|
+
"""World pose of geoms fixed to bodies: centres (B, K, 3) and rotations (B, K, 3, 3) from the body poses xpos (B,
|
|
29
|
+
nbody, 3), xquat (B, nbody, 4) (jax_ffi.kinematics'), the geoms' bodies body (K,), local positions pos (K, 3) and
|
|
30
|
+
rotations rot (K, 3, 3) (the model's geom_pos / geom_quat); geom_offset: None, or a per-world shift of the centre in
|
|
31
|
+
the body frame, (B, 3) or (B, K, 3), added to pos."""
|
|
32
|
+
import jax.numpy as jnp
|
|
33
|
+
from nablaengine.sensors.g1 import G1Sensors
|
|
34
|
+
B, K = xpos.shape[0], len(body)
|
|
35
|
+
Rb = G1Sensors._qmat(xquat[:, body])
|
|
36
|
+
gp = jnp.broadcast_to(jnp.asarray(pos), (B, K, 3))
|
|
37
|
+
if geom_offset is not None:
|
|
38
|
+
gp = gp + jnp.broadcast_to(jnp.asarray(geom_offset, jnp.float32).reshape(B, -1, 3), (B, K, 3))
|
|
39
|
+
p = xpos[:, body] + _einsum("bkij,bkj->bki", Rb, gp)
|
|
40
|
+
R = _einsum("bkij,kjl->bkil", Rb, jnp.asarray(rot))
|
|
41
|
+
return p, R
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _cross(a, b):
|
|
45
|
+
import jax.numpy as jnp
|
|
46
|
+
return jnp.stack([a[..., 1] * b[..., 2] - a[..., 2] * b[..., 1], a[..., 2] * b[..., 0] - a[..., 0] * b[..., 2],
|
|
47
|
+
a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]], -1)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def up_vector(gravity):
|
|
51
|
+
"""Unit up vectors (B, 3) = -g / |g| of gravity vectors (B, 3) (+z where g = 0)."""
|
|
52
|
+
import jax.numpy as jnp
|
|
53
|
+
n2 = jnp.sum(gravity * gravity, -1, keepdims=True)
|
|
54
|
+
safe = jnp.where(n2 > 0, n2, 1.0)
|
|
55
|
+
return jnp.where(n2 > 0, -gravity / jnp.sqrt(safe), jnp.asarray([0.0, 0.0, 1.0], gravity.dtype))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def surface_class(normal, up):
|
|
59
|
+
"""Surface class (B, ...) int32 of unit normals (B, ..., 3) for up vectors (B, 3): CLASS_TOP / CLASS_SIDE /
|
|
60
|
+
CLASS_BOTTOM (module docstring)."""
|
|
61
|
+
import jax.numpy as jnp
|
|
62
|
+
c = jnp.sum(normal * up.reshape(up.shape[:1] + (1,) * (normal.ndim - 2) + (3,)), -1)
|
|
63
|
+
return jnp.where(c > COS_CLASS, CLASS_TOP, jnp.where(c < -COS_CLASS, CLASS_BOTTOM, CLASS_SIDE)).astype(jnp.int32)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def box_face_records(centre, rot, half, valid=None):
|
|
67
|
+
"""The six faces (..., 6, FACE_WORDS) of boxes (centre (..., 3), rotation (..., 3, 3), half sizes (..., 3)), in
|
|
68
|
+
the order -x, +x, -y, +y, -z, +z of the box frame (the scene-tracking work's box_faces): centre c + s R e_a h_a,
|
|
69
|
+
normal s R e_a, u, v the box's other two axes in order (R e_b, R e_c), half widths h_b, h_c; class 0 (set by the
|
|
70
|
+
caller), on 1 (valid (...,) bool: 0 and the whole record zero where False). JAX, differentiable."""
|
|
71
|
+
import jax.numpy as jnp
|
|
72
|
+
recs = []
|
|
73
|
+
for ax in range(3):
|
|
74
|
+
o1, o2 = [k for k in range(3) if k != ax]
|
|
75
|
+
for sg in (-1.0, 1.0):
|
|
76
|
+
n = sg * rot[..., :, ax]
|
|
77
|
+
c = centre + n * half[..., ax:ax + 1]
|
|
78
|
+
one = jnp.ones_like(half[..., :1])
|
|
79
|
+
recs.append(jnp.concatenate([c, n, rot[..., :, o1], rot[..., :, o2], half[..., o1:o1 + 1],
|
|
80
|
+
half[..., o2:o2 + 1], 0 * one, one], -1))
|
|
81
|
+
out = jnp.stack(recs, -2)
|
|
82
|
+
if valid is not None:
|
|
83
|
+
out = jnp.where(valid[..., None, None], out, 0.0)
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def classify_faces(faces, up):
|
|
88
|
+
"""faces (B, F, FACE_WORDS) with the class column set from the normals and up (B, 3); padded records (on = 0) stay
|
|
89
|
+
zero."""
|
|
90
|
+
import jax.numpy as jnp
|
|
91
|
+
cls = surface_class(faces[..., 3:6], up).astype(faces.dtype)
|
|
92
|
+
cls = jnp.where(faces[..., 15] > 0, cls, 0.0)
|
|
93
|
+
return jnp.concatenate([faces[..., :14], cls[..., None], faces[..., 15:]], -1)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def box_rows(boxes):
|
|
97
|
+
"""(rows (n, 7) float64, upright (n,) bool) of boxes given as rows (n, 7) (centre, half sizes, yaw; hz <= 0: absent;
|
|
98
|
+
the scene-tracking work's scene rows) or as words (n, 15) (pos, rotation row major, half sizes:
|
|
99
|
+
terrain.Terrain.boxes, object slots; half sizes 0: absent). A word box is upright when its rotation keeps the z
|
|
100
|
+
axis vertical (|R_zz| >= 1 - 1e-6); its yaw is atan2(R_yx, R_xx). Rows are upright."""
|
|
101
|
+
b = np.asarray(boxes, np.float64)
|
|
102
|
+
if b.ndim == 1:
|
|
103
|
+
b = b.reshape(1, -1)
|
|
104
|
+
if b.shape[-1] == ROW_WORDS:
|
|
105
|
+
return b.reshape(-1, ROW_WORDS).copy(), np.ones(len(b.reshape(-1, ROW_WORDS)), bool)
|
|
106
|
+
if b.shape[-1] != 15:
|
|
107
|
+
raise ValueError(f"object_geometry: boxes as rows (n, 7) or words (n, 15), got {b.shape}")
|
|
108
|
+
b = b.reshape(-1, 15)
|
|
109
|
+
R = b[:, 3:12].reshape(-1, 3, 3)
|
|
110
|
+
rows = np.zeros((len(b), ROW_WORDS))
|
|
111
|
+
rows[:, :3], rows[:, 3:6] = b[:, :3], b[:, 12:15]
|
|
112
|
+
rows[:, 6] = np.arctan2(R[:, 1, 0], R[:, 0, 0])
|
|
113
|
+
present = np.all(b[:, 12:15] > 0, 1)
|
|
114
|
+
rows[~present] = 0.0
|
|
115
|
+
upright = np.abs(R[:, 2, 2]) >= 1 - _UPRIGHT_TOL
|
|
116
|
+
return rows, upright | ~present
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _rects_touch(lo, hi, margin):
|
|
120
|
+
return np.all((lo[:, None, :] <= hi[None, :, :] + margin) & (lo[None, :, :] <= hi[:, None, :] + margin), -1)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _make_disjoint(b, tol, max_pieces, ground=0.0):
|
|
124
|
+
k = len(b)
|
|
125
|
+
on = b[:, 5] > 0
|
|
126
|
+
if on.sum() <= 1:
|
|
127
|
+
return b.astype(np.float32), np.arange(k), "unchanged"
|
|
128
|
+
on_idx = np.nonzero(on)[0]
|
|
129
|
+
yaw = b[on, 6]
|
|
130
|
+
if np.ptp(np.mod(yaw - yaw[0] + np.pi, 2 * np.pi)) > 1e-3:
|
|
131
|
+
return b.astype(np.float32), np.arange(k), "skipped"
|
|
132
|
+
c, s_ = np.cos(yaw[0]), np.sin(yaw[0])
|
|
133
|
+
rects = []
|
|
134
|
+
for r in b[on]:
|
|
135
|
+
x, y = c * r[0] + s_ * r[1], -s_ * r[0] + c * r[1]
|
|
136
|
+
rects.append([x - r[3], x + r[3], y - r[4], y + r[4], r[2] + r[5]])
|
|
137
|
+
ra = np.asarray(rects)
|
|
138
|
+
near = _rects_touch(ra[:, [0, 2]], ra[:, [1, 3]], 2 * tol)
|
|
139
|
+
order = sorted(range(len(rects)), key=lambda i: -rects[i][4])
|
|
140
|
+
placed, owner, src, changed = [], [], [], False
|
|
141
|
+
for i in order:
|
|
142
|
+
pieces = [rects[i][:4]]
|
|
143
|
+
for h, hi in zip(placed, owner):
|
|
144
|
+
if not near[i, hi]:
|
|
145
|
+
continue
|
|
146
|
+
nxt = []
|
|
147
|
+
for (x0, x1, y0, y1) in pieces:
|
|
148
|
+
ox = min(x1, h[1]) - max(x0, h[0])
|
|
149
|
+
oy = min(y1, h[3]) - max(y0, h[2])
|
|
150
|
+
if ox <= tol or oy <= tol:
|
|
151
|
+
nxt.append((x0, x1, y0, y1))
|
|
152
|
+
continue
|
|
153
|
+
changed = True
|
|
154
|
+
if h[2] <= y0 + tol and h[3] >= y1 - tol:
|
|
155
|
+
nxt += [p for p in ((x0, h[0], y0, y1), (h[1], x1, y0, y1)) if p[1] - p[0] > tol]
|
|
156
|
+
elif h[0] <= x0 + tol and h[1] >= x1 - tol:
|
|
157
|
+
nxt += [p for p in ((x0, x1, y0, h[2]), (x0, x1, h[3], y1)) if p[3] - p[2] > tol]
|
|
158
|
+
else:
|
|
159
|
+
return b.astype(np.float32), np.arange(k), "skipped"
|
|
160
|
+
pieces = nxt
|
|
161
|
+
placed += [list(p) + [rects[i][4]] for p in pieces]
|
|
162
|
+
owner += [i] * len(pieces)
|
|
163
|
+
src += [int(on_idx[i])] * len(pieces)
|
|
164
|
+
if not changed:
|
|
165
|
+
return b.astype(np.float32), np.arange(k), "unchanged"
|
|
166
|
+
if max_pieces is not None and len(placed) > max(k, int(max_pieces)):
|
|
167
|
+
return b.astype(np.float32), np.arange(k), "skipped"
|
|
168
|
+
out = np.zeros((len(placed), ROW_WORDS))
|
|
169
|
+
for j, (x0, x1, y0, y1, t) in enumerate(placed):
|
|
170
|
+
xm, ym = (x0 + x1) / 2, (y0 + y1) / 2
|
|
171
|
+
out[j] = [c * xm - s_ * ym, s_ * xm + c * ym, (t + ground) / 2, (x1 - x0) / 2, (y1 - y0) / 2, (t - ground) / 2,
|
|
172
|
+
yaw[0]]
|
|
173
|
+
return out.astype(np.float32), np.asarray(src, np.int64), "converted"
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _rect_faces(x0, x1, y0, y1, zlo, top, yaw, side_cov=None, tol=1e-4):
|
|
177
|
+
c, s = math.cos(yaw), math.sin(yaw)
|
|
178
|
+
ex, ey, ez = np.array([c, s, 0.0]), np.array([-s, c, 0.0]), np.array([0.0, 0.0, 1.0])
|
|
179
|
+
w = lambda x, y, z: x * ex + y * ey + z * ez
|
|
180
|
+
out = []
|
|
181
|
+
if top - zlo > tol:
|
|
182
|
+
out.append(np.concatenate([w((x0 + x1) / 2, (y0 + y1) / 2, top), ez, ex, ey,
|
|
183
|
+
[(x1 - x0) / 2, (y1 - y0) / 2, 0.0, 1.0]]))
|
|
184
|
+
sides = (("x", -1, x0, y0, y1), ("x", 1, x1, y0, y1), ("y", -1, y0, x0, x1), ("y", 1, y1, x0, x1))
|
|
185
|
+
for si, (ax, sg, pos, a0, a1) in enumerate(sides):
|
|
186
|
+
strips = side_cov[si] if side_cov is not None else []
|
|
187
|
+
cuts = sorted({a0, a1} | {min(max(v, a0), a1) for st in strips for v in st[:2]})
|
|
188
|
+
segs = []
|
|
189
|
+
for p, q in zip(cuts[:-1], cuts[1:]):
|
|
190
|
+
if q - p <= tol:
|
|
191
|
+
continue
|
|
192
|
+
m = 0.5 * (p + q)
|
|
193
|
+
h = max([st[2] for st in strips if st[0] - tol <= m <= st[1] + tol] + [zlo])
|
|
194
|
+
if segs and abs(segs[-1][2] - h) < tol and abs(segs[-1][1] - p) < tol:
|
|
195
|
+
segs[-1][1] = q
|
|
196
|
+
else:
|
|
197
|
+
segs.append([p, q, h])
|
|
198
|
+
for p, q, h in segs:
|
|
199
|
+
if top - h <= tol:
|
|
200
|
+
continue
|
|
201
|
+
am, zm = 0.5 * (p + q), 0.5 * (h + top)
|
|
202
|
+
if ax == "x":
|
|
203
|
+
ctr, n, u = w(pos, am, zm), sg * ex, ey
|
|
204
|
+
else:
|
|
205
|
+
ctr, n, u = w(am, pos, zm), sg * ey, ex
|
|
206
|
+
out.append(np.concatenate([ctr, n, u, ez, [(q - p) / 2, (top - h) / 2, 1.0, 1.0]]))
|
|
207
|
+
return out
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _inside(p, b, tol=1e-4):
|
|
211
|
+
c, s = math.cos(b[6]), math.sin(b[6])
|
|
212
|
+
d = p - b[:3]
|
|
213
|
+
lx, ly = c * d[0] + s * d[1], -s * d[0] + c * d[1]
|
|
214
|
+
return abs(lx) < b[3] - tol and abs(ly) < b[4] - tol and abs(d[2]) < b[5] - tol
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _row_aabb(r):
|
|
218
|
+
c, s = abs(math.cos(r[6])), abs(math.sin(r[6]))
|
|
219
|
+
ex, ey = c * r[3] + s * r[4], s * r[3] + c * r[4]
|
|
220
|
+
return (r[0] - ex, r[1] - ey), (r[0] + ex, r[1] + ey)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _upright_faces(rows, tol, max_pieces, ground):
|
|
224
|
+
b = rows
|
|
225
|
+
if not (b[:, 5] > 0).any():
|
|
226
|
+
return np.zeros((0, FACE_WORDS)), np.zeros(0, np.int64), "empty"
|
|
227
|
+
d, dsrc, st = _make_disjoint(b, tol, max_pieces, ground)
|
|
228
|
+
d = np.asarray(d, np.float64)
|
|
229
|
+
on = d[:, 5] > 0
|
|
230
|
+
if st != "skipped" and len(np.unique(np.round(np.mod(d[on, 6], 2 * np.pi), 6))) <= 1:
|
|
231
|
+
yaw = float(d[on][0, 6])
|
|
232
|
+
c, s = math.cos(yaw), math.sin(yaw)
|
|
233
|
+
cols = []
|
|
234
|
+
for r in d[on]:
|
|
235
|
+
x, y = c * r[0] + s * r[1], -s * r[0] + c * r[1]
|
|
236
|
+
cols.append((x - r[3], x + r[3], y - r[4], y + r[4], max(r[2] - r[5], ground), r[2] + r[5]))
|
|
237
|
+
ca = np.asarray(cols).reshape(-1, 6)
|
|
238
|
+
near = _rects_touch(ca[:, [0, 2]], ca[:, [1, 3]], 2 * tol)
|
|
239
|
+
csrc = dsrc[on]
|
|
240
|
+
faces, fsrc = [], []
|
|
241
|
+
for j, (x0, x1, y0, y1, zlo, top) in enumerate(cols):
|
|
242
|
+
cov = [[], [], [], []]
|
|
243
|
+
for i in np.nonzero(near[j])[0]:
|
|
244
|
+
if i == j:
|
|
245
|
+
continue
|
|
246
|
+
nx0, nx1, ny0, ny1, _, ntop = cols[i]
|
|
247
|
+
oy, ox = (max(y0, ny0), min(y1, ny1)), (max(x0, nx0), min(x1, nx1))
|
|
248
|
+
if oy[1] - oy[0] > tol and abs(nx1 - x0) < tol:
|
|
249
|
+
cov[0].append((oy[0], oy[1], ntop))
|
|
250
|
+
if oy[1] - oy[0] > tol and abs(nx0 - x1) < tol:
|
|
251
|
+
cov[1].append((oy[0], oy[1], ntop))
|
|
252
|
+
if ox[1] - ox[0] > tol and abs(ny1 - y0) < tol:
|
|
253
|
+
cov[2].append((ox[0], ox[1], ntop))
|
|
254
|
+
if ox[1] - ox[0] > tol and abs(ny0 - y1) < tol:
|
|
255
|
+
cov[3].append((ox[0], ox[1], ntop))
|
|
256
|
+
f = _rect_faces(x0, x1, y0, y1, zlo, top, yaw, cov, tol)
|
|
257
|
+
faces += f
|
|
258
|
+
fsrc += [int(csrc[j])] * len(f)
|
|
259
|
+
return np.asarray(faces, np.float64).reshape(-1, FACE_WORDS), np.asarray(fsrc, np.int64), "disjoint"
|
|
260
|
+
sel = np.nonzero(b[:, 5] > 0)[0]
|
|
261
|
+
boxes = b[sel]
|
|
262
|
+
bb = [_row_aabb(r) for r in boxes]
|
|
263
|
+
lo, hi = np.asarray([x[0] for x in bb]), np.asarray([x[1] for x in bb])
|
|
264
|
+
near = _rects_touch(lo, hi, 2 * tol)
|
|
265
|
+
faces, fsrc = [], []
|
|
266
|
+
for k, r in enumerate(boxes):
|
|
267
|
+
zlo, top = max(r[2] - r[5], ground), r[2] + r[5]
|
|
268
|
+
c, s = math.cos(r[6]), math.sin(r[6])
|
|
269
|
+
x, y = c * r[0] + s * r[1], -s * r[0] + c * r[1]
|
|
270
|
+
others = [boxes[i] for i in np.nonzero(near[k])[0] if i != k]
|
|
271
|
+
for f in _rect_faces(x - r[3], x + r[3], y - r[4], y + r[4], zlo, top, float(r[6])):
|
|
272
|
+
if not any(_inside(f[0:3], o, tol) for o in others):
|
|
273
|
+
faces.append(f)
|
|
274
|
+
fsrc.append(int(sel[k]))
|
|
275
|
+
return np.asarray(faces, np.float64).reshape(-1, FACE_WORDS), np.asarray(fsrc, np.int64), "fallback"
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _box_faces_np(centre, R, half):
|
|
279
|
+
out = []
|
|
280
|
+
for ax in range(3):
|
|
281
|
+
o1, o2 = [k for k in range(3) if k != ax]
|
|
282
|
+
for sg in (-1.0, 1.0):
|
|
283
|
+
n = sg * R[:, ax]
|
|
284
|
+
out.append(np.concatenate([centre + n * half[ax], n, R[:, o1], R[:, o2], [half[o1], half[o2], 0.0, 1.0]]))
|
|
285
|
+
return np.asarray(out)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def exposed_faces(boxes, tol=1e-4, max_pieces=None, ground=0.0, with_source=False):
|
|
289
|
+
"""The exposed faces of one box scene (module docstring): boxes as rows (n, 7) or words (n, 15) (box_rows). Returns
|
|
290
|
+
(faces (m, FACE_WORDS) float64, mode "empty" / "disjoint" / "fallback"), with with_source also src (m,) int, each
|
|
291
|
+
face's box index. Classes as the reference's: 0 for the treads (normal +z), 1 for the sides (the device recomputes
|
|
292
|
+
them from each world's gravity). Rows give the scene-tracking work's exposed_faces bitwise (with max_pieces=8, its
|
|
293
|
+
slot limit: a scene cut into more pieces then falls back); None (the default) puts no limit on the pieces. Boxes
|
|
294
|
+
that are not upright (words only) emit their six faces (classes 0 for normals within 45 deg of +z, else 1).
|
|
295
|
+
ground: the height the columns stand on, below which no face is emitted (the scene-tracking scenes': 0, the
|
|
296
|
+
default; a terrain with pits below z = 0, e.g. mjlab's inverted stairs, needs its lowest level, or None: the
|
|
297
|
+
lowest box bottom of the scene)."""
|
|
298
|
+
rows, upright = box_rows(boxes)
|
|
299
|
+
cut = rows.copy()
|
|
300
|
+
cut[~upright] = 0.0
|
|
301
|
+
if ground is None:
|
|
302
|
+
on = cut[:, 5] > 0
|
|
303
|
+
ground = float(np.min(cut[on, 2] - cut[on, 5])) if on.any() else 0.0
|
|
304
|
+
faces, src, mode = _upright_faces(cut, tol, max_pieces, float(ground))
|
|
305
|
+
tilt = np.nonzero(~upright & np.all(np.asarray(boxes, np.float64).reshape(len(rows), -1)[:, -3:] > 0, 1))[0]
|
|
306
|
+
if len(tilt):
|
|
307
|
+
w = np.asarray(boxes, np.float64).reshape(len(rows), -1)
|
|
308
|
+
extra = []
|
|
309
|
+
for i in tilt:
|
|
310
|
+
f = _box_faces_np(w[i, :3], w[i, 3:12].reshape(3, 3), w[i, 12:15])
|
|
311
|
+
f[:, 14] = np.where(f[:, 5] > COS_CLASS, 0.0, 1.0)
|
|
312
|
+
extra.append(f)
|
|
313
|
+
faces = np.concatenate([faces] + extra, 0)
|
|
314
|
+
src = np.concatenate([src, np.repeat(tilt, 6)])
|
|
315
|
+
if mode == "empty":
|
|
316
|
+
mode = "fallback"
|
|
317
|
+
return (faces, mode, src) if with_source else (faces, mode)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def face_table(scenes, tol=1e-4, max_pieces=None, min_faces=1, ground=0.0):
|
|
321
|
+
"""Exposed faces of S scenes (S, n, 7 or 15) -> (faces (S, F, FACE_WORDS) float32 padded with zero records, src (S,
|
|
322
|
+
F) int32 (each face's box index, -1 padding), report {faces_max, faces_mean, empty, disjoint, fallback}); F >=
|
|
323
|
+
min_faces. Identical scenes are computed once."""
|
|
324
|
+
sc = np.asarray(scenes)
|
|
325
|
+
per, modes, memo = [], dict(empty=0, disjoint=0, fallback=0), {}
|
|
326
|
+
for s in sc:
|
|
327
|
+
key = s.tobytes()
|
|
328
|
+
if key not in memo:
|
|
329
|
+
memo[key] = exposed_faces(s, tol, max_pieces, ground, with_source=True)
|
|
330
|
+
f, m, src = memo[key]
|
|
331
|
+
per.append((f, src))
|
|
332
|
+
modes[m] += 1
|
|
333
|
+
F = max(int(min_faces), max([len(f) for f, _ in per] + [0]))
|
|
334
|
+
out = np.zeros((len(per), F, FACE_WORDS), np.float32)
|
|
335
|
+
srcs = np.full((len(per), F), -1, np.int32)
|
|
336
|
+
for i, (f, s) in enumerate(per):
|
|
337
|
+
out[i, :len(f)] = f
|
|
338
|
+
srcs[i, :len(f)] = s
|
|
339
|
+
return out, srcs, dict(faces_max=F, faces_mean=float(np.mean([len(f) for f, _ in per])) if per else 0.0, **modes)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def tile_scenes(boxes, origins, size):
|
|
343
|
+
"""Split static terrain boxes (n, 15) into tiles: the boxes whose centre lies in the tile [origin - size / 2, origin
|
|
344
|
+
+ size / 2) (xy; origins (T, 2 or 3), size (2,) or a scalar), e.g. mjlab's sub-terrains (TerrainGenerator's
|
|
345
|
+
terrain_origins, the sub-terrain size). Returns (T, n_max, 15) padded with absent boxes (zeros) and the box
|
|
346
|
+
indices (T, n_max) (-1 padding). Boxes outside every tile are left out."""
|
|
347
|
+
b = np.asarray(boxes, np.float64).reshape(-1, 15)
|
|
348
|
+
o = np.asarray(origins, np.float64).reshape(-1, np.shape(origins)[-1])[:, :2]
|
|
349
|
+
sz = np.broadcast_to(np.asarray(size, np.float64), (2,))
|
|
350
|
+
lo, hi = o - sz / 2, o + sz / 2
|
|
351
|
+
inside = np.all((b[None, :, :2] >= lo[:, None]) & (b[None, :, :2] < hi[:, None]), -1)
|
|
352
|
+
n = max(1, int(inside.sum(1).max()) if len(o) else 1)
|
|
353
|
+
out = np.zeros((len(o), n, 15))
|
|
354
|
+
idx = np.full((len(o), n), -1, np.int64)
|
|
355
|
+
for t in range(len(o)):
|
|
356
|
+
sel = np.nonzero(inside[t])[0]
|
|
357
|
+
out[t, :len(sel)] = b[sel]
|
|
358
|
+
idx[t, :len(sel)] = sel
|
|
359
|
+
return out, idx
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
class ObjectGeometry:
|
|
363
|
+
"""Per-world geometry of a build's objects, faces, floor and gravity (module docstring). Construction (host): the
|
|
364
|
+
model, the box geoms that are objects and the build (info, jax_ffi.init's: its com layout, terrain config and
|
|
365
|
+
per-world parameters); a call (device, jit-able): the kinematics outputs and com of B worlds."""
|
|
366
|
+
|
|
367
|
+
def __init__(self, model, geoms=None, bodies=None, *, info=None, params=None, com_layout=None, terrain=None,
|
|
368
|
+
tiles=None, slot_faces="box", floor="auto", faces=True, tol=1e-4, max_pieces=None, ground=0.0):
|
|
369
|
+
"""model: the physics model (MjModel, the engine's). geoms: box geom names or ids (one object each, in this
|
|
370
|
+
order); else bodies: names whose single box geom is taken; neither: no model objects. A geom on a moving body
|
|
371
|
+
is movable (KIND_BODY), one on the world body or welded to it static (KIND_STATIC).
|
|
372
|
+
info: jax_ffi.init's (or torch_ffi's) info, for com_layout, the terrain build's slots and floor flag; or pass
|
|
373
|
+
com_layout (info["com_layout"]) directly. params: the build's PhysicsParams (object_size: its geom takes each
|
|
374
|
+
world's half sizes from com; gravity: each world's gravity from com); None reads jax_ffi's current build when
|
|
375
|
+
its com layout has parameter words.
|
|
376
|
+
terrain: a static terrain.Terrain: the exposed faces of its boxes (heightfields: none), one table for all
|
|
377
|
+
worlds, or with tiles=(origins (T, 2|3), size) one table per tile (tile_scenes), chosen per world at the call.
|
|
378
|
+
slot_faces: the terrain slots' faces, "box" (each slot's 6 faces, on the device), "exposed" (the call takes a
|
|
379
|
+
table of each world's exposed slot faces, exposed_slot_faces) or None (no slot faces). floor: "auto" (the
|
|
380
|
+
model's first plane geom of the world body, unless the terrain build drops the floor: TerrainConfig.floor
|
|
381
|
+
False), None (no floor) or a plane geom name / id. faces: False skips every face table. tol, max_pieces,
|
|
382
|
+
ground: exposed_faces' (the terrain's and exposed_slot_faces')."""
|
|
383
|
+
import mujoco
|
|
384
|
+
box = int(mujoco.mjtGeom.mjGEOM_BOX)
|
|
385
|
+
ids = []
|
|
386
|
+
if geoms is not None:
|
|
387
|
+
for g in geoms:
|
|
388
|
+
gid = int(g) if not isinstance(g, str) else mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_GEOM, g)
|
|
389
|
+
if not 0 <= gid < model.ngeom or int(model.geom_type[gid]) != box:
|
|
390
|
+
raise ValueError(f"ObjectGeometry: {g!r} is not a box geom of the model")
|
|
391
|
+
ids.append(gid)
|
|
392
|
+
elif bodies is not None:
|
|
393
|
+
for name in bodies:
|
|
394
|
+
b = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, name)
|
|
395
|
+
if b < 1:
|
|
396
|
+
raise ValueError(f"ObjectGeometry: no body {name!r}")
|
|
397
|
+
gs = [g for g in range(model.ngeom)
|
|
398
|
+
if int(model.geom_bodyid[g]) == b and int(model.geom_type[g]) == box]
|
|
399
|
+
if len(gs) != 1:
|
|
400
|
+
raise ValueError(f"ObjectGeometry: body {name!r} has {len(gs)} box geoms (name it: geoms=...)")
|
|
401
|
+
ids.append(gs[0])
|
|
402
|
+
from nablaengine.sensors import cameras
|
|
403
|
+
self.geoms = np.asarray(ids, np.int32)
|
|
404
|
+
self.body = np.asarray([model.geom_bodyid[g] for g in ids], np.int32)
|
|
405
|
+
self.root = np.asarray([model.body_rootid[b] for b in self.body], np.int32)
|
|
406
|
+
self.pos = np.asarray([model.geom_pos[g] for g in ids], np.float32).reshape(-1, 3)
|
|
407
|
+
self.rot = np.asarray([cameras.quat_matrix(model.geom_quat[g]) for g in ids], np.float32).reshape(-1, 3, 3)
|
|
408
|
+
self.size = np.asarray([model.geom_size[g] for g in ids], np.float32).reshape(-1, 3)
|
|
409
|
+
self.movable_body = np.asarray([model.body_weldid[b] != 0 for b in self.body], bool)
|
|
410
|
+
self.kb = len(ids)
|
|
411
|
+
if info is None and com_layout is None:
|
|
412
|
+
com_layout = {"com_offset": (0, 3)}
|
|
413
|
+
lay = dict(com_layout if com_layout is not None else info["com_layout"])
|
|
414
|
+
self.com_layout = {k: (int(v[0]), int(v[1])) for k, v in lay.items()}
|
|
415
|
+
self.com_words = max(o + w for o, w in self.com_layout.values())
|
|
416
|
+
tkey = (info or {}).get("terrain") or {}
|
|
417
|
+
o, w = self.com_layout.get("objects", (0, 0))
|
|
418
|
+
from nablaengine import terrain as T
|
|
419
|
+
self.ks = w // T.OBJ_WORDS
|
|
420
|
+
self.slot_off = o
|
|
421
|
+
self.slot_vel = self.com_layout.get("object_velocity")
|
|
422
|
+
self.K = self.kb + self.ks
|
|
423
|
+
self.size_obj = None
|
|
424
|
+
self.gravity_off = self.com_layout.get("params.gravity", (None,))[0]
|
|
425
|
+
if "params.object_size" in self.com_layout:
|
|
426
|
+
if params is None:
|
|
427
|
+
from nablaengine import jax_ffi
|
|
428
|
+
params = jax_ffi._STATE.get("params")
|
|
429
|
+
if params is None:
|
|
430
|
+
raise ValueError("ObjectGeometry: the com layout has object_size words: pass the build's params=")
|
|
431
|
+
from nablaengine._optional import FOREST, load
|
|
432
|
+
object_size = load("nablaengine.forest_engine", FOREST, "object_size")
|
|
433
|
+
sg = object_size.size_geom(model, params, (info or {}).get("com_body"))
|
|
434
|
+
hit = np.nonzero(self.geoms == sg)[0]
|
|
435
|
+
self.size_obj = int(hit[0]) if len(hit) else None
|
|
436
|
+
self.size_off = self.com_layout["params.object_size"][0]
|
|
437
|
+
self.gravity0 = np.asarray(model.opt.gravity, np.float32)
|
|
438
|
+
self.floor_geom = None
|
|
439
|
+
plane = int(mujoco.mjtGeom.mjGEOM_PLANE)
|
|
440
|
+
if floor == "auto":
|
|
441
|
+
if not tkey or tkey.get("floor", False):
|
|
442
|
+
ps = [g for g in range(model.ngeom) if int(model.geom_type[g]) == plane
|
|
443
|
+
and int(model.body_weldid[model.geom_bodyid[g]]) == 0]
|
|
444
|
+
self.floor_geom = ps[0] if ps else None
|
|
445
|
+
elif floor is not None:
|
|
446
|
+
gid = (int(floor) if not isinstance(floor, str)
|
|
447
|
+
else mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_GEOM, floor))
|
|
448
|
+
if not 0 <= gid < model.ngeom or int(model.geom_type[gid]) != plane:
|
|
449
|
+
raise ValueError(f"ObjectGeometry: floor {floor!r} is not a plane geom")
|
|
450
|
+
self.floor_geom = gid
|
|
451
|
+
if self.floor_geom is not None:
|
|
452
|
+
d = mujoco.MjData(model)
|
|
453
|
+
mujoco.mj_kinematics(model, d)
|
|
454
|
+
n = d.geom_xmat[self.floor_geom].reshape(3, 3)[:, 2]
|
|
455
|
+
self.floor_normal = np.asarray(n, np.float32)
|
|
456
|
+
self.floor_height = np.float32(np.dot(d.geom_xpos[self.floor_geom], n))
|
|
457
|
+
self.faces = bool(faces)
|
|
458
|
+
if slot_faces not in ("box", "exposed", None):
|
|
459
|
+
raise ValueError(f"ObjectGeometry: slot_faces {slot_faces!r}: 'box', 'exposed' or None")
|
|
460
|
+
self.slot_faces = slot_faces if (self.faces and self.ks) else None
|
|
461
|
+
self.tol, self.max_pieces, self.ground = tol, max_pieces, ground
|
|
462
|
+
self.terrain_faces = None
|
|
463
|
+
self.tiles = None
|
|
464
|
+
self.terrain_report = None
|
|
465
|
+
if self.faces and terrain is not None and len(terrain.boxes):
|
|
466
|
+
if tiles is None:
|
|
467
|
+
sc, idx = np.asarray(terrain.boxes, np.float64)[None], np.arange(len(terrain.boxes))[None]
|
|
468
|
+
else:
|
|
469
|
+
sc, idx = tile_scenes(terrain.boxes, *tiles)
|
|
470
|
+
self.tiles = len(sc)
|
|
471
|
+
f, src, rep = face_table(sc, tol, max_pieces, ground=ground)
|
|
472
|
+
self.terrain_faces = f
|
|
473
|
+
self.terrain_src = np.where(src >= 0, np.take_along_axis(idx, np.maximum(src, 0), 1), -1)
|
|
474
|
+
self.terrain_report = rep
|
|
475
|
+
|
|
476
|
+
def exposed_slot_faces(self, slots, min_faces=1):
|
|
477
|
+
"""The exposed faces of each world's (or scene's) slot boxes, slots (S, K_slots, 15) (com's object words;
|
|
478
|
+
NumPy): (faces (S, F, 16) float32, src (S, F) int32 slot index, report) for the call's slot_faces=(faces,
|
|
479
|
+
src) (gather the rows of each world's scene). Constant per scene: compute once per scene set."""
|
|
480
|
+
return face_table(np.asarray(slots, np.float64).reshape(-1, self.ks, 15), self.tol, self.max_pieces, min_faces,
|
|
481
|
+
self.ground)
|
|
482
|
+
|
|
483
|
+
def slot_words(self, com):
|
|
484
|
+
"""The terrain slots' words (B, K_slots, 15) of com rows."""
|
|
485
|
+
return com[:, self.slot_off:self.slot_off + 15 * self.ks].reshape(com.shape[0], self.ks, 15)
|
|
486
|
+
|
|
487
|
+
def from_state(self, qpos, qvel, com, **kw):
|
|
488
|
+
"""__call__ on jax_ffi.kinematics(qpos, qvel, com) (differentiable with respect to qpos and qvel)."""
|
|
489
|
+
from nablaengine import jax_ffi
|
|
490
|
+
return self(jax_ffi.kinematics(qpos, qvel, com), com, **kw)
|
|
491
|
+
|
|
492
|
+
def __call__(self, kin, com, *, half_sizes=None, geom_offset=None, slot_faces=None, tile=None):
|
|
493
|
+
"""The geometry of B worlds (dict of arrays; module docstring) from kin = jax_ffi.kinematics' outputs (qpos_n,
|
|
494
|
+
xpos, xquat, cvel, subtree_com) and the com rows (B, com_words).
|
|
495
|
+
half_sizes: None (the model objects' geom_size, and the object_size geom's each world's from com), or (B, 3) /
|
|
496
|
+
(B, K_model, 3) in place of them (as BoxSlots.objects); geom_offset: None, or a per-world shift (B, 3) / (B,
|
|
497
|
+
K_model, 3) of the model objects' centres in their body frames. slot_faces: with
|
|
498
|
+
ObjectGeometry(slot_faces="exposed"), (faces (B, F_s, 16), src (B, F_s)) each world's rows of
|
|
499
|
+
exposed_slot_faces. tile: (B,) int, each world's tile with ObjectGeometry(tiles=...)."""
|
|
500
|
+
import jax.numpy as jnp
|
|
501
|
+
_, xpos, xquat, cvel, subtree_com = kin
|
|
502
|
+
B = xpos.shape[0]
|
|
503
|
+
f32 = jnp.float32
|
|
504
|
+
out = {}
|
|
505
|
+
if self.gravity_off is not None:
|
|
506
|
+
g = com[:, self.gravity_off:self.gravity_off + 3].astype(f32)
|
|
507
|
+
else:
|
|
508
|
+
g = jnp.broadcast_to(jnp.asarray(self.gravity0), (B, 3))
|
|
509
|
+
up = up_vector(g)
|
|
510
|
+
out["gravity"], out["up"] = g, up
|
|
511
|
+
if self.floor_geom is not None:
|
|
512
|
+
out["floor_valid"] = jnp.ones((B,), bool)
|
|
513
|
+
out["floor_height"] = jnp.full((B,), self.floor_height, f32)
|
|
514
|
+
out["floor_normal"] = jnp.broadcast_to(jnp.asarray(self.floor_normal), (B, 3))
|
|
515
|
+
else:
|
|
516
|
+
out["floor_valid"] = jnp.zeros((B,), bool)
|
|
517
|
+
out["floor_height"] = jnp.zeros((B,), f32)
|
|
518
|
+
out["floor_normal"] = jnp.zeros((B, 3), f32)
|
|
519
|
+
pos, rot, half, vel, ang, valid = [], [], [], [], [], []
|
|
520
|
+
if self.kb:
|
|
521
|
+
p, R = geom_world_pose(xpos, xquat, self.body, self.pos, self.rot, geom_offset)
|
|
522
|
+
if half_sizes is None:
|
|
523
|
+
hs = jnp.broadcast_to(jnp.asarray(self.size), (B, self.kb, 3))
|
|
524
|
+
if self.size_obj is not None:
|
|
525
|
+
hs = hs.at[:, self.size_obj].set(com[:, self.size_off:self.size_off + 3].astype(f32))
|
|
526
|
+
else:
|
|
527
|
+
hs = jnp.broadcast_to(jnp.asarray(half_sizes, f32).reshape(B, -1, 3), (B, self.kb, 3))
|
|
528
|
+
cv = cvel[:, self.body]
|
|
529
|
+
w = cv[..., :3]
|
|
530
|
+
v = cv[..., 3:] + _cross(w, p - subtree_com[:, self.root])
|
|
531
|
+
pos.append(p), rot.append(R), half.append(hs), vel.append(v), ang.append(w)
|
|
532
|
+
valid.append(jnp.ones((B, self.kb), bool))
|
|
533
|
+
if self.ks:
|
|
534
|
+
sw = self.slot_words(com).astype(f32)
|
|
535
|
+
pos.append(sw[..., :3]), rot.append(sw[..., 3:12].reshape(B, self.ks, 3, 3)), half.append(sw[..., 12:15])
|
|
536
|
+
if self.slot_vel is not None:
|
|
537
|
+
mv = com[:, self.slot_vel[0]:self.slot_vel[0] + self.slot_vel[1]].astype(f32).reshape(B, self.ks, -1)
|
|
538
|
+
vel.append(mv[..., 0:3]), ang.append(mv[..., 3:6])
|
|
539
|
+
else:
|
|
540
|
+
vel.append(jnp.zeros((B, self.ks, 3), f32)), ang.append(jnp.zeros((B, self.ks, 3), f32))
|
|
541
|
+
valid.append(sw[..., 14] > 0)
|
|
542
|
+
cat = lambda xs, shape: jnp.concatenate(xs, 1) if xs else jnp.zeros((B, 0) + shape, f32)
|
|
543
|
+
out["obj_pos"], out["obj_rot"], out["obj_half"] = cat(pos, (3,)), cat(rot, (3, 3)), cat(half, (3,))
|
|
544
|
+
out["obj_vel"], out["obj_angvel"] = cat(vel, (3,)), cat(ang, (3,))
|
|
545
|
+
out["obj_valid"] = jnp.concatenate(valid, 1) if valid else jnp.zeros((B, 0), bool)
|
|
546
|
+
kind = [KIND_BODY if m else KIND_STATIC for m in self.movable_body] + [KIND_SLOT] * self.ks
|
|
547
|
+
out["obj_kind"] = jnp.asarray(np.asarray(kind, np.int32).reshape(-1))
|
|
548
|
+
out["obj_movable"] = jnp.asarray(np.asarray(list(self.movable_body) + [False] * self.ks, bool).reshape(-1))
|
|
549
|
+
if not self.faces:
|
|
550
|
+
return out
|
|
551
|
+
fs, fo, fm = [], [], []
|
|
552
|
+
if self.kb:
|
|
553
|
+
fs.append(box_face_records(pos[0], rot[0], half[0]).reshape(B, 6 * self.kb, FACE_WORDS))
|
|
554
|
+
fo.append(jnp.broadcast_to(jnp.repeat(jnp.arange(self.kb, dtype=jnp.int32), 6), (B, 6 * self.kb)))
|
|
555
|
+
fm.append(jnp.broadcast_to(jnp.asarray(np.repeat(self.movable_body, 6)), (B, 6 * self.kb)))
|
|
556
|
+
if self.slot_faces == "box":
|
|
557
|
+
sv = valid[-1]
|
|
558
|
+
fs.append(box_face_records(pos[-1], rot[-1], half[-1], sv).reshape(B, 6 * self.ks, FACE_WORDS))
|
|
559
|
+
ids = jnp.repeat(jnp.arange(self.kb, self.K, dtype=jnp.int32), 6)
|
|
560
|
+
fo.append(jnp.where(jnp.repeat(sv, 6, 1), ids, -1))
|
|
561
|
+
fm.append(jnp.zeros((B, 6 * self.ks), bool))
|
|
562
|
+
elif self.slot_faces == "exposed":
|
|
563
|
+
if slot_faces is None:
|
|
564
|
+
raise ValueError("ObjectGeometry(slot_faces='exposed'): pass slot_faces=(faces, src) per world "
|
|
565
|
+
"(exposed_slot_faces)")
|
|
566
|
+
sf, ss = slot_faces
|
|
567
|
+
sf = jnp.asarray(sf, f32).reshape(B, -1, FACE_WORDS)
|
|
568
|
+
ss = jnp.asarray(ss, jnp.int32).reshape(B, -1)
|
|
569
|
+
fs.append(sf)
|
|
570
|
+
fo.append(jnp.where(ss >= 0, ss + self.kb, -1))
|
|
571
|
+
fm.append(jnp.zeros(ss.shape, bool))
|
|
572
|
+
tb = None
|
|
573
|
+
if self.terrain_faces is not None:
|
|
574
|
+
if self.tiles is None:
|
|
575
|
+
tf = jnp.broadcast_to(jnp.asarray(self.terrain_faces[0]), (B,) + self.terrain_faces.shape[1:])
|
|
576
|
+
tsrc = jnp.broadcast_to(jnp.asarray(self.terrain_src[0], jnp.int32), (B, self.terrain_faces.shape[1]))
|
|
577
|
+
else:
|
|
578
|
+
if tile is None:
|
|
579
|
+
raise ValueError("ObjectGeometry(tiles=...): pass tile=(B,) each world's tile index")
|
|
580
|
+
t = jnp.asarray(tile, jnp.int32).reshape(B)
|
|
581
|
+
tf = jnp.take(jnp.asarray(self.terrain_faces), t, axis=0)
|
|
582
|
+
tsrc = jnp.take(jnp.asarray(self.terrain_src, jnp.int32), t, axis=0)
|
|
583
|
+
fs.append(tf)
|
|
584
|
+
fo.append(jnp.where(tsrc >= 0, SRC_TERRAIN, -1).astype(jnp.int32))
|
|
585
|
+
fm.append(jnp.zeros(tsrc.shape, bool))
|
|
586
|
+
nb = sum(x.shape[1] for x in fs[:-1])
|
|
587
|
+
tb = jnp.concatenate([jnp.full((B, nb), -1, jnp.int32), tsrc.astype(jnp.int32)], 1)
|
|
588
|
+
if fs:
|
|
589
|
+
faces = classify_faces(jnp.concatenate(fs, 1), up)
|
|
590
|
+
out["faces"] = faces
|
|
591
|
+
out["face_valid"] = faces[..., 15] > 0
|
|
592
|
+
out["face_object"] = jnp.concatenate(fo, 1).astype(jnp.int32)
|
|
593
|
+
out["face_movable"] = jnp.concatenate(fm, 1)
|
|
594
|
+
out["face_class"] = faces[..., 14].astype(jnp.int32)
|
|
595
|
+
else:
|
|
596
|
+
out["faces"] = jnp.zeros((B, 0, FACE_WORDS), f32)
|
|
597
|
+
out["face_valid"] = jnp.zeros((B, 0), bool)
|
|
598
|
+
out["face_object"] = jnp.zeros((B, 0), jnp.int32)
|
|
599
|
+
out["face_movable"] = jnp.zeros((B, 0), bool)
|
|
600
|
+
out["face_class"] = jnp.zeros((B, 0), jnp.int32)
|
|
601
|
+
if tb is not None:
|
|
602
|
+
out["terrain_box"] = tb
|
|
603
|
+
return out
|
|
604
|
+
|
|
605
|
+
def box_slots(self, g):
|
|
606
|
+
"""G1Sensors object slots (B, K, 15) (pos, rotation row major, half sizes) of a call's output g."""
|
|
607
|
+
import jax.numpy as jnp
|
|
608
|
+
B, K = g["obj_pos"].shape[:2]
|
|
609
|
+
return jnp.concatenate([g["obj_pos"], g["obj_rot"].reshape(B, K, 9), g["obj_half"]], -1).astype(jnp.float32)
|