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.
Files changed (136) hide show
  1. nablaengine/__init__.py +4 -0
  2. nablaengine/_fixtures/README.md +19 -0
  3. nablaengine/_fixtures/data/mf_s0.npz +0 -0
  4. nablaengine/_fixtures/mjlab/LICENSE +27 -0
  5. nablaengine/_fixtures/mjlab/README.md +113 -0
  6. nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
  7. nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
  8. nablaengine/_optional.py +30 -0
  9. nablaengine/_paths.py +38 -0
  10. nablaengine/actuators/__init__.py +169 -0
  11. nablaengine/actuators/bam.py +306 -0
  12. nablaengine/actuators/bam_params/LICENSE +202 -0
  13. nablaengine/actuators/bam_params/xl330/m6.json +19 -0
  14. nablaengine/boxbox.py +259 -0
  15. nablaengine/ccd.py +1122 -0
  16. nablaengine/checks.py +376 -0
  17. nablaengine/cuda.py +483 -0
  18. nablaengine/dist_query.py +628 -0
  19. nablaengine/dual.py +223 -0
  20. nablaengine/dyn_query.py +685 -0
  21. nablaengine/engines.py +114 -0
  22. nablaengine/envs/__init__.py +24 -0
  23. nablaengine/envs/brax.py +165 -0
  24. nablaengine/envs/convert.py +771 -0
  25. nablaengine/envs/dmc.py +523 -0
  26. nablaengine/envs/env.py +233 -0
  27. nablaengine/envs/kin.py +371 -0
  28. nablaengine/envs/ops.py +134 -0
  29. nablaengine/envs/rewards.py +57 -0
  30. nablaengine/fixtures.py +243 -0
  31. nablaengine/forest_engine/__init__.py +0 -0
  32. nablaengine/forest_engine/adjoint.py +1726 -0
  33. nablaengine/forest_engine/adjoint_contact.py +493 -0
  34. nablaengine/forest_engine/bam_hooks.py +248 -0
  35. nablaengine/forest_engine/body_params.py +1007 -0
  36. nablaengine/forest_engine/capacity_diag.py +116 -0
  37. nablaengine/forest_engine/ccd_coop.py +250 -0
  38. nablaengine/forest_engine/chol_blk.py +80 -0
  39. nablaengine/forest_engine/contact_forces.py +142 -0
  40. nablaengine/forest_engine/contact_vjp.py +462 -0
  41. nablaengine/forest_engine/convex.py +1331 -0
  42. nablaengine/forest_engine/cylinder.py +73 -0
  43. nablaengine/forest_engine/dist_device.py +923 -0
  44. nablaengine/forest_engine/dyn_device.py +696 -0
  45. nablaengine/forest_engine/ellipsoid.py +179 -0
  46. nablaengine/forest_engine/elliptic.py +272 -0
  47. nablaengine/forest_engine/equality.py +842 -0
  48. nablaengine/forest_engine/floss.py +148 -0
  49. nablaengine/forest_engine/foot_offset.py +368 -0
  50. nablaengine/forest_engine/free_gyro.py +288 -0
  51. nablaengine/forest_engine/host.py +530 -0
  52. nablaengine/forest_engine/kdof64.py +127 -0
  53. nablaengine/forest_engine/kinematics.py +320 -0
  54. nablaengine/forest_engine/margin.py +167 -0
  55. nablaengine/forest_engine/margin_convex.py +326 -0
  56. nablaengine/forest_engine/midphase.py +439 -0
  57. nablaengine/forest_engine/model_hooks.py +913 -0
  58. nablaengine/forest_engine/motor_hooks.py +50 -0
  59. nablaengine/forest_engine/muscle.py +485 -0
  60. nablaengine/forest_engine/nb128.py +118 -0
  61. nablaengine/forest_engine/nb64.py +163 -0
  62. nablaengine/forest_engine/noslip.py +1124 -0
  63. nablaengine/forest_engine/nv128.py +1944 -0
  64. nablaengine/forest_engine/object_size.py +283 -0
  65. nablaengine/forest_engine/replay_guard.py +40 -0
  66. nablaengine/forest_engine/root_spread.py +126 -0
  67. nablaengine/forest_engine/solref.py +74 -0
  68. nablaengine/forest_engine/source.py +1464 -0
  69. nablaengine/forest_engine/sparse_pattern.py +527 -0
  70. nablaengine/forest_engine/spatial.py +1045 -0
  71. nablaengine/forest_engine/step.py +3083 -0
  72. nablaengine/forest_engine/surrogate.py +498 -0
  73. nablaengine/forest_engine/tape.py +199 -0
  74. nablaengine/forest_engine/tendon.py +845 -0
  75. nablaengine/forest_engine/terrain.py +1059 -0
  76. nablaengine/forest_engine/world_forces.py +166 -0
  77. nablaengine/forest_engine/world_params.py +230 -0
  78. nablaengine/g1_engine/__init__.py +0 -0
  79. nablaengine/g1_engine/adjoint.py +1661 -0
  80. nablaengine/g1_engine/adjoint_contact.py +577 -0
  81. nablaengine/g1_engine/bam_hooks.py +596 -0
  82. nablaengine/g1_engine/condim4.py +245 -0
  83. nablaengine/g1_engine/contact_forces.py +500 -0
  84. nablaengine/g1_engine/cylccd.py +1158 -0
  85. nablaengine/g1_engine/cylinder.py +216 -0
  86. nablaengine/g1_engine/elliptic.py +565 -0
  87. nablaengine/g1_engine/exact_replay.py +61 -0
  88. nablaengine/g1_engine/host.py +358 -0
  89. nablaengine/g1_engine/kinematics.py +320 -0
  90. nablaengine/g1_engine/mesh.py +305 -0
  91. nablaengine/g1_engine/mesh_tables.py +79 -0
  92. nablaengine/g1_engine/model_hooks.py +919 -0
  93. nablaengine/g1_engine/motor_hooks.py +70 -0
  94. nablaengine/g1_engine/replay_guard.py +55 -0
  95. nablaengine/g1_engine/source.py +1107 -0
  96. nablaengine/g1_engine/sphbox.py +93 -0
  97. nablaengine/g1_engine/step.py +3716 -0
  98. nablaengine/g1_engine/tape.py +173 -0
  99. nablaengine/g1_engine/world_params.py +447 -0
  100. nablaengine/identity.py +401 -0
  101. nablaengine/jax_ffi.py +2536 -0
  102. nablaengine/model/__init__.py +1 -0
  103. nablaengine/model/capability.py +694 -0
  104. nablaengine/model/fields.py +317 -0
  105. nablaengine/model/gravcomp.py +64 -0
  106. nablaengine/model/invweight.py +145 -0
  107. nablaengine/motor.py +143 -0
  108. nablaengine/object_geometry.py +609 -0
  109. nablaengine/params.py +258 -0
  110. nablaengine/provenance.py +196 -0
  111. nablaengine/reference/__init__.py +0 -0
  112. nablaengine/reference/adjoint_groups.py +226 -0
  113. nablaengine/reference/jax64.py +690 -0
  114. nablaengine/reference/warp_physics.py +262 -0
  115. nablaengine/sensors/__init__.py +4 -0
  116. nablaengine/sensors/cameras.py +285 -0
  117. nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
  118. nablaengine/sensors/data/livox_mid360.npz +0 -0
  119. nablaengine/sensors/g1.py +521 -0
  120. nablaengine/sensors/jax_rays.py +364 -0
  121. nablaengine/sensors/optix_rays.py +725 -0
  122. nablaengine/sensors/raycore.py +630 -0
  123. nablaengine/sensors/raygrad.py +374 -0
  124. nablaengine/sensors/raygrad_cuda.py +191 -0
  125. nablaengine/sensors/robot_mesh.py +273 -0
  126. nablaengine/sensors/torch_rays.py +275 -0
  127. nablaengine/terrain.py +424 -0
  128. nablaengine/torch_ffi.py +1328 -0
  129. nablaengine/workdir.py +37 -0
  130. nablaengine-1.0.2.dist-info/METADATA +236 -0
  131. nablaengine-1.0.2.dist-info/RECORD +136 -0
  132. nablaengine-1.0.2.dist-info/WHEEL +5 -0
  133. nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
  134. nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
  135. nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
  136. nablaengine-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1045 @@
1
+ # The tendon path code here (sp_wrap_circle, sp_wrap_inside, sp_wrap_local, the segment rules of sp_compute) follows
2
+ # MuJoCo Warp's util_misc.wrap / wrap_circle / wrap_inside and smooth._spatial_site_tendon / _spatial_geom_tendon
3
+ # (mujoco_warp 3.17, Copyright 2025 The Newton Developers, Apache License 2.0), which mirror MuJoCo's mju_wrap /
4
+ # mju_wrapCircle / mju_wrapInside and mj_tendon; the templated form, the explicit roundings and the derivatives are this
5
+ # engine's.
6
+ """Spatial tendons in the forest engine (with forest_engine.tendon): length and Jacobian of site paths with pulleys and
7
+ sphere / cylinder wrapping (side sites, inside side sites), forward and adjoint."""
8
+ import mujoco
9
+ import numpy as np
10
+
11
+ W = mujoco.mjtWrap
12
+ KIND_SITE, KIND_SPHERE, KIND_CYL = 0, 1, 2
13
+ MAX_KTEN = 32
14
+
15
+
16
+ MAX_TS_WORDS = 6144
17
+
18
+
19
+ def storage_words(m, ts, kten, nact):
20
+ """TS_WORDS of a spatial build (ts the used tendons) with J in KTEN-strided rows."""
21
+ return len(ts) + len(ts) * kten + 2 * nact
22
+
23
+
24
+ def _sizes(m):
25
+ from nablaengine.forest_engine import muscle
26
+ from nablaengine.forest_engine import tendon as TEN
27
+ ts = TEN.used(m)
28
+ return ts, [len(TEN.support_list(m, t)) for t in ts], len(TEN.actuators(m)), muscle.act_words(m)
29
+
30
+
31
+ def compact_on(m):
32
+ """The packed layout (compact()): a spatial build whose KTEN-strided storage exceeds MAX_TS_WORDS."""
33
+ from nablaengine.forest_engine import tendon as TEN
34
+ if not TEN.spatial_build(m):
35
+ return False
36
+ ts, sup, nact, na = _sizes(m)
37
+ return storage_words(m, ts, max(sup), nact) + na > MAX_TS_WORDS
38
+
39
+
40
+ def words(m):
41
+ """TS_WORDS of a spatial build (the activation words included): KTEN-strided J rows, or the packed layout's (each
42
+ tendon's J over its own support) when the strided one exceeds MAX_TS_WORDS."""
43
+ ts, sup, nact, na = _sizes(m)
44
+ if compact_on(m):
45
+ return len(ts) + max(sum(sup), 1) + 2 * nact + na
46
+ return storage_words(m, ts, max(sup), nact) + na
47
+
48
+
49
+ def is_spatial(m, t):
50
+ if t >= m.ntendon:
51
+ return False
52
+ adr, n = int(m.tendon_adr[t]), int(m.tendon_num[t])
53
+ return any(int(m.wrap_type[w]) != int(W.mjWRAP_JOINT) for w in range(adr, adr + n))
54
+
55
+
56
+ def path(m, t):
57
+ """The segments of spatial tendon t: [dict(kind, s0, s1, g (-1), side (-1), scale)] in path order (MuJoCo's rules:
58
+ a pulley sets the scale of what follows and breaks the path; site-site is straight; site-geom-site may wrap).
59
+ Raises ValueError for a path MuJoCo would not compile (kept as a guard)."""
60
+ adr, n = int(m.tendon_adr[t]), int(m.tendon_num[t])
61
+ typ = [int(m.wrap_type[w]) for w in range(adr, adr + n)]
62
+ obj = [int(m.wrap_objid[w]) for w in range(adr, adr + n)]
63
+ prm = [float(m.wrap_prm[w]) for w in range(adr, adr + n)]
64
+ out, scale, j = [], 1.0, 0
65
+ while j < n - 1:
66
+ t0, t1 = typ[j], typ[j + 1]
67
+ if t0 == int(W.mjWRAP_PULLEY):
68
+ scale = 1.0 / prm[j]
69
+ j += 1
70
+ continue
71
+ if t1 == int(W.mjWRAP_PULLEY):
72
+ j += 1
73
+ continue
74
+ if t0 != int(W.mjWRAP_SITE):
75
+ raise ValueError(f"tendon {t}: wrap element {j} of type {t0} where a site is expected")
76
+ if t1 == int(W.mjWRAP_SITE):
77
+ out.append(dict(kind=KIND_SITE, s0=obj[j], s1=obj[j + 1], g=-1, side=-1, scale=scale))
78
+ j += 1
79
+ continue
80
+ if t1 in (int(W.mjWRAP_SPHERE), int(W.mjWRAP_CYLINDER)):
81
+ if j + 2 >= n or typ[j + 2] != int(W.mjWRAP_SITE):
82
+ raise ValueError(f"tendon {t}: a wrap geom not followed by a site")
83
+ g = obj[j + 1]
84
+ gt = int(m.geom_type[g])
85
+ kind = KIND_SPHERE if gt == int(mujoco.mjtGeom.mjGEOM_SPHERE) else (
86
+ KIND_CYL if gt == int(mujoco.mjtGeom.mjGEOM_CYLINDER) else -1)
87
+ if kind < 0:
88
+ raise ValueError(f"tendon {t}: wrap geom {g} is neither a sphere nor a cylinder")
89
+ out.append(dict(kind=kind, s0=obj[j], s1=obj[j + 2], g=g, side=int(round(prm[j + 1])), scale=scale))
90
+ j += 2
91
+ continue
92
+ raise ValueError(f"tendon {t}: wrap element {j + 1} of type {t1}")
93
+ return out
94
+
95
+
96
+ def bodies(m, t):
97
+ """The bodies spatial tendon t's path touches (its sites' and wrap geoms' bodies; side sites only decide)."""
98
+ bs = set()
99
+ for s in path(m, t):
100
+ bs |= {int(m.site_bodyid[s["s0"]]), int(m.site_bodyid[s["s1"]])}
101
+ if s["g"] >= 0:
102
+ bs.add(int(m.geom_bodyid[s["g"]]))
103
+ return bs
104
+
105
+
106
+ def _chain(m, b):
107
+ out = []
108
+ while b > 0:
109
+ out += range(int(m.body_dofadr[b]), int(m.body_dofadr[b]) + int(m.body_dofnum[b]))
110
+ b = int(m.body_parentid[b])
111
+ return out
112
+
113
+
114
+ def support(m, t):
115
+ """The dofs J of spatial tendon t can be nonzero on, ascending: the chains of the bodies its path touches minus the
116
+ chain they all share."""
117
+ chains = [set(_chain(m, b)) for b in bodies(m, t)]
118
+ if not chains:
119
+ return []
120
+ return sorted(set.union(*chains) - set.intersection(*chains))
121
+
122
+
123
+ def check_tendon(m, t):
124
+ """[reason] spatial tendon t is not supported (empty: supported); the reasons start with "spatial tendon"."""
125
+ try:
126
+ p = path(m, t)
127
+ except ValueError as e:
128
+ return [f"spatial tendon: {e}"]
129
+ why = []
130
+ if not p:
131
+ why.append("spatial tendon: an empty path")
132
+ if len(support(m, t)) > MAX_KTEN:
133
+ why.append(f"spatial tendon: Jacobian support of {len(support(m, t))} dofs (at most {MAX_KTEN})")
134
+ for b in bodies(m, t):
135
+ if b > 0 and int(m.body_jntnum[b]) != 1:
136
+ why.append("spatial tendon: a path body without exactly one joint")
137
+ break
138
+ if m.tendon_armature[t] > 0:
139
+ why.append("spatial tendon: armature (not supported on spatial tendons)")
140
+ return why
141
+
142
+
143
+ def _f32(x):
144
+ return f"{float(np.float32(x))!r}f"
145
+
146
+
147
+ def tables(m, ts, kten, acts):
148
+ """The spatial tables' text: ts the used tendons (forest_engine.tendon.used, the table order), kten = KTEN, acts:
149
+ the tendon actuators [(actuator, tendon)]."""
150
+ tix = {t: k for k, t in enumerate(ts)}
151
+ sites, geoms, segs, sg0, sgn = [], [], [], [], []
152
+ for t in ts:
153
+ sg0.append(len(segs))
154
+ if not is_spatial(m, t):
155
+ sgn.append(0)
156
+ continue
157
+ p = path(m, t)
158
+ sgn.append(len(p))
159
+ for s in p:
160
+ for key in ("s0", "s1"):
161
+ if s[key] not in sites:
162
+ sites.append(s[key])
163
+ if s["side"] >= 0 and s["side"] not in sites:
164
+ sites.append(s["side"])
165
+ if s["g"] >= 0 and s["g"] not in geoms:
166
+ geoms.append(s["g"])
167
+ segs.append(s)
168
+ n1 = lambda n: max(n, 1)
169
+ I = lambda xs: ", ".join(str(int(x)) for x in xs) or "0"
170
+ F = lambda xs: ", ".join(_f32(x) for x in xs) or "0.f"
171
+ tab = lambda typ, nm, n, vals, note="": (f"__device__ const {typ} {nm}[{n}] = {{{vals}}};"
172
+ + (f" // {note}" if note else "") + "\n")
173
+ tpos = []
174
+ from nablaengine.forest_engine import tendon as TEN
175
+ for t in ts:
176
+ sup = [d for d, _ in TEN.support_list(m, t)]
177
+ row = [-1] * m.nv
178
+ for k, d in enumerate(sup):
179
+ row[d] = k
180
+ tpos += row
181
+ nsp = sum(1 for t in ts if is_spatial(m, t))
182
+ return (f"#define NTS_SPATIAL {nsp} // spatial tendons among the NTEN (forest_engine.spatial)\n"
183
+ f"#define NSPSEG {len(segs)} // their path segments\n"
184
+ f"#define TS_WORDS (NTEN + NTEN * KTEN + 2 * NTACT) // per-world storage: L, J (KTEN per tendon), actuator "
185
+ "force and flags\n"
186
+ + tab("int", "c_tsg0", len(ts), I(sg0), "tendon: its first segment")
187
+ + tab("int", "c_tsgn", len(ts), I(sgn), "its number of segments (0: a fixed tendon)")
188
+ + tab("signed char", "c_tpos", len(ts) * m.nv, I(tpos), "dof -> its support entry (-1: none)")
189
+ + tab("int", "c_sgk", n1(len(segs)), I(s["kind"] for s in segs), "segment: 0 site-site, 1 sphere, 2 cylinder")
190
+ + tab("int", "c_sgs0", n1(len(segs)), I(sites.index(s["s0"]) for s in segs), "its first site")
191
+ + tab("int", "c_sgs1", n1(len(segs)), I(sites.index(s["s1"]) for s in segs), "its last site")
192
+ + tab("int", "c_sgg", n1(len(segs)), I(geoms.index(s["g"]) if s["g"] >= 0 else -1 for s in segs),
193
+ "its wrap geom (-1: none)")
194
+ + tab("int", "c_sgsd", n1(len(segs)), I(sites.index(s["side"]) if s["side"] >= 0 else -1 for s in segs),
195
+ "its side site (-1: none)")
196
+ + tab("float", "c_sgsc", n1(len(segs)), F(s["scale"] for s in segs), "its scale (1 / the pulley divisor)")
197
+ + tab("int", "c_stb", n1(len(sites)), I(m.site_bodyid[s] for s in sites), "site: body")
198
+ + tab("float", "c_stp", 3 * n1(len(sites)), F(x for s in sites for x in m.site_pos[s]),
199
+ "its position in the body frame")
200
+ + tab("int", "c_wgb", n1(len(geoms)), I(m.geom_bodyid[g] for g in geoms), "wrap geom: body")
201
+ + tab("float", "c_wgp", 3 * n1(len(geoms)), F(x for g in geoms for x in m.geom_pos[g]), "its position")
202
+ + tab("float", "c_wgq", 4 * n1(len(geoms)), F(x for g in geoms for x in m.geom_quat[g]), "its quaternion")
203
+ + tab("float", "c_wgr", n1(len(geoms)), F(m.geom_size[g, 0] for g in geoms), "its radius")
204
+ + tab("int", "c_tatix", n1(len(acts)), I(tix[t] for _, t in acts), "tendon actuator: its tendon (table)"))
205
+
206
+
207
+ DEVICE = r"""
208
+ // ---------------------------------------------------------------- spatial tendons (forest_engine.spatial)
209
+ #if DK_PRE2W
210
+ #error "spatial tendons: not with DK_PRE2W (the latency mode)"
211
+ #endif
212
+ #define SP_MINVAL 1e-15f
213
+ // the per-world storage (sp_compute): L[NTEN], J[NTEN][KTEN] (over the tendon's support), the tendon actuators'
214
+ // force[NTACT] and flags[NTACT] (bit 0 force at its forcerange, bit 1 ctrl at its ctrlrange); dk_tsp points at it
215
+ // (lane 0 sets it at the start of substep_pre, substep_post and adj_substep)
216
+ __shared__ float* dk_tsp;
217
+ #define TS_L(t) (dk_tsp[(t)])
218
+ #define TS_J(t) (dk_tsp + NTEN + KTEN * (t))
219
+ #define TS_F(k) (dk_tsp[NTEN + NTEN * KTEN + (k)])
220
+ #define TS_FL(k) (__float_as_int(dk_tsp[NTEN + NTEN * KTEN + NTACT + (k)]))
221
+ __device__ __forceinline__ float ts_cd(int t, int i) { // J of tendon t at dof i (0 off its support)
222
+ const int k = c_tpos[NV * t + i];
223
+ return k >= 0 ? TS_J(t)[k] : 0.f;
224
+ }
225
+ // the storage of a state: right after the connect rows' J (forest_engine.equality ec_J)
226
+ template <class S>
227
+ __device__ __forceinline__ float* ts_base(const S& s) {
228
+ return (float*)(s.con_J + MAXCON) + (NEQC > 0 ? NEQC : 1) * 3 * KEQC;
229
+ }
230
+
231
+ // SpR: a float whose operations are never contracted (explicit roundings: the same bits in every kernel and unit)
232
+ struct SpR {
233
+ float v;
234
+ __device__ __forceinline__ SpR(float x = 0.f) : v(x) {}
235
+ };
236
+ __device__ __forceinline__ SpR operator+(SpR a, SpR b) { return SpR(__fadd_rn(a.v, b.v)); }
237
+ __device__ __forceinline__ SpR operator-(SpR a, SpR b) { return SpR(__fsub_rn(a.v, b.v)); }
238
+ __device__ __forceinline__ SpR operator*(SpR a, SpR b) { return SpR(__fmul_rn(a.v, b.v)); }
239
+ __device__ __forceinline__ SpR operator/(SpR a, SpR b) { return SpR(__fdiv_rn(a.v, b.v)); }
240
+ __device__ __forceinline__ SpR operator-(SpR a) { return SpR(-a.v); }
241
+ __device__ __forceinline__ float spv(SpR a) { return a.v; }
242
+ __device__ __forceinline__ SpR sp_sqrt(SpR a) { return SpR(__fsqrt_rn(a.v)); }
243
+ __device__ __forceinline__ SpR sp_atan2(SpR y, SpR x) { return SpR(atan2f(y.v, x.v)); }
244
+ __device__ __forceinline__ SpR sp_acos(SpR a) { return SpR(acosf(a.v)); }
245
+ __device__ __forceinline__ SpR sp_asin(SpR a) { return SpR(asinf(a.v)); }
246
+ __device__ __forceinline__ SpR sp_sin(SpR a) { return SpR(sinf(a.v)); }
247
+ __device__ __forceinline__ SpR sp_cos(SpR a) { return SpR(cosf(a.v)); }
248
+ __device__ __forceinline__ SpR sp_abs(SpR a) { return SpR(fabsf(a.v)); }
249
+ // SpD: the same value arithmetic with six partials (forward mode)
250
+ struct SpD {
251
+ float v, d[6];
252
+ __device__ __forceinline__ SpD(float x = 0.f) : v(x) {
253
+ for (int k = 0; k < 6; k++) d[k] = 0.f;
254
+ }
255
+ };
256
+ __device__ __forceinline__ SpD operator+(SpD a, SpD b) {
257
+ SpD r(__fadd_rn(a.v, b.v));
258
+ for (int k = 0; k < 6; k++) r.d[k] = a.d[k] + b.d[k];
259
+ return r;
260
+ }
261
+ __device__ __forceinline__ SpD operator-(SpD a, SpD b) {
262
+ SpD r(__fsub_rn(a.v, b.v));
263
+ for (int k = 0; k < 6; k++) r.d[k] = a.d[k] - b.d[k];
264
+ return r;
265
+ }
266
+ __device__ __forceinline__ SpD operator*(SpD a, SpD b) {
267
+ SpD r(__fmul_rn(a.v, b.v));
268
+ for (int k = 0; k < 6; k++) r.d[k] = a.d[k] * b.v + a.v * b.d[k];
269
+ return r;
270
+ }
271
+ __device__ __forceinline__ SpD operator/(SpD a, SpD b) {
272
+ SpD r(__fdiv_rn(a.v, b.v));
273
+ for (int k = 0; k < 6; k++) r.d[k] = (a.d[k] - r.v * b.d[k]) / b.v;
274
+ return r;
275
+ }
276
+ __device__ __forceinline__ SpD operator-(SpD a) {
277
+ SpD r(-a.v);
278
+ for (int k = 0; k < 6; k++) r.d[k] = -a.d[k];
279
+ return r;
280
+ }
281
+ __device__ __forceinline__ float spv(SpD a) { return a.v; }
282
+ __device__ __forceinline__ SpD sp_chain(float v, const SpD& a, float g) { // f(a) with f(a.v) = v, f'(a.v) = g
283
+ SpD r(v);
284
+ for (int k = 0; k < 6; k++) r.d[k] = g * a.d[k];
285
+ return r;
286
+ }
287
+ __device__ __forceinline__ SpD sp_sqrt(SpD a) {
288
+ const float v = __fsqrt_rn(a.v);
289
+ return sp_chain(v, a, v > 0.f ? 0.5f / v : 0.f);
290
+ }
291
+ __device__ __forceinline__ SpD sp_atan2(SpD y, SpD x) {
292
+ SpD r(atan2f(y.v, x.v));
293
+ const float n = x.v * x.v + y.v * y.v;
294
+ if (n > 0.f)
295
+ for (int k = 0; k < 6; k++) r.d[k] = (x.v * y.d[k] - y.v * x.d[k]) / n;
296
+ return r;
297
+ }
298
+ __device__ __forceinline__ SpD sp_acos(SpD a) {
299
+ const float s = 1.f - a.v * a.v;
300
+ return sp_chain(acosf(a.v), a, s > 0.f ? -rsqrtf(s) : 0.f);
301
+ }
302
+ __device__ __forceinline__ SpD sp_asin(SpD a) {
303
+ const float s = 1.f - a.v * a.v;
304
+ return sp_chain(asinf(a.v), a, s > 0.f ? rsqrtf(s) : 0.f);
305
+ }
306
+ __device__ __forceinline__ SpD sp_sin(SpD a) { return sp_chain(sinf(a.v), a, cosf(a.v)); }
307
+ __device__ __forceinline__ SpD sp_cos(SpD a) { return sp_chain(cosf(a.v), a, -sinf(a.v)); }
308
+ __device__ __forceinline__ SpD sp_abs(SpD a) { return a.v < 0.f ? -a : a; }
309
+
310
+ template <class T> __device__ __forceinline__ T sp_sdiv(T x, T y) { return x / (spv(y) != 0.f ? y : T(SP_MINVAL)); }
311
+ template <class T> __device__ __forceinline__ T sp_nrm2(T x, T y) { return sp_sqrt(x * x + y * y); }
312
+ template <class T> __device__ __forceinline__ T sp_nrm3(const T* a) { return sp_sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); }
313
+
314
+ // 2D segment intersection (util_misc.is_intersect), on the values
315
+ __device__ __forceinline__ bool sp_intersect(SpR p1x, SpR p1y, SpR p2x, SpR p2y, SpR p3x, SpR p3y, SpR p4x, SpR p4y) {
316
+ const SpR ux = p2x - p1x, uy = p2y - p1y, vx = p4x - p3x, vy = p4y - p3y;
317
+ const SpR det = vy * ux - vx * uy;
318
+ if (fabsf(det.v) < SP_MINVAL) return false;
319
+ const SpR s = SpR(det.v > 0.f ? 1.f : -1.f);
320
+ const SpR wx = p1x - p3x, wy = p1y - p3y, dx = p2x - p4x, dy = p2y - p4y;
321
+ const SpR a0 = (vx * wy - vy * wx) * s, a1 = (vx * dy - vy * dx) * s;
322
+ const SpR b0 = (ux * wy - uy * wx) * s, b1 = (ux * dy - uy * dx) * s;
323
+ return a0.v >= 0.f && a1.v <= 0.f && b0.v >= 0.f && b1.v <= 0.f;
324
+ }
325
+
326
+ // util_misc.length_circle
327
+ template <class T>
328
+ __device__ __forceinline__ T sp_length_circle(const T* p0, const T* p1, int ind, float radius) {
329
+ const T cr = p0[1] * p1[0] - p0[0] * p1[1];
330
+ T ang = sp_atan2(sp_abs(cr), p0[0] * p1[0] + p0[1] * p1[1]);
331
+ if ((spv(cr) > 0.f && ind != 0) || (spv(cr) < 0.f && ind == 0)) ang = T(6.2831853071795862f) - ang;
332
+ return T(radius) * ang;
333
+ }
334
+
335
+ // util_misc.wrap_circle: e = (end0, end1), side (sd, valid: vs) projected and scaled; the wrap length (< 0: none) and
336
+ // the two points
337
+ template <class T>
338
+ __device__ T sp_wrap_circle(const T* e, bool vs, const T* sd, float radius, T* pnt0, T* pnt1) {
339
+ const T sqlen0 = e[0] * e[0] + e[1] * e[1], sqlen1 = e[2] * e[2] + e[3] * e[3];
340
+ const T sqrad = T(radius) * T(radius);
341
+ if (spv(sqlen0) < spv(sqrad) || spv(sqlen1) < spv(sqrad) || radius < SP_MINVAL) return T(-1.f);
342
+ const T dx = e[2] - e[0], dy = e[3] - e[1];
343
+ const T dd = dx * dx + dy * dy;
344
+ if (spv(dd) < SP_MINVAL) return T(-1.f);
345
+ T a = -(dx * e[0] + dy * e[1]) / dd;
346
+ if (spv(a) < 0.f) a = T(0.f);
347
+ if (spv(a) > 1.f) a = T(1.f);
348
+ const T tx = a * dx + e[0], ty = a * dy + e[1];
349
+ if (spv(tx * tx + ty * ty) > spv(sqrad) && (!vs || spv(sd[0] * tx + sd[1] * ty) >= 0.f)) return T(-1.f);
350
+ const T s0 = sp_sqrt(sqlen0 - sqrad), s1 = sp_sqrt(sqlen1 - sqrad), R = T(radius);
351
+ T sol00[2] = {sp_sdiv(e[0] * sqrad + R * e[1] * s0, sqlen0), sp_sdiv(e[1] * sqrad - R * e[0] * s0, sqlen0)};
352
+ T sol01[2] = {sp_sdiv(e[2] * sqrad - R * e[3] * s1, sqlen1), sp_sdiv(e[3] * sqrad + R * e[2] * s1, sqlen1)};
353
+ T sol10[2] = {sp_sdiv(e[0] * sqrad - R * e[1] * s0, sqlen0), sp_sdiv(e[1] * sqrad + R * e[0] * s0, sqlen0)};
354
+ T sol11[2] = {sp_sdiv(e[2] * sqrad + R * e[3] * s1, sqlen1), sp_sdiv(e[3] * sqrad - R * e[2] * s1, sqlen1)};
355
+ SpR good0, good1;
356
+ if (vs) {
357
+ SpR ax = SpR(spv(sol00[0])) + SpR(spv(sol01[0])), ay = SpR(spv(sol00[1])) + SpR(spv(sol01[1]));
358
+ SpR n = sp_sqrt(ax * ax + ay * ay);
359
+ if (n.v != 0.f) { ax = ax / n; ay = ay / n; }
360
+ good0 = ax * SpR(spv(sd[0])) + ay * SpR(spv(sd[1]));
361
+ ax = SpR(spv(sol10[0])) + SpR(spv(sol11[0])); ay = SpR(spv(sol10[1])) + SpR(spv(sol11[1]));
362
+ n = sp_sqrt(ax * ax + ay * ay);
363
+ if (n.v != 0.f) { ax = ax / n; ay = ay / n; }
364
+ good1 = ax * SpR(spv(sd[0])) + ay * SpR(spv(sd[1]));
365
+ } else {
366
+ SpR ax = SpR(spv(sol00[0])) - SpR(spv(sol01[0])), ay = SpR(spv(sol00[1])) - SpR(spv(sol01[1]));
367
+ good0 = -(ax * ax + ay * ay);
368
+ ax = SpR(spv(sol10[0])) - SpR(spv(sol11[0])); ay = SpR(spv(sol10[1])) - SpR(spv(sol11[1]));
369
+ good1 = -(ax * ax + ay * ay);
370
+ }
371
+ const bool i0 = sp_intersect(SpR(spv(e[0])), SpR(spv(e[1])), SpR(spv(sol00[0])), SpR(spv(sol00[1])), SpR(spv(e[2])),
372
+ SpR(spv(e[3])), SpR(spv(sol01[0])), SpR(spv(sol01[1])));
373
+ const bool i1 = sp_intersect(SpR(spv(e[0])), SpR(spv(e[1])), SpR(spv(sol10[0])), SpR(spv(sol10[1])), SpR(spv(e[2])),
374
+ SpR(spv(e[3])), SpR(spv(sol11[0])), SpR(spv(sol11[1])));
375
+ if (i0) good0 = SpR(-10000.f);
376
+ if (i1) good1 = SpR(-10000.f);
377
+ int ind;
378
+ if (good0.v > good1.v) {
379
+ if (i0) return T(-1.f);
380
+ pnt0[0] = sol00[0]; pnt0[1] = sol00[1]; pnt1[0] = sol01[0]; pnt1[1] = sol01[1];
381
+ ind = 0;
382
+ } else {
383
+ if (i1) return T(-1.f);
384
+ pnt0[0] = sol10[0]; pnt0[1] = sol10[1]; pnt1[0] = sol11[0]; pnt1[1] = sol11[1];
385
+ ind = 1;
386
+ }
387
+ return sp_length_circle(pnt0, pnt1, ind, radius);
388
+ }
389
+
390
+ // util_misc.wrap_inside (side site inside the geom): 0 and the single point (pnt0 = pnt1), or -1 (no wrap)
391
+ template <class T>
392
+ __device__ T sp_wrap_inside(const T* e, float radius, T* pnt0, T* pnt1) {
393
+ const T len0 = sp_nrm2(e[0], e[1]), len1 = sp_nrm2(e[2], e[3]);
394
+ const T dx = e[2] - e[0], dy = e[3] - e[1];
395
+ const T dd = dx * dx + dy * dy;
396
+ if (spv(len0) <= radius || spv(len1) <= radius || radius < SP_MINVAL || spv(len0) < SP_MINVAL
397
+ || spv(len1) < SP_MINVAL)
398
+ return T(-1.f);
399
+ if (spv(dd) > SP_MINVAL) {
400
+ const T a = -(dx * e[0] + dy * e[1]) / dd;
401
+ if (spv(a) > 0.f && spv(a) < 1.f) {
402
+ const T tx = e[0] + a * dx, ty = e[1] + a * dy;
403
+ if (spv(sp_nrm2(tx, ty)) <= radius) return T(-1.f);
404
+ }
405
+ }
406
+ T px = T(0.5f) * (e[0] + e[2]), py = T(0.5f) * (e[1] + e[3]);
407
+ {
408
+ const T n = sp_nrm2(px, py);
409
+ if (spv(n) != 0.f) { px = px / n; py = py / n; }
410
+ }
411
+ px = px * T(radius); py = py * T(radius);
412
+ pnt0[0] = pnt1[0] = px; pnt0[1] = pnt1[1] = py;
413
+ const T R = T(radius);
414
+ const T A = sp_sdiv(R, len0), B = sp_sdiv(R, len1);
415
+ const T sqA = A * A, sqB = B * B;
416
+ const T cosG = sp_sdiv(len0 * len0 + len1 * len1 - dd, T(2.f) * len0 * len1);
417
+ if (spv(cosG) < -1.f + SP_MINVAL) return T(-1.f);
418
+ if (spv(cosG) > 1.f - SP_MINVAL) return T(0.f);
419
+ const T G = sp_acos(cosG);
420
+ T phi = T(1.5707963267948966f), z = T(1.f);
421
+ T asA = sp_asin(A), asB = sp_asin(B);
422
+ T f = asA + asB - T(3.1415926535897931f) + G;
423
+ if (spv(f) > 0.f) return T(0.f);
424
+ int it = 0;
425
+ while (it < 20 && fabsf(spv(f)) > 1e-6f) {
426
+ const T sqz = z * z;
427
+ T r1 = sp_sqrt(T(1.f) - sqz * sqA), r2 = sp_sqrt(T(1.f) - sqz * sqB);
428
+ if (spv(r1) < SP_MINVAL) r1 = T(SP_MINVAL);
429
+ if (spv(r2) < SP_MINVAL) r2 = T(SP_MINVAL);
430
+ const T df = sp_cos(phi) * (A / r1 + B / r2) - T(2.f);
431
+ if (spv(df) > -SP_MINVAL) return T(0.f);
432
+ const T phi1 = phi - sp_sdiv(f, df);
433
+ if (spv(phi1) > spv(phi)) return T(0.f);
434
+ phi = phi1;
435
+ z = sp_sin(phi);
436
+ asA = sp_asin(A * z);
437
+ asB = sp_asin(B * z);
438
+ f = asA + asB - T(2.f) * phi + G;
439
+ if (spv(f) > 1e-6f) return T(0.f);
440
+ it++;
441
+ }
442
+ if (it >= 20) return T(0.f);
443
+ T vx, vy, ang;
444
+ if (spv(e[0] * e[3] - e[1] * e[2]) > 0.f) { vx = e[0]; vy = e[1]; ang = phi - asA; }
445
+ else { vx = e[2]; vy = e[3]; ang = phi - asB; }
446
+ {
447
+ const T n = sp_nrm2(vx, vy);
448
+ if (spv(n) != 0.f) { vx = vx / n; vy = vy / n; }
449
+ }
450
+ const T ca = sp_cos(ang), sa = sp_sin(ang);
451
+ px = R * (ca * vx - sa * vy);
452
+ py = R * (sa * vx + ca * vy);
453
+ pnt0[0] = pnt1[0] = px; pnt0[1] = pnt1[1] = py;
454
+ return T(0.f);
455
+ }
456
+
457
+ // util_misc.wrap in the geom's frame: p0, p1 the sites, side the side site (null: none); the wrap length (< 0: no wrap)
458
+ // and the tangent points r0, r1 (geom frame); cyl: a cylinder (else a sphere)
459
+ template <class T>
460
+ __device__ T sp_wrap_local(const T* p0, const T* p1, const SpR* side, float radius, bool cyl, T* r0, T* r1) {
461
+ if (spv(sp_nrm3(p0)) < SP_MINVAL || spv(sp_nrm3(p1)) < SP_MINVAL) return T(-1.f);
462
+ T a0[3], a1[3];
463
+ if (!cyl) {
464
+ T n0 = sp_nrm3(p0);
465
+ for (int k = 0; k < 3; k++) a0[k] = spv(n0) != 0.f ? p0[k] / n0 : p0[k];
466
+ T nm[3] = {p0[1] * p1[2] - p0[2] * p1[1], p0[2] * p1[0] - p0[0] * p1[2], p0[0] * p1[1] - p0[1] * p1[0]};
467
+ const T nrm = sp_nrm3(nm);
468
+ if (spv(nrm) != 0.f)
469
+ for (int k = 0; k < 3; k++) nm[k] = nm[k] / nrm;
470
+ if (spv(nrm) < SP_MINVAL) {
471
+ const float b0 = fabsf(spv(a0[0])), b1 = fabsf(spv(a0[1])), b2 = fabsf(spv(a0[2]));
472
+ int i = 0;
473
+ if (b1 > b0 && b1 > b2) i = 1;
474
+ if (b2 > b0 && b2 > b1) i = 2;
475
+ T ax[3] = {T(1.f), T(1.f), T(1.f)};
476
+ ax[i] = T(0.f);
477
+ nm[0] = a0[1] * ax[2] - a0[2] * ax[1]; nm[1] = a0[2] * ax[0] - a0[0] * ax[2]; nm[2] = a0[0] * ax[1] - a0[1] * ax[0];
478
+ const T n2 = sp_nrm3(nm);
479
+ if (spv(n2) != 0.f)
480
+ for (int k = 0; k < 3; k++) nm[k] = nm[k] / n2;
481
+ }
482
+ a1[0] = nm[1] * a0[2] - nm[2] * a0[1]; a1[1] = nm[2] * a0[0] - nm[0] * a0[2]; a1[2] = nm[0] * a0[1] - nm[1] * a0[0];
483
+ const T n1 = sp_nrm3(a1);
484
+ if (spv(n1) != 0.f)
485
+ for (int k = 0; k < 3; k++) a1[k] = a1[k] / n1;
486
+ } else {
487
+ a0[0] = T(1.f); a0[1] = T(0.f); a0[2] = T(0.f);
488
+ a1[0] = T(0.f); a1[1] = T(1.f); a1[2] = T(0.f);
489
+ }
490
+ T e[4] = {p0[0] * a0[0] + p0[1] * a0[1] + p0[2] * a0[2], p0[0] * a1[0] + p0[1] * a1[1] + p0[2] * a1[2],
491
+ p1[0] * a0[0] + p1[1] * a0[1] + p1[2] * a0[2], p1[0] * a1[0] + p1[1] * a1[1] + p1[2] * a1[2]};
492
+ T pn0[2], pn1[2], wlen;
493
+ if (side) { // the side site: projected and scaled (decisions only: its values)
494
+ T sd[2] = {T(spv(side[0])) * a0[0] + T(spv(side[1])) * a0[1] + T(spv(side[2])) * a0[2],
495
+ T(spv(side[0])) * a1[0] + T(spv(side[1])) * a1[1] + T(spv(side[2])) * a1[2]};
496
+ const T n = sp_nrm2(sd[0], sd[1]);
497
+ if (spv(n) != 0.f) { sd[0] = sd[0] / n; sd[1] = sd[1] / n; }
498
+ sd[0] = sd[0] * T(radius); sd[1] = sd[1] * T(radius);
499
+ if (spv(sp_nrm3(side)) < radius) wlen = sp_wrap_inside(e, radius, pn0, pn1);
500
+ else wlen = sp_wrap_circle(e, true, sd, radius, pn0, pn1);
501
+ } else {
502
+ const T sd[2] = {T(0.f), T(0.f)};
503
+ wlen = sp_wrap_circle(e, false, sd, radius, pn0, pn1);
504
+ }
505
+ if (spv(wlen) < 0.f) return T(-1.f);
506
+ for (int k = 0; k < 3; k++) {
507
+ r0[k] = a0[k] * pn0[0] + a1[k] * pn0[1];
508
+ r1[k] = a0[k] * pn1[0] + a1[k] * pn1[1];
509
+ }
510
+ if (cyl) {
511
+ const T d0x = p0[0] - r0[0], d0y = p0[1] - r0[1], d1x = p1[0] - r1[0], d1y = p1[1] - r1[1];
512
+ const T L0 = sp_sqrt(d0x * d0x + d0y * d0y), L1 = sp_sqrt(d1x * d1x + d1y * d1y);
513
+ const T tot = L0 + wlen + L1;
514
+ r0[2] = p0[2] + (p1[2] - p0[2]) * sp_sdiv(L0, tot);
515
+ r1[2] = p0[2] + (p1[2] - p0[2]) * sp_sdiv(L0 + wlen, tot);
516
+ const T hgt = sp_abs(r1[2] - r0[2]);
517
+ wlen = sp_sqrt(wlen * wlen + hgt * hgt);
518
+ }
519
+ return wlen;
520
+ }
521
+
522
+ // world position of site s
523
+ __device__ __forceinline__ void sp_site(const float (*Q)[4], const float (*X)[3], int s, float* x) {
524
+ const int b = c_stb[s];
525
+ float o[3];
526
+ qrot_rn(Q[b], c_stp + 3 * s, o);
527
+ for (int k = 0; k < 3; k++) x[k] = RADD(X[b][k], o[k]);
528
+ }
529
+ // world pose of wrap geom g (centre xg, quaternion qg)
530
+ __device__ __forceinline__ void sp_geom(const float (*Q)[4], const float (*X)[3], int g, float* xg, float* qg) {
531
+ const int b = c_wgb[g];
532
+ float o[3];
533
+ qrot_rn(Q[b], c_wgp + 3 * g, o);
534
+ for (int k = 0; k < 3; k++) xg[k] = RADD(X[b][k], o[k]);
535
+ qmul_rn(Q[b], c_wgq + 4 * g, qg);
536
+ }
537
+ // x (world) in the frame (xg, qg)
538
+ __device__ __forceinline__ void sp_tolocal(const float* xg, const float* qg, const float* x, float* l) {
539
+ const float qc[4] = {qg[0], -qg[1], -qg[2], -qg[3]};
540
+ const float d[3] = {RSUB(x[0], xg[0]), RSUB(x[1], xg[1]), RSUB(x[2], xg[2])};
541
+ qrot_rn(qc, d, l);
542
+ }
543
+ // segment sg's wrap at sites x0, x1 (world): the wrap length (< 0: none, straight), the tangent points t0, t1 (world),
544
+ // and the sites in the geom frame p0l, p1l and the geom's pose (for the adjoint)
545
+ __device__ float sp_wrap(const float (*Q)[4], const float (*X)[3], int sg, const float* x0, const float* x1, float* t0,
546
+ float* t1, float* p0l, float* p1l, float* xg, float* qg) {
547
+ const int g = c_sgg[sg];
548
+ sp_geom(Q, X, g, xg, qg);
549
+ sp_tolocal(xg, qg, x0, p0l);
550
+ sp_tolocal(xg, qg, x1, p1l);
551
+ SpR side[3], P0[3] = {p0l[0], p0l[1], p0l[2]}, P1[3] = {p1l[0], p1l[1], p1l[2]}, R0[3], R1[3];
552
+ const int sd = c_sgsd[sg];
553
+ if (sd >= 0) {
554
+ float xs[3], sl[3];
555
+ sp_site(Q, X, sd, xs);
556
+ sp_tolocal(xg, qg, xs, sl);
557
+ for (int k = 0; k < 3; k++) side[k] = SpR(sl[k]);
558
+ }
559
+ const SpR wl = sp_wrap_local(P0, P1, sd >= 0 ? side : (const SpR*)nullptr, c_wgr[g], c_sgk[sg] == 2, R0, R1);
560
+ if (wl.v < 0.f) return -1.f;
561
+ const float r0[3] = {R0[0].v, R0[1].v, R0[2].v}, r1[3] = {R1[0].v, R1[1].v, R1[2].v};
562
+ float o[3];
563
+ qrot_rn(qg, r0, o);
564
+ for (int k = 0; k < 3; k++) t0[k] = RADD(xg[k], o[k]);
565
+ qrot_rn(qg, r1, o);
566
+ for (int k = 0; k < 3; k++) t1[k] = RADD(xg[k], o[k]);
567
+ return wl.v;
568
+ }
569
+ __device__ __forceinline__ SpR sp_dist(const float* a, const float* b) {
570
+ const SpR dx = SpR(b[0]) - SpR(a[0]), dy = SpR(b[1]) - SpR(a[1]), dz = SpR(b[2]) - SpR(a[2]);
571
+ return sp_sqrt(dx * dx + dy * dy + dz * dz);
572
+ }
573
+ // the motion column of dof i of body bb at world point p (hinge z x (p - X), slide z, free: translation e_j, rotation
574
+ // (R e_j) x (p - X)); j: the free joint's dof index (0..5). Explicit roundings (as all of J: the fused and the split
575
+ // forward compute the same bits)
576
+ __device__ __forceinline__ void sp_col(const float (*Q)[4], const float (*X)[3], int bb, int j, const float* p,
577
+ float* col, float* z) {
578
+ const int jt = JT_OF(bb);
579
+ const float r[3] = {RSUB(p[0], X[bb][0]), RSUB(p[1], X[bb][1]), RSUB(p[2], X[bb][2])};
580
+ if (jt == JFREE) {
581
+ if (j < 3) { col[0] = col[1] = col[2] = 0.f; col[j] = 1.f; z[0] = z[1] = z[2] = 0.f; return; }
582
+ float e[3] = {0.f, 0.f, 0.f};
583
+ e[j - 3] = 1.f;
584
+ qrot_rn(Q[bb], e, z);
585
+ } else {
586
+ qrot_rn(Q[bb], c_axis + 3 * bb, z);
587
+ if (jt == JSLIDE) { col[0] = z[0]; col[1] = z[1]; col[2] = z[2]; return; }
588
+ }
589
+ cross_rn(z, r, col);
590
+ }
591
+ // J[t] += w u . (motion column of each support dof on body b's chain at p)
592
+ __device__ void sp_chain_add(const float (*Q)[4], const float (*X)[3], float* J, int t, int b, const float* p,
593
+ const float* u, float w) {
594
+ for (int bb = b; bb > 0; bb = c_parent[bb]) {
595
+ const int i0 = c_dadr[bb], nd = JT_OF(bb) == JFREE ? 6 : 1;
596
+ for (int j = 0; j < nd; j++) {
597
+ const int k = c_tpos[NV * t + i0 + j];
598
+ if (k < 0) continue;
599
+ float col[3], z[3];
600
+ sp_col(Q, X, bb, nd == 6 ? j : 0, p, col, z);
601
+ J[k] = RFMA(w, dot3_rn(u, col), J[k]);
602
+ }
603
+ }
604
+ }
605
+ // a straight piece pa (body ba) -> pb (body bb) with scale sc: J += sc u'(J_pb - J_pa) when the bodies differ
606
+ __device__ __forceinline__ void sp_piece(const float (*Q)[4], const float (*X)[3], float* J, int t, const float* pa,
607
+ int ba, const float* pb, int bb, float sc) {
608
+ if (ba == bb) return;
609
+ float u[3] = {RSUB(pb[0], pa[0]), RSUB(pb[1], pa[1]), RSUB(pb[2], pa[2])};
610
+ const float n = __fsqrt_rn(dot3_rn(u, u));
611
+ if (n < SP_MINVAL) { u[0] = 1.f; u[1] = u[2] = 0.f; }
612
+ else for (int k = 0; k < 3; k++) u[k] = __fdiv_rn(u[k], n);
613
+ sp_chain_add(Q, X, J, t, bb, pb, u, sc);
614
+ sp_chain_add(Q, X, J, t, ba, pa, u, -sc);
615
+ }
616
+ // L and J of every tendon (lane per tendon) into T (TS_WORDS: L, J), from the body poses Q, X (bitwise the forward's in
617
+ // the adjoint) and qpos (fixed tendons: L = sum c q, the fixed text's ten_len)
618
+ __device__ void sp_compute(const float (*Q)[4], const float (*X)[3], const float* qpos, float* T, int lane) {
619
+ for (int t = lane; t < NTEN; t += 32) {
620
+ float* J = T + NTEN + KTEN * t;
621
+ if (c_tsgn[t] == 0) {
622
+ const unsigned char* d = c_tdof + KTEN * t;
623
+ const float* c = c_tco + KTEN * t;
624
+ float L = RMUL(c[0], qpos[c_dqadr[d[0]]]);
625
+ for (int k = 1; k < c_tnd[t]; k++) L = RFMA(c[k], qpos[c_dqadr[d[k]]], L);
626
+ T[t] = L;
627
+ for (int k = 0; k < KTEN; k++) J[k] = c[k];
628
+ continue;
629
+ }
630
+ for (int k = 0; k < KTEN; k++) J[k] = 0.f;
631
+ SpR L(0.f);
632
+ for (int sg = c_tsg0[t]; sg < c_tsg0[t] + c_tsgn[t]; sg++) {
633
+ const int s0 = c_sgs0[sg], s1 = c_sgs1[sg], b0 = c_stb[s0], b1 = c_stb[s1];
634
+ const float sc = c_sgsc[sg];
635
+ float x0[3], x1[3];
636
+ sp_site(Q, X, s0, x0);
637
+ sp_site(Q, X, s1, x1);
638
+ if (c_sgk[sg] != 0) {
639
+ float t0[3], t1[3], p0l[3], p1l[3], xg[3], qg[4];
640
+ const float wl = sp_wrap(Q, X, sg, x0, x1, t0, t1, p0l, p1l, xg, qg);
641
+ if (wl >= 0.f) {
642
+ const int bg = c_wgb[c_sgg[sg]];
643
+ const SpR tot = sp_dist(x0, t0) + SpR(wl) + sp_dist(t1, x1);
644
+ if (tot.v != 0.f) L = L + tot * SpR(sc);
645
+ sp_piece(Q, X, J, t, x0, b0, t0, bg, sc);
646
+ sp_piece(Q, X, J, t, t1, bg, x1, b1, sc);
647
+ continue;
648
+ }
649
+ }
650
+ const SpR len = sp_dist(x0, x1);
651
+ if (len.v != 0.f) L = L + len * SpR(sc);
652
+ sp_piece(Q, X, J, t, x0, b0, x1, b1, sc);
653
+ }
654
+ T[t] = L.v;
655
+ }
656
+ }
657
+ // the tendon actuators (lane per actuator, after sp_compute): f = kp u - kq L - kv (J v), u = ctrl clamped to
658
+ // ctrlrange, f clamped to the forcerange; force and flags (bit 0 force clamped, bit 1 ctrl clamped) into the storage and
659
+ // the tape (rec: null for none)
660
+ __device__ void sp_actuators(const float* qvel, const float* ctrl, float* T, float* rec, int lane) {
661
+ for (int k = lane; k < NTACT; k += 32) {
662
+ const int t = c_tat[k], a = c_taa[k];
663
+ const unsigned char* d = c_tdof + KTEN * t;
664
+ const float* J = T + NTEN + KTEN * t;
665
+ float jv = 0.f;
666
+ for (int q = 0; q < c_tnd[t]; q++) jv = RFMA(J[q], qvel[d[q]], jv);
667
+ const float u = fminf(fmaxf(ctrl[a], c_tactr[2 * k]), c_tactr[2 * k + 1]);
668
+ float f = RFMS(c_takv[k], jv, RFMS(c_takq[k], T[t], RMUL(c_takp[k], u)));
669
+ const bool fc = f <= -c_tafrc[k] || f >= c_tafrc[k];
670
+ f = fminf(fmaxf(f, -c_tafrc[k]), c_tafrc[k]);
671
+ const int fl = (fc ? 1 : 0) | (u != ctrl[a] ? 2 : 0);
672
+ T[NTEN + NTEN * KTEN + k] = f;
673
+ T[NTEN + NTEN * KTEN + NTACT + k] = __int_as_float(fl);
674
+ if (rec) { __stcs(rec + OFF_TACT + k, f); __stcs(rec + OFF_TACT + NTACT + k, __int_as_float(fl)); }
675
+ }
676
+ }
677
+ // the tendon actuators' force on dof i (J f)
678
+ __device__ __forceinline__ float sp_tact_qfrc(int i) {
679
+ float acc = 0.f;
680
+ for (int k = 0; k < NTACT; k++) {
681
+ const float c = ts_cd(c_tat[k], i);
682
+ if (c != 0.f) acc = RFMA(c, TS_F(k), acc);
683
+ }
684
+ return acc;
685
+ }
686
+ // L += h kv J J' of the tendon actuators whose force is not clamped, on M's sparsity pattern
687
+ template <class S>
688
+ __device__ void sp_tact_implicit(S& s, float h, int lane) {
689
+ for (int k = 0; k < NTACT; k++) {
690
+ if ((TS_FL(k) & 1) || c_takv[k] == 0.f) continue;
691
+ const int t = c_tat[k], nd = c_tnd[t];
692
+ const unsigned char* d = c_tdof + KTEN * t;
693
+ const float* c = TS_J(t);
694
+ if (lane < nd) {
695
+ const float g = h * c_takv[k] * c[lane];
696
+ const unsigned pm = c_tpat[KTEN * t + lane];
697
+ for (int b = 0; b <= lane; b++)
698
+ if ((pm >> b) & 1u) s.L[TRI(d[lane], d[b])] += g * c[b];
699
+ }
700
+ __syncwarp();
701
+ }
702
+ }
703
+ """
704
+
705
+ ADJ_DEVICE = r"""
706
+ #if DK_ADJ_WARPS == 2
707
+ #error "spatial tendons: not with DK_ADJ_WARPS=2 (the latency mode)"
708
+ #endif
709
+ // the limit row's weight on J (forest_engine.spatial): W += D (J lam) (a + b v) + sg D x lam on the support
710
+ __device__ __forceinline__ void sp_row_w(Adj& s, int t, float D, float cl, float x, float b, float sg) {
711
+ if (c_tsgn[t] == 0) return;
712
+ const unsigned char* d = c_tdof + KTEN * t;
713
+ float* w = s.tw + KTEN * t;
714
+ for (int q = 0; q < c_tnd[t]; q++) w[q] += D * cl * (s.a[d[q]] + b * s.v[d[q]]) + sg * D * x * s.lam[d[q]];
715
+ }
716
+ // body b's pose cotangent of a point cotangent pb at world point p (b 0: none)
717
+ __device__ __forceinline__ void sp_pt_bar(Adj& s, int b, const float* p, const float* pb) {
718
+ if (b <= 0) return;
719
+ float t[3], r[3] = {p[0] - s.X[b][0], p[1] - s.X[b][1], p[2] - s.X[b][2]};
720
+ cross(r, pb, t);
721
+ for (int k = 0; k < 3; k++) { s.fb[b][k] += pb[k]; s.tb[b][k] += t[k]; }
722
+ }
723
+ // the end p (body b) of a piece with g = coefficient x u (J . W's term g . V_W(p)): the support dofs' axes / anchors
724
+ // (pose cotangents of their bodies) and the point's own cotangent pbar += g x omega_W; also V_W(p) into vw
725
+ __device__ void sp_end_bar(Adj& s, int t, int b, const float* p, const float* g, const float* w, float* pbar,
726
+ float* vw) {
727
+ for (int k = 0; k < 3; k++) vw[k] = 0.f;
728
+ for (int bb = b; bb > 0; bb = c_parent[bb]) {
729
+ const int i0 = c_dadr[bb], nd = JT_OF(bb) == JFREE ? 6 : 1;
730
+ for (int j = 0; j < nd; j++) {
731
+ const int k = c_tpos[NV * t + i0 + j];
732
+ if (k < 0) continue;
733
+ const float wk = w[k];
734
+ float col[3], z[3], t3[3], u3[3];
735
+ sp_col(s.Q, s.X, bb, nd == 6 ? j : 0, p, col, z);
736
+ for (int c = 0; c < 3; c++) vw[c] += wk * col[c];
737
+ const int jt = JT_OF(bb);
738
+ if (jt == JFREE && j < 3) continue;
739
+ if (jt == JSLIDE) { // g . z w: z rotates with bb
740
+ for (int c = 0; c < 3; c++) u3[c] = wk * g[c];
741
+ cross(z, u3, t3);
742
+ for (int c = 0; c < 3; c++) s.tb[bb][c] += t3[c];
743
+ continue;
744
+ }
745
+ // g . (z x (p - X)) w: X bar = -w (g x z), z bar = w (p - X) x g, p bar = w (g x z)
746
+ float gz[3], r[3] = {p[0] - s.X[bb][0], p[1] - s.X[bb][1], p[2] - s.X[bb][2]};
747
+ cross(g, z, gz);
748
+ cross(r, g, u3);
749
+ for (int c = 0; c < 3; c++) u3[c] *= wk;
750
+ cross(z, u3, t3);
751
+ for (int c = 0; c < 3; c++) { s.fb[bb][c] -= wk * gz[c]; s.tb[bb][c] += t3[c]; pbar[c] += wk * gz[c]; }
752
+ }
753
+ }
754
+ }
755
+ // P_q += d/dq [J_t(q) . W] of spatial tendon t (W = s.tw's row on the support), as pose cotangents (s.fb, s.tb)
756
+ __device__ void sp_hvp(Adj& s, int t) {
757
+ const float* w = s.tw + KTEN * t;
758
+ for (int sg = c_tsg0[t]; sg < c_tsg0[t] + c_tsgn[t]; sg++) {
759
+ const int s0 = c_sgs0[sg], s1 = c_sgs1[sg], b0 = c_stb[s0], b1 = c_stb[s1];
760
+ const float sc = c_sgsc[sg];
761
+ float x0[3], x1[3];
762
+ sp_site(s.Q, s.X, s0, x0);
763
+ sp_site(s.Q, s.X, s1, x1);
764
+ // the pieces: (pa, ba, tangent index of pa or -1, pb, bb, tangent index of pb or -1)
765
+ float P[2][2][3];
766
+ int Bd[2][2], Tg[2][2], np = 1;
767
+ float t0[3], t1[3], p0l[3], p1l[3], xg[3], qg[4];
768
+ int bg = 0;
769
+ float wl = -1.f;
770
+ if (c_sgk[sg] != 0) wl = sp_wrap(s.Q, s.X, sg, x0, x1, t0, t1, p0l, p1l, xg, qg);
771
+ if (wl >= 0.f) {
772
+ bg = c_wgb[c_sgg[sg]];
773
+ np = 2;
774
+ for (int k = 0; k < 3; k++) { P[0][0][k] = x0[k]; P[0][1][k] = t0[k]; P[1][0][k] = t1[k]; P[1][1][k] = x1[k]; }
775
+ Bd[0][0] = b0; Bd[0][1] = bg; Bd[1][0] = bg; Bd[1][1] = b1;
776
+ Tg[0][0] = -1; Tg[0][1] = 0; Tg[1][0] = 1; Tg[1][1] = -1;
777
+ } else {
778
+ for (int k = 0; k < 3; k++) { P[0][0][k] = x0[k]; P[0][1][k] = x1[k]; }
779
+ Bd[0][0] = b0; Bd[0][1] = b1; Tg[0][0] = Tg[0][1] = -1;
780
+ }
781
+ float tbar[2][3] = {{0.f, 0.f, 0.f}, {0.f, 0.f, 0.f}}; // the tangent points' world cotangents (sliding part)
782
+ for (int pc = 0; pc < np; pc++) {
783
+ const float *pa = P[pc][0], *pb = P[pc][1];
784
+ const int ba = Bd[pc][0], bb = Bd[pc][1];
785
+ if (ba == bb) continue;
786
+ float u[3] = {pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]};
787
+ const float n = sqrtf(dot3(u, u));
788
+ const bool fix = n < SP_MINVAL;
789
+ if (fix) { u[0] = 1.f; u[1] = u[2] = 0.f; }
790
+ else for (int k = 0; k < 3; k++) u[k] /= n;
791
+ float ga[3], gb[3], pba[3] = {0.f, 0.f, 0.f}, pbb[3] = {0.f, 0.f, 0.f}, va[3], vb[3];
792
+ for (int k = 0; k < 3; k++) { gb[k] = sc * u[k]; ga[k] = -sc * u[k]; }
793
+ sp_end_bar(s, t, bb, pb, gb, w, pbb, vb);
794
+ sp_end_bar(s, t, ba, pa, ga, w, pba, va);
795
+ if (!fix) { // u's cotangent sc (V_W(pb) - V_W(pa)) onto the ends
796
+ float ub[3] = {sc * (vb[0] - va[0]), sc * (vb[1] - va[1]), sc * (vb[2] - va[2])};
797
+ const float uu = dot3(u, ub);
798
+ for (int k = 0; k < 3; k++) {
799
+ const float db = (ub[k] - u[k] * uu) / n;
800
+ pbb[k] += db; pba[k] -= db;
801
+ }
802
+ }
803
+ sp_pt_bar(s, bb, pb, pbb);
804
+ sp_pt_bar(s, ba, pa, pba);
805
+ if (Tg[pc][1] >= 0) for (int k = 0; k < 3; k++) tbar[Tg[pc][1]][k] += pbb[k];
806
+ if (Tg[pc][0] >= 0) for (int k = 0; k < 3; k++) tbar[Tg[pc][0]][k] += pba[k];
807
+ }
808
+ if (np == 2) { // the tangent points' motion over the geom: through the sites' local coordinates p0l, p1l
809
+ float tl[2][3];
810
+ const float qc[4] = {qg[0], -qg[1], -qg[2], -qg[3]};
811
+ qrot(qc, tbar[0], tl[0]);
812
+ qrot(qc, tbar[1], tl[1]);
813
+ SpD P0[3], P1[3], R0[3], R1[3];
814
+ for (int k = 0; k < 3; k++) {
815
+ P0[k] = SpD(p0l[k]); P0[k].d[k] = 1.f;
816
+ P1[k] = SpD(p1l[k]); P1[k].d[3 + k] = 1.f;
817
+ }
818
+ SpR side[3];
819
+ const int sd = c_sgsd[sg];
820
+ if (sd >= 0) {
821
+ float xs[3], sl[3];
822
+ sp_site(s.Q, s.X, sd, xs);
823
+ sp_tolocal(xg, qg, xs, sl);
824
+ for (int k = 0; k < 3; k++) side[k] = SpR(sl[k]);
825
+ }
826
+ const SpD wd = sp_wrap_local(P0, P1, sd >= 0 ? side : (const SpR*)nullptr, c_wgr[c_sgg[sg]], c_sgk[sg] == 2, R0,
827
+ R1);
828
+ if (wd.v >= 0.f) {
829
+ float l0[3], l1[3], g0[3], g1[3];
830
+ for (int c = 0; c < 3; c++) {
831
+ l0[c] = l1[c] = 0.f;
832
+ for (int k = 0; k < 3; k++) {
833
+ l0[c] += tl[0][k] * R0[k].d[c] + tl[1][k] * R1[k].d[c];
834
+ l1[c] += tl[0][k] * R0[k].d[3 + c] + tl[1][k] * R1[k].d[3 + c];
835
+ }
836
+ }
837
+ qrot(qg, l0, g0); // the sites' world cotangents; the geom's body pays the opposite (p_l = R'(x - x_g))
838
+ qrot(qg, l1, g1);
839
+ float m0[3] = {-g0[0], -g0[1], -g0[2]}, m1[3] = {-g1[0], -g1[1], -g1[2]};
840
+ sp_pt_bar(s, b0, x0, g0);
841
+ sp_pt_bar(s, bg, x0, m0);
842
+ sp_pt_bar(s, b1, x1, g1);
843
+ sp_pt_bar(s, bg, x1, m1);
844
+ }
845
+ }
846
+ }
847
+ }
848
+ // A5 / A6 (after adj_tendon, lane 0): the weights of the passive force, the actuators and the implicit damping / kv,
849
+ // then the pose cotangents of d/dq [J . W] for every spatial tendon; s.tw zeroed for the next substep
850
+ __device__ __noinline__ void adj_spatial(Adj& s, int lane) {
851
+ const float h = c_misc[0];
852
+ if (lane == 0)
853
+ for (int t = 0; t < NTEN; t++) {
854
+ if (c_tsgn[t] == 0) continue;
855
+ const unsigned char* d = c_tdof + KTEN * t;
856
+ const float* J = TS_J(t);
857
+ float* w = s.tw + KTEN * t;
858
+ const int nd = c_tnd[t];
859
+ float cl = 0.f;
860
+ for (int q = 0; q < nd; q++) cl += J[q] * s.lam[d[q]];
861
+ float cimp = 0.f; // the implicit matrix's coefficient of J J' (damping, actuator kv)
862
+ #if NTP > 0
863
+ for (int p = 0; p < NTP; p++) {
864
+ if (c_tpas[p] != t) continue;
865
+ float ke;
866
+ const float f = ten_passive_f(s.q, s.v, t, &ke);
867
+ for (int q = 0; q < nd; q++) w[q] += -f * s.lam[d[q]] + c_tdamp[t] * cl * s.v[d[q]];
868
+ if (TEN_IMPLICIT) cimp += c_tdamp[t];
869
+ }
870
+ #endif
871
+ for (int k = 0; k < NTACT; k++) {
872
+ if (c_tat[k] != t) continue;
873
+ const int fl = s.tfl[k];
874
+ const float f = s.tfrc[k], lt = (fl & 1) ? 0.f : cl;
875
+ for (int q = 0; q < nd; q++) w[q] += -f * s.lam[d[q]] + c_takv[k] * (DK_ADJ_CLAMP_KV ? lt : cl) * s.v[d[q]];
876
+ if (SP_IMPLICIT && !(fl & 1)) cimp += c_takv[k];
877
+ }
878
+ if (cimp != 0.f) // h c (y_i (J a_adv)_pat(i) + a_adv,i (J y)_pat(i)), y = -ny, a_adv = a - at
879
+ for (int q = 0; q < nd; q++) {
880
+ const int i = d[q];
881
+ float ja = 0.f, jy = 0.f;
882
+ for (int r = 0; r < nd; r++) {
883
+ const bool on = r <= q ? (c_tpat[KTEN * t + q] >> r) & 1u : (c_tpat[KTEN * t + r] >> q) & 1u;
884
+ if (on) { ja += J[r] * (s.a[d[r]] - s.at[d[r]]); jy -= J[r] * s.ny[d[r]]; }
885
+ }
886
+ w[q] += h * cimp * (-s.ny[i] * ja + (s.a[i] - s.at[i]) * jy);
887
+ }
888
+ sp_hvp(s, t);
889
+ for (int q = 0; q < KTEN; q++) w[q] = 0.f;
890
+ }
891
+ __syncwarp();
892
+ }
893
+ """
894
+
895
+
896
+ TEN_LEN_FIXED = """__device__ __forceinline__ float ten_len(const float* qpos, int t) {
897
+ const unsigned char* d = c_tdof + KTEN * t;
898
+ const float* c = c_tco + KTEN * t;
899
+ float L = RMUL(c[0], qpos[c_dqadr[d[0]]]);
900
+ for (int k = 1; k < c_tnd[t]; k++) L = RFMA(c[k], qpos[c_dqadr[d[k]]], L);
901
+ return L;
902
+ }
903
+ """
904
+ TEN_LEN_SPATIAL = """__device__ __forceinline__ float ten_len(const float* qpos, int t) { // (forest_engine.spatial: the storage)
905
+ (void)qpos;
906
+ return TS_L(t);
907
+ }
908
+ """
909
+
910
+
911
+ def _sub_tcd(b):
912
+ key = "c_tcd[NV * "
913
+ out, pos = [], 0
914
+ while True:
915
+ k = b.find(key, pos)
916
+ if k < 0:
917
+ return "".join(out) + b[pos:]
918
+ j, depth = k + len(key), 1
919
+ while depth:
920
+ depth += {"[": 1, "]": -1}.get(b[j], 0)
921
+ j += 1
922
+ inner = b[k + len(key):j - 1]
923
+ assert inner.endswith(" + i"), inner
924
+ out += [b[pos:k], f"ts_cd({inner[:-4]}, i)"]
925
+ pos = j
926
+
927
+
928
+ def _rewrite(b):
929
+ b = b.replace(TEN_LEN_FIXED, TEN_LEN_SPATIAL)
930
+ b = b.replace("c_tco + KTEN * t", "TS_J(t)")
931
+ b = _sub_tcd(b)
932
+ b = b.replace(", cr = c_tacar[k];", ";")
933
+ b = b.replace("!((s.kvoff[cr >> 5] >> (cr & 31)) & 1u)", "!(s.tfl[k] & 1)")
934
+ b = b.replace("((s.clamp[cr >> 5] >> (cr & 31)) & 1u) ? 0.f : cl", "(s.tfl[k] & 1) ? 0.f : cl")
935
+ b = b.replace("if (((s.clamp[cr >> 5] >> (cr & 31)) & 1u) || ((s.uclamp[cr >> 5] >> (cr & 31)) & 1u)) continue;",
936
+ "if (s.tfl[k] & 3) continue;")
937
+ b = b.replace("act += tact_qfrc(s.qpos, s.qvel, ctrl, i, &aclamp, &uclamp, &clamp);",
938
+ "act += sp_tact_qfrc(i);")
939
+ b = b.replace(" tact_implicit(s, h, lane);", " sp_tact_implicit(s, h, lane);")
940
+ return b
941
+
942
+
943
+ SP_FWD_AT = " __syncwarp();\n SUBPROF(17);\n"
944
+ SP_FWD = (" __syncwarp();\n"
945
+ " if (lane == 0) dk_tsp = ts_base(s); // the tendons' L, J and actuator forces (forest_engine.spatial)\n"
946
+ " __syncwarp();\n"
947
+ " sp_compute(s.Q, s.X, s.qpos, dk_tsp, lane);\n"
948
+ " __syncwarp();\n"
949
+ " sp_actuators(s.qvel, ctrl, dk_tsp, rec, lane);\n")
950
+ SP_POST_AT = ("__device__ void substep_post(S& s, int iterations, int lane, int* niter_out, float* rec) {\n"
951
+ " const float h = c_misc[0];\n")
952
+ SP_ADJ_MEMBERS_AT = " int flags; // union of the records' flags (tape.py), ADJ_ROWS_SKIPPED, ADJ_REPLAY_MISMATCH\n"
953
+ SP_ADJ_MEMBERS = (" float ts_store[TS_WORDS]; // the tendons' L, J (forest_engine.spatial), replayed per substep\n"
954
+ " float tw[NTEN * KTEN]; // the spatial tendons' weights W of d/dq [J . W] (adj_spatial)\n"
955
+ " float tfrc[NTACT > 0 ? NTACT : 1]; // the record's tendon actuator forces\n"
956
+ " int tfl[NTACT > 0 ? NTACT : 1]; // and flags (bit 0 force clamped, bit 1 ctrl clamped)\n")
957
+ SP_INIT_AT = "__device__ void adj_init(Adj& s, int lane) {\n"
958
+ SP_POSES_AT = " adj_poses(s, lane); // A3: poses and channel 1\n APROF(APROF_POSES);\n"
959
+ SP_POSES = (" if (lane == 0) dk_tsp = s.ts_store; // the tendons' L, J from the replayed poses (forest_engine.spatial)\n"
960
+ " __syncwarp();\n"
961
+ " sp_compute(s.Q, s.X, s.q, s.ts_store, lane);\n"
962
+ " for (int k = lane; k < NTACT; k += 32) {\n"
963
+ " s.tfrc[k] = __ldcs(rec + OFF_TACT + k);\n"
964
+ " s.tfl[k] = __float_as_int(__ldcs(rec + OFF_TACT + NTACT + k));\n"
965
+ " }\n"
966
+ " __syncwarp();\n")
967
+ SP_ROW_AT = " limit_row_vjp(sg, pos, ca, cv, cl, ri[0], ri[1], ri[2], ri[3], ri[4], ri[5], &pq, &pv);\n"
968
+ SP_ROW = " sp_row_w(s, t, ri[4], cl, sg * ca + ri[0] * ri[2] * pos + ri[1] * (sg * cv), ri[1], sg);\n"
969
+
970
+
971
+ def transform(m, pairs, conj_at, conj_extra, dev_at):
972
+ """forest_engine.tendon's (anchor, replacement) edits for a spatial build: the replacements rewritten (_rewrite),
973
+ this module's device text ahead of the tendon text (dev_at: the anchor whose replacement carries it), the storage
974
+ after the connect rows' J (conj_at: the struct Sim / Hand anchor, conj_extra its line), and the spatial edits
975
+ (sp_compute after the mass matrix, dk_tsp in substep_post and the adjoint, the adjoint's members, replay and
976
+ adj_spatial)."""
977
+ out = [(SP_FWD_AT, SP_FWD + SP_FWD_AT)]
978
+ for a, b in pairs:
979
+ b = _rewrite(b)
980
+ if a == conj_at:
981
+ b = b + conj_extra
982
+ if a == dev_at:
983
+ mark = "// fixed tendons (forest_engine.tendon): L = sum c_i q_i"
984
+ assert b.count(mark) == 1
985
+ b = b.replace(mark, DEVICE + mark, 1)
986
+ if "__device__ __noinline__ void adj_tendon(Adj& s, int lane, bool jtf)" in b:
987
+ assert b.count(SP_ROW_AT) == 1
988
+ b = b.replace(SP_ROW_AT, SP_ROW_AT + SP_ROW)
989
+ b = b.replace("// A5 / A6, tendon rows (forest_engine.tendon)", ADJ_DEVICE + "// A5 / A6, tendon rows "
990
+ "(forest_engine.tendon)", 1)
991
+ assert " adj_tendon(s, lane, jtf);\n}\n" in b
992
+ b = b.replace(" adj_tendon(s, lane, jtf);\n}\n", " adj_tendon(s, lane, jtf);\n adj_spatial(s, lane);\n}\n")
993
+ out.append((a, b))
994
+ out.append((SP_POST_AT, SP_POST_AT + " if (lane == 0) dk_tsp = ts_base(s); // (forest_engine.spatial)\n"
995
+ " __syncwarp();\n"))
996
+ return out
997
+
998
+
999
+ def adj_extra():
1000
+ """The adjoint's own spatial edits (with transform's)."""
1001
+ return [(SP_ADJ_MEMBERS_AT, SP_ADJ_MEMBERS_AT + SP_ADJ_MEMBERS),
1002
+ (SP_INIT_AT, SP_INIT_AT + " for (int i = lane; i < NTEN * KTEN; i += 32) s.tw[i] = 0.f; // "
1003
+ "(forest_engine.spatial)\n"),
1004
+ (SP_POSES_AT, SP_POSES_AT + SP_POSES)]
1005
+
1006
+
1007
+ PACK = (
1008
+ ("#define TS_WORDS (NTEN + NTEN * KTEN + 2 * NTACT", "#define TS_WORDS (NTEN + TS_JW + 2 * NTACT", 1),
1009
+ ("#define TS_J(t) (dk_tsp + NTEN + KTEN * (t))", "#define TS_J(t) (dk_tsp + NTEN + c_tjo[t])", 1),
1010
+ ("per-world storage: L, J (KTEN per tendon)", "per-world storage: L, J (packed: c_tjo)", 1),
1011
+ ("L[NTEN], J[NTEN][KTEN] (over the tendon's support)", "L[NTEN], J[TS_JW] (packed: each tendon's support)", 1),
1012
+ ("T + NTEN + KTEN * t", "T + NTEN + c_tjo[t]", None),
1013
+ ("NTEN + NTEN * KTEN", "NTEN + TS_JW", None),
1014
+ ("s.tw + KTEN * t", "s.tw + c_tjo[t]", None),
1015
+ (" float tw[NTEN * KTEN];", " float tw[TS_JW];", None),
1016
+ ("for (int i = lane; i < NTEN * KTEN; i += 32) s.tw[i] = 0.f;", "for (int i = lane; i < TS_JW; i += 32) s.tw[i] = 0.f;",
1017
+ None),
1018
+ (" for (int k = 0; k < KTEN; k++) J[k] = c[k];\n", " for (int k = 0; k < c_tnd[t]; k++) J[k] = c[k];\n", 1),
1019
+ (" for (int k = 0; k < KTEN; k++) J[k] = 0.f;\n", " for (int k = 0; k < c_tnd[t]; k++) J[k] = 0.f;\n", 1),
1020
+ (" for (int q = 0; q < KTEN; q++) w[q] = 0.f;\n", " for (int q = 0; q < c_tnd[t]; q++) w[q] = 0.f;\n", None),
1021
+ )
1022
+
1023
+
1024
+ def compact(src, m):
1025
+ """src (a spatial build's unit text, after forest_engine.tendon / spatial / muscle) in the packed layout: TS_JW (the
1026
+ J words: the used tendons' support sizes summed) and c_tjo (each tendon's first J word) ahead of TS_WORDS."""
1027
+ ts, sup, _, _ = _sizes(m)
1028
+ jo = np.concatenate([[0], np.cumsum(sup)[:-1]]).astype(int) if sup else [0]
1029
+ key = "#define TS_WORDS (NTEN + NTEN * KTEN + 2 * NTACT"
1030
+ if src.count(key) != 1:
1031
+ raise RuntimeError(f"forest spatial (packed layout): {src.count(key)} x {key!r}")
1032
+ head = (f"#define TS_JW {max(sum(sup), 1)} // the J words of the packed layout (forest_engine.spatial.compact: each "
1033
+ "tendon's J over its own support)\n"
1034
+ f"__device__ const int c_tjo[{len(ts)}] = {{{', '.join(str(int(x)) for x in jo)}}}; // tendon: its first J "
1035
+ "word\n")
1036
+ src = src.replace(key, head + key, 1)
1037
+ for a, b, n in PACK:
1038
+ k = src.count(a)
1039
+ if (n is not None and k != n) or k == 0:
1040
+ raise RuntimeError(f"forest spatial (packed layout): {k} x {a!r}")
1041
+ src = src.replace(a, b)
1042
+ for left in ("NTEN * KTEN", "NTEN + KTEN", "tw + KTEN", "k < KTEN; k++) J[k]", "q < KTEN; q++) w[q]"):
1043
+ if left in src:
1044
+ raise RuntimeError(f"forest spatial (packed layout): {left!r} left in the text")
1045
+ return src