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,577 @@
1
+ # The collision-primitive VJPs here differentiate the primitives step.py translated from MuJoCo Warp
2
+ # (mujoco_warp/_src/collision_primitive_core.py, math.make_frame; Copyright 2025 The Newton Developers, Apache License
3
+ # 2.0), and follow the conventions of MuJoCo Warp's adjoint (google-deepmind/mujoco_warp pull request 1535:
4
+ # collision_adjoint.py, adjoint_util.py, constraint_adjoint.py) so that they can be checked against it; the derivations
5
+ # are this engine's.
6
+ """CUDA device functions of the contact side of the analytic adjoint: impedance derivatives, the joint-limit row VJP,
7
+ the contact row VJP Psi_c, the per-dof pose cotangents of a contact Jacobian column, and the collision-primitive VJPs
8
+ of the mjlab model (plane-sphere, plane-capsule, sphere-sphere, sphere-capsule, capsule-capsule) with make_frame, the
9
+ normal option DK_ADJ_NORMAL and the near-parallel capsule option DK_ADJ_PARALLEL."""
10
+
11
+ import mujoco
12
+
13
+ from nablaengine.g1_engine import step
14
+
15
+
16
+ def check_model(m):
17
+ """The contact adjoint is for the mjlab model only: collision geoms are planes, spheres and capsules
18
+ (no boxes), and no dof has a frictionloss row."""
19
+ types = {int(m.geom_type[g]) for g in step.collision_geoms(m)}
20
+ from nablaengine.g1_engine import model_hooks
21
+ has_box, box_ok, _ = model_hooks.box_pairs(m)
22
+ assert not has_box or box_ok, "the adjoint has box contacts with planes, spheres, capsules and boxes (model_hooks)"
23
+ from nablaengine.g1_engine import cylinder
24
+ has_cyl, cyl_ok = cylinder.pairs(m)
25
+ assert not has_cyl or cyl_ok, "cylinder contacts with planes, spheres, capsules, cylinders and boxes only"
26
+ from nablaengine.g1_engine import mesh
27
+ has_mesh, mesh_ok = mesh.pairs(m)
28
+ assert not has_mesh or mesh_ok, "mesh contacts with planes, spheres, capsules, cylinders, boxes and meshes only"
29
+ assert {step.GEOM_TYPE[t] for t in types} <= {0, 1, 2, 3, 5, 6}, ("collision geoms other than plane / sphere / "
30
+ "capsule / box / cylinder / mesh")
31
+ planes = [g for g in step.collision_geoms(m) if int(m.geom_type[g]) == int(mujoco.mjtGeom.mjGEOM_PLANE)]
32
+ assert all(int(m.geom_bodyid[g]) == 0 for g in planes), "a plane not on the world body (it gets no cotangent)"
33
+
34
+
35
+ def header(m):
36
+ """#defines and checks of the contact adjoint for model m (asserts check_model); after step.step_header(m)."""
37
+ check_model(m)
38
+ return r"""
39
+ #ifndef DK_ADJ_NORMAL // default 3: frozen below eps (finite gradients, no 1 / nu singularity)
40
+ #define DK_ADJ_NORMAL 3 // normal derivative of the sphere core: 0 exact (MuJoCo Warp), 1 frozen frame,
41
+ #endif // 2 regularized kappa = 1 / max(nu, eps), 3 frozen below eps (kappa = nu < eps ? 0 : 1 / nu)
42
+ #ifndef DK_ADJ_NORMAL_EPS
43
+ #define DK_ADJ_NORMAL_EPS 1e-3f // m, the eps of DK_ADJ_NORMAL 2 and 3 (strict <)
44
+ #endif
45
+ #ifndef DK_ADJ_PARALLEL // near-parallel capsule-capsule with both segment parameters free: 1 holds the
46
+ #define DK_ADJ_PARALLEL (DK_ADJ_NORMAL != 0) // parameters constant where sin^2(theta) < DK_ADJ_PARALLEL_EPS (finite);
47
+ #endif // 0 exact (MuJoCo Warp). Default: on with a normal option, so the exact
48
+ // gradient mode (DK_ADJ_NORMAL 0) stays exact
49
+ #ifndef DK_ADJ_PARALLEL_EPS
50
+ #define DK_ADJ_PARALLEL_EPS 1.2e-3f // sin^2(theta) = |a1 x a2|^2 / (|a1|^2 |a2|^2) of DK_ADJ_PARALLEL 1 (strict <):
51
+ #endif // ~sin^2(2 degrees) (theta < 1.99 degrees)
52
+ static_assert(!HAS_BOX && NFLOSS == 0, "the contact adjoint is for the mjlab model: no boxes, no frictionloss rows");
53
+ // adj_contact_geom's branch bits (its return value; -1: a type combination without a VJP)
54
+ #define ADJ_BR_FREE1 1 // capsule-capsule: segment parameter x1 free (inside, not clamped)
55
+ #define ADJ_BR_FREE2 2 // capsule-capsule x2 / sphere-capsule t free
56
+ #define ADJ_BR_PARALLEL 4 // capsule-capsule parallel branch (|det| < 1e-15), the tape's slot = the candidate
57
+ #define ADJ_BR_FALLBACK 8 // plane-capsule: the projected axis is shorter than 0.5, the frame uses make_frame's basis
58
+ #define ADJ_BR_FRAME_Z 16 // the frame's basis vector is e_z (|n_y| >= 0.5), else e_y
59
+ """
60
+
61
+
62
+ DEVICE = r"""
63
+ // ---------------------------------------------------------------- impedance
64
+
65
+ // kbimp with the derivative of the impedance: k, b, imp from the forward's kbimp() itself (bitwise the same), and
66
+ // dimp = d imp / d pos on the branch kbimp took: sign(pos) imp_x / width, imp_x = (dmax - dmin) p y^(p-1) / m^(p-1)
67
+ // with (y, m) = (x, mid) for x <= mid and (1 - x, 1 - mid) above (x = |pos| / width); 0 where imp is constant (x <= 0,
68
+ // x >= 1, dmin == dmax) and where the forward's clamp to [dmin, dmax] changes the value (raw outside [dmin, dmax]; it
69
+ // only guards rounding). MuJoCo Warp's wp.clamp also drops the gradient when its float32 raw equals dmax, which happens
70
+ // for x within about 5e-4 of 1 (mjlab solimp; there imp_x is below 1e-3 of its peak): that float32 artifact is not
71
+ // copied. pow_imp: no powf for p = 1, 2
72
+ __device__ __forceinline__ void kbimp_d(const float* solref, const float* solimp, float pos, float h, float* k,
73
+ float* b, float* imp, float* dimp) {
74
+ kbimp(solref, solimp, pos, h, k, b, imp);
75
+ float dmin = fminf(fmaxf(solimp[0], 1e-4f), 0.9999f), dmax = fminf(fmaxf(solimp[1], 1e-4f), 0.9999f);
76
+ float width = fmaxf(1e-15f, solimp[2]), mid = fminf(fmaxf(solimp[3], 1e-4f), 0.9999f), power = fmaxf(1.f, solimp[4]);
77
+ float x = fabsf(pos) / width, d = 0.f;
78
+ if (!(dmin == dmax || solimp[2] <= 1e-15f) && x > 0.f && x < 1.f) {
79
+ if (power == 1.f) d = dmax - dmin;
80
+ else {
81
+ bool lo = x <= mid; // the forward's raw (unclamped) value on this branch, for the clamp test
82
+ float raw = imp_raw(x, dmin, dmax, mid, power, lo);
83
+ // 1 - x as (width - |pos|) / width: no cancellation of x's rounding near x = 1 (the derivative only)
84
+ float y = lo ? x : (width - fabsf(pos)) / width, ym = lo ? mid : 1.f - mid;
85
+ if (raw >= dmin && raw <= dmax) d = power * pow_imp(y, power - 1.f) / pow_imp(ym, power - 1.f) * (dmax - dmin);
86
+ }
87
+ }
88
+ *dimp = (pos < 0.f ? -d : d) / width;
89
+ }
90
+
91
+ // row impedance D = 1 / max(R, 1e-15), R = invw (1 - imp) / imp (the forward's expression in substep_pre), and its
92
+ // derivative dD = dimp / (invw (1 - imp)^2) (0 where the floor acts): with kbimp_d's dimp, dD = dD / dpos
93
+ __device__ __forceinline__ void efc_D_d(float invw, float imp, float dimp, float* D, float* dD) {
94
+ float R = invw * (1.f - imp) / imp, om = 1.f - imp;
95
+ *D = efc_D(invw, imp); // the forward's (step.py)
96
+ *dD = R > 1e-15f ? dimp / (invw * om * om) : 0.f;
97
+ }
98
+
99
+ // ---------------------------------------------------------------- joint limits
100
+
101
+ // one joint-limit row of hinge dof i in its quadratic zone (the tape's zone bit; inactive rows contribute nothing).
102
+ // sigma = +1 at the lower limit (pos = q_i - lo, J = +e_i), -1 at the upper (pos = hi - q_i, J = -e_i); a, v, lam: the
103
+ // dof's a*, qvel and lambda; k, b, imp, dimp from kbimp_d(c_jsolref, c_jsolimp, pos), D, dD from
104
+ // efc_D_d(c_dinvw[i], ...). x = J a* - aref = sigma a + k imp pos + b sigma v, Psi_e = D x sigma lam. Out: the row's
105
+ // terms of P_phi,i = dPsi_e / dq_i (through pos; MuJoCo Warp's res_dof of the row) and P_v,i = dPsi_e / dv_i (res_qvel)
106
+ __device__ __forceinline__ void limit_row_vjp(float sigma, float pos, float a, float v, float lam, float k, float b,
107
+ float imp, float dimp, float D, float dD, float* Pphi, float* Pv) {
108
+ float x = sigma * a + k * imp * pos + b * (sigma * v);
109
+ *Pphi = lam * (dD * x + D * (k * (imp + dimp * pos)));
110
+ *Pv = D * b * lam;
111
+ }
112
+
113
+ // ---------------------------------------------------------------- contact rows
114
+
115
+ // Psi_c VJP of one contact. In: the contact point's motions V_v = J_p v, V_a = J_p a*, V_lam = J_p lam (world, body 2
116
+ // relative to body 1), the frame fr (rows n, t1, t2), friction mu, condim dim (1 or 3), zone (bit e: row e on its
117
+ // quadratic zone, the tape's bits of the contact's rows), the distance d and its rows' impedance (one D for all rows of
118
+ // a contact): k, b, imp, dimp from kbimp_d(PSOLREF, PSOLIMP, d), D, dD from efc_D_d(invw_c, ...).
119
+ // Psi_c = sum_{e in zone} D x_e (u_e . V_lam), x_e = u_e . V_a + k imp d + b u_e . V_v.
120
+ // Out: W_v, W_a, W_lam = dPsi_c / dV_* (W_v = b W_a),
121
+ // dbar = dPsi_c / dd = sum_e (u_e . V_lam) [dD x_e + D k (imp + dimp d)], frbar = dPsi_c / dfr (rows nbar, t1bar,
122
+ // t2bar; from ubar_e = D x_e V_lam + D (u_e . V_lam)(V_a + b V_v)). A contact with no row in its zone has Psi_c = 0 and
123
+ // all outputs zero (MuJoCo Warp's _contact_any_active).
124
+ __device__ __forceinline__ void contact_psi_vjp(const float* Vv, const float* Va, const float* Vl, const float* fr,
125
+ float mu, int dim, unsigned zone, float d, float D, float dD, float k,
126
+ float b, float imp, float dimp, float* Wv, float* Wa, float* Wl,
127
+ float* dbar, float* frbar) {
128
+ float vf[3], af[3], lf[3]; // frame components
129
+ #pragma unroll
130
+ for (int j = 0; j < 3; j++) {
131
+ vf[j] = dot3(fr + 3 * j, Vv); af[j] = dot3(fr + 3 * j, Va); lf[j] = dot3(fr + 3 * j, Vl);
132
+ }
133
+ float g = k * imp * d, gd = k * (imp + dimp * d); // the reference acceleration's position term and its d-derivative
134
+ float cl[3] = {0.f, 0.f, 0.f}, ca[3] = {0.f, 0.f, 0.f}, db = 0.f; // frame components of W_lam, W_a
135
+ #pragma unroll
136
+ for (int e = 0; e < 4; e++) {
137
+ if (!((zone >> e) & 1u) || (e > 0 && dim != 3)) continue;
138
+ const int t = 1 + (e >> 1);
139
+ float sm = (e & 1) ? -mu : mu; // u_e = n + sm t_t (condim 1: n)
140
+ float uv = vf[0], ua = af[0], ul = lf[0];
141
+ if (dim == 3) { uv += sm * vf[t]; ua += sm * af[t]; ul += sm * lf[t]; }
142
+ float x = ua + g + b * uv, Dx = D * x, Dl = D * ul;
143
+ cl[0] += Dx; ca[0] += Dl;
144
+ if (dim == 3) { cl[t] += sm * Dx; ca[t] += sm * Dl; }
145
+ db += ul * (dD * x + D * gd);
146
+ }
147
+ #pragma unroll
148
+ for (int i = 0; i < 3; i++) {
149
+ Wl[i] = cl[0] * fr[i] + cl[1] * fr[3 + i] + cl[2] * fr[6 + i];
150
+ Wa[i] = ca[0] * fr[i] + ca[1] * fr[3 + i] + ca[2] * fr[6 + i];
151
+ Wv[i] = b * Wa[i];
152
+ }
153
+ float ab[3] = {Va[0] + b * Vv[0], Va[1] + b * Vv[1], Va[2] + b * Vv[2]};
154
+ #pragma unroll
155
+ for (int j = 0; j < 3; j++)
156
+ #pragma unroll
157
+ for (int i = 0; i < 3; i++) frbar[3 * j + i] = cl[j] * Vl[i] + ca[j] * ab[i];
158
+ *dbar = db;
159
+ }
160
+
161
+ // one support dof i of a contact: s = +1 on body 2's chain, -1 on body 1's (the dofs on exactly one chain); col = the
162
+ // dof's point-Jacobian column at the contact point p (rotational dof: z x (p - x), z its world axis, x its anchor: the
163
+ // origin X_b(i) of its body, X_1 for the three root rotations; root translation k: e_k, rot = false); v, a, lam: the
164
+ // dof's qvel, a* and lambda; W_* from contact_psi_vjp. Returns the dof's P_v term s col . W_v. With
165
+ // G = s (v W_v + a W_a + lam W_lam) = dPsi_c / dcol (MuJoCo Warp's _contact_scatter G), a rotational dof adds the pose
166
+ // cotangents of its body (root rotations: body 1) fbar += z x G, tbar += z x ((p - x) x G), and pbar += G x z (the
167
+ // contact point's cotangent through the Jacobian; contact_pbar_motion gives its sum over the support in closed form)
168
+ __device__ __forceinline__ float contact_dof_vjp(float s, const float* col, float v, float a, float lam,
169
+ const float* Wv, const float* Wa, const float* Wl, bool rot,
170
+ const float* z, const float* x, const float* p, float* fbar,
171
+ float* tbar, float* pbar) {
172
+ if (rot) {
173
+ float G[3], r[3], u[3], w[3], t[3];
174
+ #pragma unroll
175
+ for (int k = 0; k < 3; k++) { G[k] = s * (v * Wv[k] + a * Wa[k] + lam * Wl[k]); r[k] = p[k] - x[k]; }
176
+ cross(z, G, u);
177
+ cross(r, G, w);
178
+ cross(z, w, t);
179
+ #pragma unroll
180
+ for (int k = 0; k < 3; k++) { fbar[k] += u[k]; tbar[k] += t[k]; pbar[k] -= u[k]; }
181
+ }
182
+ return s * dot3(col, Wv);
183
+ }
184
+
185
+ // the contact point's cotangent through the Jacobian, summed over the support: sum_i G_i x z_i = W_v x Om_v
186
+ // + W_a x Om_a + W_lam x Om_lam with Om_* = sum over the rotational support dofs of s_i z_i (v_i, a*_i, lam_i): the
187
+ // angular parts of the contact's relative spatial motions (MuJoCo Warp's contact_V / A / Z top); adds to pbar
188
+ __device__ __forceinline__ void contact_pbar_motion(const float* Wv, const float* Wa, const float* Wl, const float* Omv,
189
+ const float* Oma, const float* Oml, float* pbar) {
190
+ float u[3];
191
+ cross(Wv, Omv, u);
192
+ for (int k = 0; k < 3; k++) pbar[k] += u[k];
193
+ cross(Wa, Oma, u);
194
+ for (int k = 0; k < 3; k++) pbar[k] += u[k];
195
+ cross(Wl, Oml, u);
196
+ for (int k = 0; k < 3; k++) pbar[k] += u[k];
197
+ }
198
+
199
+ // ---------------------------------------------------------------- collision geometry
200
+
201
+ // kappa(nu) of the sphere core's normal derivative kappa (I - n n') (DK_ADJ_NORMAL)
202
+ __device__ __forceinline__ float adj_kappa(float nu) {
203
+ #if DK_ADJ_NORMAL == 0
204
+ return 1.f / nu; // exact: (I - n n') / nu, MuJoCo Warp
205
+ #elif DK_ADJ_NORMAL == 1
206
+ return 0.f; // frame frozen in the backward (distance and contact point keep their derivatives)
207
+ #elif DK_ADJ_NORMAL == 2
208
+ return 1.f / fmaxf(nu, DK_ADJ_NORMAL_EPS); // regularized: exact for nu >= eps, continuous in nu
209
+ #else
210
+ return nu < DK_ADJ_NORMAL_EPS ? 0.f : 1.f / nu; // frozen below eps only
211
+ #endif
212
+ }
213
+
214
+ // kappa(nu) nu: the factor of the normal's derivative where it is written without 1 / nu (capsule-capsule, both
215
+ // parameters free); 1 for the exact derivative
216
+ __device__ __forceinline__ float adj_kappa_nu(float nu) {
217
+ #if DK_ADJ_NORMAL == 0
218
+ return 1.f;
219
+ #elif DK_ADJ_NORMAL == 1
220
+ return 0.f;
221
+ #elif DK_ADJ_NORMAL == 2
222
+ return nu / fmaxf(nu, DK_ADJ_NORMAL_EPS);
223
+ #else
224
+ return nu < DK_ADJ_NORMAL_EPS ? 0.f : 1.f;
225
+ #endif
226
+ }
227
+
228
+ // make_frame VJP: fr = make_frame(n) (rows n, b, c; b = normalize(e - n (n . e)), e = e_y if -0.5 < n_y < 0.5 else e_z,
229
+ // c = n x b; n a unit vector), frbar = dL/d(n, b, c) -> nbar = dL/dn (the frame's own n row included):
230
+ // nbar = nbar_0 + b x cbar, btot = bbar + cbar x n, bt = (I - b b') btot / beta, nbar -= (n . e) bt + e (n . bt)
231
+ __device__ __forceinline__ void make_frame_vjp(const float* fr, const float* frbar, float* nbar) {
232
+ const float *n = fr, *b = fr + 3, *cb = frbar + 6;
233
+ bool ey = -0.5f < n[1] && n[1] < 0.5f; // the forward's test
234
+ float ne = ey ? n[1] : n[2], bt[3] = {-n[0] * ne, (ey ? 1.f : 0.f) - n[1] * ne, (ey ? 0.f : 1.f) - n[2] * ne};
235
+ float beta = sqrtf(dot3(bt, bt)), u[3], w[3];
236
+ cross(cb, n, u);
237
+ for (int k = 0; k < 3; k++) u[k] += frbar[3 + k]; // btot
238
+ float bu = dot3(b, u);
239
+ for (int k = 0; k < 3; k++) bt[k] = (u[k] - b[k] * bu) / beta;
240
+ cross(b, cb, w);
241
+ float nb = dot3(n, bt);
242
+ for (int k = 0; k < 3; k++) nbar[k] = frbar[k] + w[k] - ne * bt[k];
243
+ nbar[ey ? 1 : 2] -= nb;
244
+ }
245
+
246
+ // sphere core VJP: (dist, pos, n) = sphere_sphere(c1, r1, c2, r2), i.e. nu = |c2 - c1|, n = (c2 - c1) / nu,
247
+ // dist = nu - r1 - r2, pos = c1 + n (r1 + dist / 2). In: n, nu, dist, r1 and the cotangents dbar, pbar, nbar (nbar: the
248
+ // normal's own, e.g. make_frame_vjp's). Adds c1bar, c2bar: v = c2 - c1, vbar = n dtot + kappa(nu) (I - n n') ntot with
249
+ // ntot = nbar + (r1 + dist / 2) pbar, dtot = dbar + (n . pbar) / 2; c2bar += vbar, c1bar += pbar - vbar. nu = 0
250
+ // (n = e_x): no derivative through v (MuJoCo Warp's safe_sqrt)
251
+ __device__ __forceinline__ void sphere_core_vjp(const float* n, float nu, float dist, float r1, float dbar,
252
+ const float* pbar, const float* nbar, float* c1bar, float* c2bar) {
253
+ float hp = r1 + 0.5f * dist, vb[3] = {0.f, 0.f, 0.f};
254
+ if (nu > 0.f) {
255
+ float nt[3], dt = dbar + 0.5f * dot3(n, pbar), kap = adj_kappa(nu);
256
+ for (int k = 0; k < 3; k++) nt[k] = nbar[k] + hp * pbar[k];
257
+ float nn = dot3(n, nt);
258
+ for (int k = 0; k < 3; k++) vb[k] = n[k] * dt + kap * (nt[k] - n[k] * nn);
259
+ }
260
+ for (int k = 0; k < 3; k++) { c2bar[k] += vb[k]; c1bar[k] += pbar[k] - vb[k]; }
261
+ }
262
+
263
+ // One contact's geometry from the two geoms' world poses (geom_poses: s.gx, s.gq): the replay and, with cot, its VJP.
264
+ // t1 <= t2: engine geom types of the pair's geoms g1, g2 (0 plane, 1 sphere, 2 capsule; c_gtype[PG1 / PG2]), sz1, sz2
265
+ // their sizes (c_gsize + 3 g), slot: the tape's (plane-capsule end 0: +axis, 1: -axis; parallel capsule-capsule
266
+ // candidate 0..3; else 0). Replay (always): dist, pos[3], fr[9] = the forward's (collide_pair) bitwise, and nu = the
267
+ // sphere core's centre distance |c2 - c1| before the radii (the tape's min_nu; +inf for plane contacts): by collide_pair's
268
+ // own functions (step.py: zaxis_rn, plane_point, plane_capsule_frame, capsule_end, segment_point, capcap_*,
269
+ // sphere_sphere, make_frame; explicit roundings, so the same bits in this kernel as in the forward's). The primitive's
270
+ // branches are decided again here, on that arithmetic (sphere-capsule t clamp, capsule-capsule clamp cascade with its
271
+ // free set, plane-capsule frame fallback, make_frame's basis), as MuJoCo Warp's _narrowphase_recompute does. cot (null:
272
+ // replay only) = (dbar, pbar[3], frbar[9]) = dL/d(dist, pos, frame rows); then gb[12] = (xbar1, tbar1,
273
+ // xbar2, tbar2): the geoms' pose cotangents (world; torque form, see the module docstring); the plane's are 0. The
274
+ // normal derivative of the sphere core follows DK_ADJ_NORMAL. Returns the ADJ_BR_* branch bits, -1 for a type
275
+ // combination without a VJP (boxes; the replay outputs are then undefined). One copy of the code: called twice per
276
+ // contact by the adjoint (replay before the row VJPs, VJP after)
277
+ __device__ __noinline__ int adj_contact_geom(int t1, int t2, int slot, const float* p1, const float* q1,
278
+ const float* sz1, const float* p2, const float* q2, const float* sz2,
279
+ float* dist, float* pos, float* fr, float* nu, const float* cot,
280
+ float* gb) {
281
+ int br = 0;
282
+ *nu = __int_as_float(0x7f800000);
283
+ if (cot)
284
+ for (int k = 0; k < 12; k++) gb[k] = 0.f;
285
+ if (t1 == 0) { // plane (the floor, static): normal = its z axis; the frame does not depend on the other geom...
286
+ float n[3];
287
+ zaxis_rn(q1, n);
288
+ if (t2 == 1) { // plane-sphere
289
+ *dist = plane_point(p1, n, p2, sz2[0], pos);
290
+ make_frame(n, fr);
291
+ if (!(-0.5f < n[1] && n[1] < 0.5f)) br |= ADJ_BR_FRAME_Z;
292
+ if (cot) { // xbar_s = pbar + n (dbar - (n . pbar) / 2); the frame is constant
293
+ float pn = dot3(n, cot + 1);
294
+ for (int k = 0; k < 3; k++) gb[6 + k] = cot[1 + k] + n[k] * (cot[0] - 0.5f * pn);
295
+ }
296
+ return br;
297
+ }
298
+ if (t2 != 2) return -1;
299
+ // plane-capsule: ...except here, where t1 follows the capsule axis projected on the plane (fallback when short)
300
+ float axis[3];
301
+ zaxis_rn(q2, axis);
302
+ const float bn = plane_capsule_frame(n, axis, fr), *b = fr + 3;
303
+ if (bn < 0.5f) {
304
+ br |= ADJ_BR_FALLBACK;
305
+ if (!(-0.5f < n[1] && n[1] < 0.5f)) br |= ADJ_BR_FRAME_Z;
306
+ }
307
+ float sg = slot == 0 ? 1.f : -1.f, ce[3]; // the end slot (the forward's e)
308
+ capsule_end(p2, axis, sz2[1], slot, ce);
309
+ *dist = plane_point(p1, n, ce, sz2[0], pos);
310
+ if (cot) { // end ce = x_c + sg l a: cbar = pbar + n (dbar - (n . pbar) / 2); abar = sg l cbar + frame part
311
+ float pn = dot3(n, cot + 1), ab[3], u[3];
312
+ for (int k = 0; k < 3; k++) {
313
+ gb[6 + k] = cot[1 + k] + n[k] * (cot[0] - 0.5f * pn);
314
+ ab[k] = sg * sz2[1] * gb[6 + k];
315
+ }
316
+ if (!(br & ADJ_BR_FALLBACK)) { // t1 = normalize(a - n (n . a)), t2 = n x t1: btot = t1bar + t2bar x n, then
317
+ cross(cot + 10, n, u); // abar += (I - n n') (I - t1 t1') btot / beta
318
+ for (int k = 0; k < 3; k++) u[k] += cot[7 + k];
319
+ float bu = dot3(b, u);
320
+ for (int k = 0; k < 3; k++) u[k] -= b[k] * bu;
321
+ float un = dot3(n, u);
322
+ for (int k = 0; k < 3; k++) ab[k] += (u[k] - n[k] * un) / bn;
323
+ }
324
+ cross(axis, ab, gb + 9);
325
+ }
326
+ return br;
327
+ }
328
+ float n[3], c1b[3] = {0.f, 0.f, 0.f}, c2b[3] = {0.f, 0.f, 0.f}, nb[3];
329
+ if (t1 == 1 && t2 == 1) { // sphere-sphere: the core on the centres
330
+ *nu = sphere_sphere(p1, sz1[0], p2, sz2[0], dist, pos, n);
331
+ make_frame(n, fr);
332
+ if (!(-0.5f < n[1] && n[1] < 0.5f)) br |= ADJ_BR_FRAME_Z;
333
+ if (cot) {
334
+ make_frame_vjp(fr, cot + 4, nb);
335
+ sphere_core_vjp(n, *nu, *dist, sz1[0], cot[0], cot + 1, nb, gb, gb + 6);
336
+ }
337
+ return br;
338
+ }
339
+ if (t1 == 1 && t2 == 2) { // sphere-capsule: closest point A + t B of the segment, then the core
340
+ float axis[3], a[3], ab[3], ap[3], pt[3], gam, t; // gam: MuJoCo Warp's 1e-6 regularizer (kept)
341
+ zaxis_rn(q2, axis);
342
+ const float raw = segment_point(p1, p2, axis, sz2[1], a, ab, ap, &gam, &t, pt);
343
+ *nu = sphere_sphere(p1, sz1[0], pt, sz2[0], dist, pos, n);
344
+ make_frame(n, fr);
345
+ if (!(-0.5f < n[1] && n[1] < 0.5f)) br |= ADJ_BR_FRAME_Z;
346
+ bool free_t = raw >= 0.f && raw < 1.f; // wp.clamp passes the gradient for lo <= raw < hi
347
+ if (free_t) br |= ADJ_BR_FREE2;
348
+ if (cot) {
349
+ make_frame_vjp(fr, cot + 4, nb);
350
+ sphere_core_vjp(n, *nu, *dist, sz1[0], cot[0], cot + 1, nb, gb, c2b); // c2b = ptbar
351
+ float Ab[3], Bb[3], tb = dot3(ab, c2b);
352
+ for (int k = 0; k < 3; k++) { Ab[k] = c2b[k]; Bb[k] = t * c2b[k]; }
353
+ if (free_t) { // t = (x_s - A) . B / gam: alpha bar, gam bar
354
+ float al = tb / gam, gm = -t * tb / gam;
355
+ for (int k = 0; k < 3; k++) {
356
+ gb[k] += al * ab[k]; Ab[k] -= al * ab[k]; Bb[k] += al * ap[k] + 2.f * gm * ab[k];
357
+ }
358
+ }
359
+ float abar[3]; // A = x_c - l a, B = 2 l a
360
+ for (int k = 0; k < 3; k++) { gb[6 + k] = Ab[k]; abar[k] = sz2[1] * (2.f * Bb[k] - Ab[k]); }
361
+ cross(axis, abar, gb + 9);
362
+ }
363
+ return br;
364
+ }
365
+ if (t1 != 2 || t2 != 2) return -1;
366
+ // capsule-capsule: segment parameters (x1, x2) by the forward's clamp cascade (or the parallel candidate `slot`); the
367
+ // free ones solve their rows of G x = h, G = [ma mb; mb mc], h = (u, v), the others are fixed at +-1
368
+ CapCap cc;
369
+ capcap_setup(p1, q1, sz1[1], p2, q2, sz2[1], cc);
370
+ const float *a1 = cc.a1, *a2 = cc.a2, *dif = cc.dif;
371
+ const float ma = cc.ma, mb = cc.mb, mc = cc.mc, det = cc.det;
372
+ float x1, x2, raw;
373
+ bool f1, f2; // a clamp to [-1, 1] leaves x free for -1 <= raw < 1 (wp.clamp's gradient rule)
374
+ if (fabsf(det) >= 1e-15f) capcap_params(cc, &x1, &x2, &f1, &f2, &raw);
375
+ else { // parallel: candidate e = slot of the forward's loop
376
+ br |= ADJ_BR_PARALLEL;
377
+ capcap_candidate(cc, slot, &x1, &x2, &f1, &f2, &raw);
378
+ }
379
+ (void)raw;
380
+ if (f1) br |= ADJ_BR_FREE1;
381
+ if (f2) br |= ADJ_BR_FREE2;
382
+ *nu = capcap_core(p1, p2, cc, x1, x2, sz1[0], sz2[0], dist, pos, n);
383
+ make_frame(n, fr);
384
+ if (!(-0.5f < n[1] && n[1] < 0.5f)) br |= ADJ_BR_FRAME_Z;
385
+ if (cot) {
386
+ make_frame_vjp(fr, cot + 4, nb);
387
+ // c_k = x_k + s_k x_k: xbar_k += cbar_k, sbar_k += x_k cbar_k, x_k bar = s_k . cbar_k (free ones only); then
388
+ // z = G_FF^-1 xbar_F (0 off F), hbar = z, Gbar = -z x' (sym.): mabar = -z1 x1, mbbar = -(z1 x2 + z2 x1),
389
+ // mcbar = -z2 x2
390
+ float s1b[3], s2b[3], xb1, xb2, w[3];
391
+ cross(a1, a2, w);
392
+ float ww = dot3(w, w); // = det = ma mc - mb^2 without its cancellation
393
+ // exactly parallel float32 axes can still take the non-parallel branch (det is FMA rounding noise, >= 1e-15): w
394
+ // is then 0, so below sin^2(theta) = 1e-12 the general chain runs and G is inverted with the forward's det, as
395
+ // MuJoCo Warp does (large but finite)
396
+ bool wok = ww > 1e-12f * ma * mc;
397
+ #if DK_ADJ_PARALLEL
398
+ // near parallel with both parameters free (DK_ADJ_PARALLEL): the closest points slide along the axes
399
+ // with derivatives of order nu / sin^2(theta) (a tilt of one axis against the other), the normal n = sg w / |w|
400
+ // turns with 1 / sin(theta). Below the threshold x1, x2 are held constant (no z through G^-1, the general chain
401
+ // below): the contact moves with the two material points p_k + a_k x_k, its frame by the sphere core's
402
+ // kappa(nu) (I - n n'). By the envelope theorem the distance's derivative stays the exact one (d dist / dx = 0 at
403
+ // the interior minimum); what is approximated is the contact point's sliding and the normal's turning
404
+ if (f1 && f2 && ww < DK_ADJ_PARALLEL_EPS * ma * mc) f1 = f2 = false;
405
+ #endif
406
+ if (f1 && f2 && *nu > 0.f && wok) {
407
+ // both parameters free (C0): c2 - c1 is normal to both axes, so n = sg w / |w| exactly and the normal's
408
+ // derivative goes to the axes alone, dn = sg (I - n n') dw / |w|. The general chain (sphere_core_vjp, then x
409
+ // through G) gives the same in exact arithmetic but as a sum of terms of order 1/nu that cancel to order 1
410
+ // (relative errors up to 1e-3 at nu = 5 mm in float32); here no 1/nu appears. DK_ADJ_NORMAL scales the normal
411
+ // path by kappa(nu) nu
412
+ const float* pb = cot + 1;
413
+ float hp = sz1[0] + 0.5f * (*dist), dt = cot[0] + 0.5f * dot3(n, pb), t[3], u1[3], u2[3];
414
+ for (int k = 0; k < 3; k++) t[k] = nb[k] + hp * pb[k];
415
+ float nt = dot3(n, t), f = adj_kappa_nu(*nu) * rsqrtf(ww);
416
+ if (dot3(n, w) < 0.f) f = -f;
417
+ for (int k = 0; k < 3; k++) t[k] = f * (t[k] - n[k] * nt); // sg (I - n n') ntot / |w|
418
+ cross(a2, t, u1);
419
+ cross(t, a1, u2);
420
+ for (int k = 0; k < 3; k++) { // radial: dnu = n . (dc2 - dc1) with n . s_k dx_k = 0; pos = c1 + n (r1 + d / 2)
421
+ c2b[k] = n[k] * dt; c1b[k] = pb[k] - c2b[k];
422
+ s1b[k] = x1 * c1b[k] + u1[k]; s2b[k] = x2 * c2b[k] + u2[k];
423
+ }
424
+ xb1 = dot3(a1, pb); xb2 = 0.f; // only pos moves with x1 (c1); the distance and the normal are stationary in x
425
+ } else {
426
+ sphere_core_vjp(n, *nu, *dist, sz1[0], cot[0], cot + 1, nb, c1b, c2b);
427
+ for (int k = 0; k < 3; k++) { s1b[k] = x1 * c1b[k]; s2b[k] = x2 * c2b[k]; }
428
+ xb1 = f1 ? dot3(a1, c1b) : 0.f; xb2 = f2 ? dot3(a2, c2b) : 0.f;
429
+ }
430
+ float z1 = 0.f, z2 = 0.f;
431
+ float gd = wok ? ww : det;
432
+ if (f1 && f2) { z1 = (mc * xb1 - mb * xb2) / gd; z2 = (ma * xb2 - mb * xb1) / gd; }
433
+ else if (f1) z1 = xb1 / ma;
434
+ else if (f2) z2 = xb2 / mc;
435
+ float mab = -z1 * x1, mbb = -(z1 * x2 + z2 * x1), mcb = -z2 * x2, db[3];
436
+ for (int k = 0; k < 3; k++) { // ma = s1.s1, mb = -s1.s2, mc = s2.s2, u = -s1.dif, v = s2.dif, dif = x_1 - x_2
437
+ s1b[k] += 2.f * mab * a1[k] - mbb * a2[k] - z1 * dif[k];
438
+ s2b[k] += 2.f * mcb * a2[k] - mbb * a1[k] + z2 * dif[k];
439
+ db[k] = -z1 * a1[k] + z2 * a2[k];
440
+ gb[k] = c1b[k] + db[k];
441
+ gb[6 + k] = c2b[k] - db[k];
442
+ }
443
+ cross(a1, s1b, gb + 3); // s_k = l_k R_k e_z: tbar_k = s_k x sbar_k
444
+ cross(a2, s2b, gb + 9);
445
+ }
446
+ return br;
447
+ }
448
+
449
+ // adj_contact_geom for contact (pair, slot) of the engine's pair table, from the collision geoms' world poses
450
+ // gx[NGEOMC][3], gq[NGEOMC][4] (struct Sim's gx / gq layout, or the adjoint's copy)
451
+ __device__ __forceinline__ int adj_pair_geom(int pair, int slot, const float (*gx)[3], const float (*gq)[4],
452
+ float* dist, float* pos, float* fr, float* nu, const float* cot,
453
+ float* gb) {
454
+ int g1 = PG1(pair), g2 = PG2(pair);
455
+ return adj_contact_geom(c_gtype[g1], c_gtype[g2], slot, gx[g1], gq[g1], c_gsize + 3 * g1, gx[g2], gq[g2],
456
+ c_gsize + 3 * g2, dist, pos, fr, nu, cot, gb);
457
+ }
458
+
459
+ // a geom's pose cotangent (xbar, tbar = gb + 6 j of adj_contact_geom) onto its body's:
460
+ // x_g = X_b + R_b g0, R_g = R_b R_g0, so fbar_b += xbar, tbar_b += tbar + (x_g - X_b) x xbar; xg, Xb: the geom's centre
461
+ // and the body origin (the world body takes no cotangent: skip it)
462
+ __device__ __forceinline__ void geom_to_body_vjp(const float* xg, const float* Xb, const float* xbar, const float* tbar,
463
+ float* fbar_b, float* tbar_b) {
464
+ float r[3] = {xg[0] - Xb[0], xg[1] - Xb[1], xg[2] - Xb[2]}, u[3];
465
+ cross(r, xbar, u);
466
+ for (int k = 0; k < 3; k++) { fbar_b[k] += xbar[k]; tbar_b[k] += tbar[k] + u[k]; }
467
+ }
468
+ """
469
+
470
+
471
+
472
+ TERRAIN_DEVICE = r"""
473
+ // A terrain contact (virtual pair NPAIR + t: geom 1 the static terrain, geom 2 the robot geom of type gt, size sz, pose
474
+ // p2 / q2) with tape slot k | element << 8 (aux: a native heightfield contact's candidate, the tape's taux): the replay (dist, pos, fr: the forward's bits, by the same __noinline__
475
+ // geometry, step.TERRAIN_DEVICE) and, with cot = (dbar, pbar, frbar), gb[6..11] = the robot geom's pose cotangents
476
+ // (gb[0..5] = 0). The contact's point on the robot geom is a material point c = p2 + w l axis: the sphere centre (w = 0),
477
+ // a capsule_box candidate (w: its segment parameter) or a heightfield sample point (w fixed); w is held constant (exact
478
+ // at the segment ends and for the distance at an interior minimum, by the envelope theorem; the candidate's sliding
479
+ // along the axis is left out). Box: dist = |c_l - clamp(c_l)| - r with the normal u = (c_l - cl) / |.| (outside, in the
480
+ // box frame; its derivative (I - u u') P / |.| on the clamped axes P, scaled as the sphere core's: adj_kappa), or the
481
+ // nearest face's constant normal (inside); heightfield: the triangle's plane, dist = n . c - const, constant normal.
482
+ // Either way pos = c - n (r + dist / 2) up to the clamped part. Returns the ADJ_BR_* bits (-1: not a contact)
483
+ __device__ __noinline__ int adj_terrain_geom(int slot, unsigned aux, int gt, const float* sz, const float* p2,
484
+ const float* q2, float* dist, float* pos, float* fr, float* nu,
485
+ const float* cot, float* gb) {
486
+ const int k = slot & 255, e = slot >> 8, nbox = g_ter.grid ? int(g_ter.grid[5]) : 0;
487
+ const bool box = e < nbox || e >= OBJ_E0; // a terrain box or a per-world object slot (ter_box)
488
+ *nu = __int_as_float(0x7f800000);
489
+ if (cot)
490
+ for (int t = 0; t < 12; t++) gb[t] = 0.f;
491
+ float n[3], c[3] = {p2[0], p2[1], p2[2]}, axis[3] = {0.f, 0.f, 0.f}, w = 0.f, qp[3];
492
+ bool point_n = false; // native heightfield HF_POINT: n = (c - qp) / |c - qp|
493
+ if (gt == 2) zaxis_rn(q2, axis);
494
+ if (box) {
495
+ const float* b = ter_box(e);
496
+ if (gt == 2) {
497
+ float segs[2];
498
+ terrain_capbox_segs(p2, axis, sz[1], b, segs);
499
+ w = segs[k];
500
+ capbox_point(p2, axis, sz[1], b, w, c);
501
+ }
502
+ terrain_sphere_box(c, sz[0], b, dist, pos, n);
503
+ } else {
504
+ #if TERRAIN_HF_NATIVE
505
+ // the native contact: its candidate (aux: the tape's taux, HfCand.pid) recomputed from its prism alone
506
+ (void)k;
507
+ HfCon con[1];
508
+ if (!hfield_native_one(e - nbox, gt, sz, p2, q2, aux, con)) return -1;
509
+ const int k1 = 0;
510
+ const float* hh = g_ter.hfh + 16 * (e - nbox);
511
+ *dist = con[k1].dist;
512
+ hf_world_point(hh, con[k1].pos, pos);
513
+ hf_mv3(hh + 3, con[k1].n, n);
514
+ if (gt == 2) w = 2.f * con[k1].t - 1.f;
515
+ if (con[k1].type == HF_POINT) { // normal from the fixed prism point q to the core point
516
+ hf_world_point(hh, con[k1].q, qp);
517
+ point_n = true;
518
+ }
519
+ #else
520
+ if (!terrain_hfield_point(e - nbox, gt, sz, p2, q2, k, dist, pos, n)) return -1;
521
+ if (gt == 2) w = TERRAIN_CAP_PTS > 1 ? -1.f + float(k) * 2.f / float(TERRAIN_CAP_PTS - 1) : 0.f;
522
+ #endif
523
+ }
524
+ make_frame(n, fr);
525
+ const int br = (-0.5f < n[1] && n[1] < 0.5f) ? 0 : ADJ_BR_FRAME_Z;
526
+ if (!cot) return br;
527
+ const float* pb = cot + 1;
528
+ float cb[3]; // the material point's cotangent (world)
529
+ bool fixed_n = !box;
530
+ if (box) {
531
+ const float *b = ter_box(e), *R = b + 3, *bs = b + 12;
532
+ float d[3] = {c[0] - b[0], c[1] - b[1], c[2] - b[2]}, cl[3], u[3], P[3], pbl[3], cbl[3];
533
+ mtv3(R, d, cl);
534
+ for (int t = 0; t < 3; t++) {
535
+ float q = fmaxf(-bs[t], fminf(bs[t], cl[t]));
536
+ u[t] = cl[t] - q;
537
+ P[t] = q != cl[t] ? 1.f : 0.f;
538
+ }
539
+ float dd = sqrtf(dot3(u, u));
540
+ if (dd <= 1e-15f) fixed_n = true; // inside: the nearest face's normal
541
+ else {
542
+ float nbar[3], nbl[3], ub[3];
543
+ mtv3(R, pb, pbl);
544
+ make_frame_vjp(fr, cot + 4, nbar);
545
+ mtv3(R, nbar, nbl);
546
+ for (int t = 0; t < 3; t++) { u[t] /= dd; ub[t] = nbl[t] - 0.5f * sz[0] * pbl[t]; }
547
+ const float uu = dot3(u, ub), kap = adj_kappa(dd);
548
+ for (int t = 0; t < 3; t++)
549
+ cbl[t] = u[t] * cot[0] + 0.5f * (2.f - P[t]) * pbl[t] + P[t] * kap * (ub[t] - u[t] * uu);
550
+ mv3(R, cbl, cb);
551
+ }
552
+ }
553
+ if (point_n) { // the sphere core on (qp, c): nu = |c - qp| = dist + r
554
+ float nbar[3], qb[3] = {0.f, 0.f, 0.f};
555
+ make_frame_vjp(fr, cot + 4, nbar);
556
+ for (int t = 0; t < 3; t++) cb[t] = 0.f;
557
+ sphere_core_vjp(n, *dist + sz[0], *dist, 0.f, cot[0], pb, nbar, qb, cb);
558
+ fixed_n = false;
559
+ }
560
+ if (fixed_n) { // dist = n . c - const, pos = c - n (r + dist / 2): cbar = pbar - n (n . pbar) / 2 + n dbar
561
+ const float pn = dot3(n, pb);
562
+ for (int t = 0; t < 3; t++) cb[t] = pb[t] - 0.5f * n[t] * pn + n[t] * cot[0];
563
+ }
564
+ for (int t = 0; t < 3; t++) gb[6 + t] = cb[t];
565
+ if (gt == 2) { // c = p2 + w l axis: axis bar = w l cbar, as a torque
566
+ float ab[3];
567
+ for (int t = 0; t < 3; t++) ab[t] = w * sz[1] * cb[t];
568
+ cross(axis, ab, gb + 9);
569
+ }
570
+ return br;
571
+ }
572
+
573
+ """
574
+
575
+ def source(m):
576
+ """header(m) + DEVICE: the contact adjoint's device code for model m, to place after step.STEP_DEVICE."""
577
+ return header(m) + DEVICE