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,1158 @@
1
+ """Convex contacts with cylinders for the G1 engine (model_hooks): capsule-cylinder, cylinder-cylinder and cylinder-box
2
+ pairs as MuJoCo Warp 3.17's native CCD (mujoco_warp/_src/collision_convex.py ccd_kernel, collision_gjk.py gjk_phase,
3
+ epa_phase, multicontact with the cylinder's caps as 16-gons and the capsule's segment as an edge; Copyright 2025 The
4
+ Newton Developers, Apache License 2.0), margin and gap 0, multiccd on (MuJoCo's default), in their order of operations."""
5
+ import math
6
+ import re
7
+
8
+ import mujoco
9
+ import numpy as np
10
+
11
+ TYPES = ((2, 5), (5, 5), (5, 3), (1, 6), (2, 6), (5, 6), (3, 6), (6, 6))
12
+ COND = "((t1 == 2 && t2 == 5) || (t1 == 5 && (t2 == 5 || t2 == 3)) || (t2 == 6 && t1 != 0))"
13
+
14
+
15
+ def _lit(x):
16
+ t = f"{np.float32(x):.9g}"
17
+ return (t if ("." in t or "e" in t) else t + ".0") + "f"
18
+
19
+
20
+ def _cs16():
21
+ return (", ".join(_lit(math.cos(i * math.pi / 8.0)) for i in range(16)),
22
+ ", ".join(_lit(math.sin(i * math.pi / 8.0)) for i in range(16)))
23
+
24
+
25
+ def header(m):
26
+ """#defines of the convex CCD (the model's ccd_iterations and ccd_tolerance: MuJoCo Warp's EPA uses ccd_iterations
27
+ when a convex pair other than box-box exists, which these are); with mesh collision geoms the multicontact's
28
+ buffers (MuJoCo Warp's npolygonmax / nmeshdegmax: the largest polygon and vertex degree of the meshes)."""
29
+ from nablaengine.g1_engine import mesh
30
+ mt = mesh.tables(m)
31
+ sizes = (f"#define CY_NPOLY {max(16, mt['poly_max'])}\n#define CY_NDEG {max(3, mt['deg_max'])}\n#define CY_HAS_MESH 1\n"
32
+ if mt is not None else "")
33
+ return (f"#define CY_GJK_ITERATIONS {int(m.opt.ccd_iterations)}\n"
34
+ f"#define CY_EPA_ITERATIONS {int(m.opt.ccd_iterations)}\n"
35
+ f"#define CY_CCD_TOLERANCE {float(m.opt.ccd_tolerance):.9g}f\n" + sizes)
36
+
37
+
38
+ def pairs(m):
39
+ """Whether model m has a capsule-cylinder, cylinder-cylinder, cylinder-box pair or a mesh with a sphere, capsule,
40
+ cylinder, box or mesh."""
41
+ G = mujoco.mjtGeom
42
+ mesh = int(G.mjGEOM_MESH)
43
+ want = {tuple(sorted(x)) for x in ((int(G.mjGEOM_CAPSULE), int(G.mjGEOM_CYLINDER)),
44
+ (int(G.mjGEOM_CYLINDER), int(G.mjGEOM_CYLINDER)),
45
+ (int(G.mjGEOM_CYLINDER), int(G.mjGEOM_BOX)))}
46
+ want |= {tuple(sorted((int(t), mesh))) for t in (G.mjGEOM_SPHERE, G.mjGEOM_CAPSULE, G.mjGEOM_CYLINDER, G.mjGEOM_BOX,
47
+ G.mjGEOM_MESH)}
48
+ return any(tuple(sorted((int(m.geom_type[m.pair_geom1[p]]), int(m.geom_type[m.pair_geom2[p]])))) in want
49
+ for p in range(m.npair))
50
+
51
+
52
+ def core_text():
53
+ """ccd.DEVICE's helpers, support, GJK and EPA (to epa_witness), the cylinder's support added, its macros renamed
54
+ (CY_*: this module's iteration counts)."""
55
+ from nablaengine import ccd
56
+ src = ccd.DEVICE
57
+ end = src.index("// ------------------------------------------------------------------------------------- multicontact")
58
+ body = src[:end]
59
+ old = " return sp; // (no meshes in this module)\n}"
60
+ new = """ if (g.type == 5) { // cylinder (g1_engine.cylccd: MuJoCo Warp 3.17's support)
61
+ f3 res = mk3(0.f, 0.f, 0.f);
62
+ float d = sqrtf(ld.x * ld.x + ld.y * ld.y);
63
+ if (d > CV_MINVAL) {
64
+ float scl = g.size.x / d;
65
+ res.x = ld.x * scl;
66
+ res.y = ld.y * scl;
67
+ }
68
+ res.z = ld.z >= 0.f ? g.size.y : -g.size.y;
69
+ sp.vidx = ld.z >= 0.f ? 0 : 1;
70
+ sp.point = rmul(g.R, res) + g.pos;
71
+ return sp;
72
+ }
73
+ return sp;
74
+ }"""
75
+ if body.count(old) != 1:
76
+ raise RuntimeError("cylccd: no cv_support tail in ccd.DEVICE")
77
+ body = body.replace(old, new)
78
+ old = " if (g.type == 5) { // cylinder (g1_engine.cylccd: MuJoCo Warp 3.17's support)"
79
+ body = body.replace(old, MESH_SUPPORT + old)
80
+ cg = " int index; // the support's cached vertex (MuJoCo Warp's geom.index)\n};"
81
+ if body.count(cg) != 1:
82
+ raise RuntimeError("cylccd: no CGeom in ccd.DEVICE")
83
+ body = body.replace(cg, " int index; // the support's cached vertex (MuJoCo Warp's geom.index)\n"
84
+ " int mesh; // type 6: the packed tables' mesh (g1_engine.cylccd)\n};")
85
+ disc = "{ return (t1 == 3 || t1 == 4) && (t2 == 3 || t2 == 4); }"
86
+ if body.count(disc) != 1:
87
+ raise RuntimeError("cylccd: no is_discrete in ccd.DEVICE")
88
+ body = body.replace(disc, "{ return (t1 == 3 || t1 == 6) && (t2 == 3 || t2 == 6); } // (box, the engine's mesh)")
89
+ for old, new in ((" int index1, index2;\n};",
90
+ " int index1, index2;\n int ln, lv1[4], lv2[4]; // (g1_engine.cylccd: the last subdistance "
91
+ "call's vertices)\n};"),
92
+ ("si1[n] = sp1.vidx;",
93
+ "si1[n] = g1.type == 2 ? (rtmul(g1.R, -dir_neg).z >= 0.f ? -3 : -2) : sp1.vidx;"),
94
+ (" subdistance(n + 1, simplex, l);\n",
95
+ " r.ln = n + 1; // (g1_engine.cylccd)\n"
96
+ " for (int i = 0; i <= n; i++) { r.lv1[i] = si1[i]; r.lv2[i] = si2[i]; }\n"
97
+ " subdistance(n + 1, simplex, l);\n"),
98
+ ("r.sidx1[i] = si1[i]; r.sidx2[i] = si2[i];",
99
+ "r.sidx1[i] = si1[i] < -1 ? -1 : si1[i]; r.sidx2[i] = si2[i];")):
100
+ if body.count(old) != 1:
101
+ raise RuntimeError(f"cylccd: {old!r} not once in ccd.DEVICE's GJK")
102
+ body = body.replace(old, new)
103
+ body = re.sub(r"\bEPA_(ITERATIONS|NV|NF|NH)\b", r"CY_EPA_\1", body)
104
+ return body
105
+
106
+
107
+ MESH_SUPPORT = r"""#if CY_HAS_MESH
108
+ if (g.type == 6) { // mesh (g1_engine.cylccd: MuJoCo Warp 3.17's support; g.mesh: the packed tables' mesh)
109
+ const int va = c_mvadr[g.mesh], vn = c_mvnum[g.mesh], ga = c_mgadr[g.mesh];
110
+ float max_dist = CV_FLOAT_MIN;
111
+ f3 pt = mk3(0.f, 0.f, 0.f);
112
+ if (ga == -1 || vn < 10) {
113
+ if (g.index > -1) { // (the cached index is global here, as MuJoCo Warp's)
114
+ sp.cached = g.index;
115
+ pt = mk3(c_mvert[3 * g.index], c_mvert[3 * g.index + 1], c_mvert[3 * g.index + 2]);
116
+ max_dist = dt3(pt, ld);
117
+ }
118
+ for (int i = 0; i < vn; i++) {
119
+ f3 v = mk3(c_mvert[3 * (va + i)], c_mvert[3 * (va + i) + 1], c_mvert[3 * (va + i) + 2]);
120
+ float d = dt3(v, ld);
121
+ if (d > max_dist) { max_dist = d; pt = v; sp.cached = va + i; }
122
+ }
123
+ sp.vidx = sp.cached - va;
124
+ } else {
125
+ const int* gr = c_mgraph + ga;
126
+ const int numvert = gr[0], vert_edgeadr = 2, vert_globalid = 2 + numvert, edge_localid = 2 + 2 * numvert;
127
+ int prev = -1, imax = g.index > -1 ? g.index : 0;
128
+ int q = va + gr[vert_globalid + imax];
129
+ max_dist = dt3(ld, mk3(c_mvert[3 * q], c_mvert[3 * q + 1], c_mvert[3 * q + 2]));
130
+ while (imax != prev) { // hill-climb until no change
131
+ prev = imax;
132
+ int i = gr[vert_edgeadr + imax];
133
+ int subidx = gr[edge_localid + i];
134
+ while (subidx >= 0) {
135
+ q = va + gr[vert_globalid + subidx];
136
+ float d = dt3(ld, mk3(c_mvert[3 * q], c_mvert[3 * q + 1], c_mvert[3 * q + 2]));
137
+ if (d > max_dist) { imax = subidx; max_dist = d; }
138
+ i++;
139
+ subidx = gr[edge_localid + i];
140
+ }
141
+ }
142
+ sp.cached = imax;
143
+ sp.vidx = gr[vert_globalid + imax];
144
+ q = va + sp.vidx;
145
+ pt = mk3(c_mvert[3 * q], c_mvert[3 * q + 1], c_mvert[3 * q + 2]);
146
+ }
147
+ sp.point = rmul(g.R, pt) + g.pos;
148
+ return sp;
149
+ }
150
+ #endif
151
+ """
152
+
153
+
154
+ MULTI = r"""
155
+ // ------------------------------------------------- multicontact (MuJoCo Warp 3.17, collision_gjk.py; margins 0)
156
+ #ifndef CY_NPOLY
157
+ #define CY_NPOLY 16 // (the cylinder's 16-gon; meshes: their largest polygon, header)
158
+ #endif
159
+ #ifndef CY_NDEG
160
+ #define CY_NDEG 3 // (a box vertex's faces; meshes: their largest vertex degree, header)
161
+ #endif
162
+ struct CyBuf {
163
+ f3 polygon[2 * CY_NPOLY], clipped[2 * CY_NPOLY], pnormal[CY_NPOLY];
164
+ float pdist[CY_NPOLY];
165
+ int idx1[CY_NDEG], idx2[CY_NDEG];
166
+ f3 n1[CY_NDEG], n2[CY_NDEG], endvert[CY_NDEG], face1[CY_NPOLY], face2[CY_NPOLY];
167
+ f3 cdir; // the clip's dir (CLEAN_NORMAL)
168
+ int cset;
169
+ };
170
+ __device__ int cy_feature_dim(const int* fv, const Polytope& pt, int off, int* fi, f3* fx) {
171
+ int v1i = pt.vidx[2 * fv[0] + off], v2i = pt.vidx[2 * fv[1] + off], v3i = pt.vidx[2 * fv[2] + off];
172
+ fi[0] = v1i; fi[1] = v2i; fi[2] = v3i;
173
+ fx[0] = pt.vert[2 * fv[0] + off]; fx[1] = pt.vert[2 * fv[1] + off]; fx[2] = pt.vert[2 * fv[2] + off];
174
+ if (v1i != v2i) return (v3i == v1i || v3i == v2i) ? 2 : 3;
175
+ fi[1] = v3i;
176
+ fx[1] = pt.vert[2 * fv[2] + off];
177
+ return v1i != v3i ? 2 : 1;
178
+ }
179
+ __device__ int cy_aligned_faces(const f3* a, int la, const f3* b, int lb, f3 dir, int* res) {
180
+ float dir_tol = CV_EDGE_TOL * nm3(dir);
181
+ float best = -CV_FACE_TOL;
182
+ int found = 0;
183
+ for (int i = 0; i < la; i++) {
184
+ if (dt3(a[i], dir) >= -dir_tol) continue;
185
+ for (int j = 0; j < lb; j++) {
186
+ if (dt3(b[j], dir) <= dir_tol) continue;
187
+ float d = dt3(a[i], b[j]);
188
+ if (d < best) { best = d; res[0] = i; res[1] = j; found = 1; }
189
+ }
190
+ }
191
+ return found;
192
+ }
193
+ __device__ int cy_aligned_face_edge(const f3* edge, int nedge, const f3* face, int nface, f3 dir, int* res) {
194
+ for (int i = 0; i < nface; i++) {
195
+ if (dt3(face[i], dir) <= CV_MINVAL) continue;
196
+ for (int j = 0; j < nedge; j++)
197
+ if (fabsf(dt3(edge[j], face[i])) < CV_EDGE_TOL) { res[0] = j; res[1] = i; return 1; }
198
+ }
199
+ return 0;
200
+ }
201
+ __device__ __forceinline__ f3 cy_fn(int i) { // mat63 face normals: +x, -x, +y, -y, +z, -z
202
+ return mk3(i == 0 ? 1.f : (i == 1 ? -1.f : 0.f), i == 2 ? 1.f : (i == 3 ? -1.f : 0.f), i == 4 ? 1.f : (i == 5 ? -1.f : 0.f));
203
+ }
204
+ __device__ int cy_box_normals2(const float* R, f3 n, f3* nout, int* iout) {
205
+ f3 ln = nz3(rtmul(R, n));
206
+ for (int i = 0; i < 6; i++)
207
+ if (dt3(ln, cy_fn(i)) > CV_FACE_TOL) { nout[0] = rmul(R, cy_fn(i)); iout[0] = i; return 1; }
208
+ return 0;
209
+ }
210
+ __device__ int cy_box_normals(int dim, const int* fi, const float* R, f3 dir, f3* nout, int* iout) {
211
+ int v1 = fi[0], v2 = fi[1], v3 = fi[2];
212
+ if (dim == 3) {
213
+ int c = 0;
214
+ float x = float((v1 & 1) && (v2 & 1) && (v3 & 1)) - float(!(v1 & 1) && !(v2 & 1) && !(v3 & 1));
215
+ float y = float((v1 & 2) && (v2 & 2) && (v3 & 2)) - float(!(v1 & 2) && !(v2 & 2) && !(v3 & 2));
216
+ float z = float((v1 & 4) && (v2 & 4) && (v3 & 4)) - float(!(v1 & 4) && !(v2 & 4) && !(v3 & 4));
217
+ nout[0] = rmul(R, mk3(x, y, z));
218
+ float sgn = x + y + z;
219
+ if (x != 0.f) iout[c++] = 0;
220
+ if (y != 0.f) iout[c++] = 2;
221
+ if (z != 0.f) iout[c++] = 4;
222
+ if (sgn == -1.f) iout[0] = iout[0] + 1;
223
+ if (c == 1) return 1;
224
+ return cy_box_normals2(R, dir, nout, iout);
225
+ }
226
+ if (dim == 2) {
227
+ int c = 0;
228
+ float x = float((v1 & 1) && (v2 & 1)) - float(!(v1 & 1) && !(v2 & 1));
229
+ float y = float((v1 & 2) && (v2 & 2)) - float(!(v1 & 2) && !(v2 & 2));
230
+ float z = float((v1 & 4) && (v2 & 4)) - float(!(v1 & 4) && !(v2 & 4));
231
+ if (x != 0.f) { nout[c] = rmul(R, mk3(x, 0.f, 0.f)); iout[c] = x > 0.f ? 0 : 1; c++; }
232
+ if (y != 0.f) { nout[c] = rmul(R, mk3(0.f, y, 0.f)); iout[c] = y > 0.f ? 2 : 3; c++; }
233
+ if (z != 0.f) { nout[c] = rmul(R, mk3(0.f, 0.f, z)); iout[c] = z > 0.f ? 4 : 5; c++; }
234
+ if (c == 1 || c == 2) return c;
235
+ return cy_box_normals2(R, dir, nout, iout);
236
+ }
237
+ if (dim == 1) {
238
+ float x = (v1 & 1) ? 1.f : -1.f, y = (v1 & 2) ? 1.f : -1.f, z = (v1 & 4) ? 1.f : -1.f;
239
+ nout[0] = rmul(R, mk3(x, 0.f, 0.f)); nout[1] = rmul(R, mk3(0.f, y, 0.f)); nout[2] = rmul(R, mk3(0.f, 0.f, z));
240
+ iout[0] = x > 0.f ? 0 : 1; iout[1] = y > 0.f ? 2 : 3; iout[2] = z > 0.f ? 4 : 5;
241
+ return 3;
242
+ }
243
+ return 0;
244
+ }
245
+ // 3.17's _box_edge_normals: the vertices recomputed from their indices; v: the edge's first vertex
246
+ __device__ int cy_box_edge_normals(int dim, const CGeom& g, int v1i, int v2i, f3* nout, f3* eout, f3* v) {
247
+ float x = (v1i & 1) ? g.size.x : -g.size.x, y = (v1i & 2) ? g.size.y : -g.size.y, z = (v1i & 4) ? g.size.z : -g.size.z;
248
+ f3 v1 = rmul(g.R, mk3(x, y, z)) + g.pos;
249
+ *v = v1;
250
+ if (dim == 2) {
251
+ float x2 = (v2i & 1) ? g.size.x : -g.size.x, y2 = (v2i & 2) ? g.size.y : -g.size.y, z2 = (v2i & 4) ? g.size.z : -g.size.z;
252
+ f3 v2 = rmul(g.R, mk3(x2, y2, z2)) + g.pos;
253
+ eout[0] = v2;
254
+ nout[0] = nz3(v2 - v1);
255
+ return 1;
256
+ }
257
+ if (dim == 1) {
258
+ eout[0] = rmul(g.R, mk3(-x, y, z)) + g.pos; nout[0] = nz3(eout[0] - v1);
259
+ eout[1] = rmul(g.R, mk3(x, -y, z)) + g.pos; nout[1] = nz3(eout[1] - v1);
260
+ eout[2] = rmul(g.R, mk3(x, y, -z)) + g.pos; nout[2] = nz3(eout[2] - v1);
261
+ return 3;
262
+ }
263
+ return 0;
264
+ }
265
+ __device__ int cy_box_face(const CGeom& g, int idx, f3* f) {
266
+ const float sx = g.size.x, sy = g.size.y, sz = g.size.z;
267
+ f3 c[4];
268
+ if (idx == 0) { c[0] = mk3(sx, sy, sz); c[1] = mk3(sx, sy, -sz); c[2] = mk3(sx, -sy, -sz); c[3] = mk3(sx, -sy, sz); }
269
+ else if (idx == 1) { c[0] = mk3(-sx, sy, -sz); c[1] = mk3(-sx, sy, sz); c[2] = mk3(-sx, -sy, sz); c[3] = mk3(-sx, -sy, -sz); }
270
+ else if (idx == 2) { c[0] = mk3(-sx, sy, -sz); c[1] = mk3(sx, sy, -sz); c[2] = mk3(sx, sy, sz); c[3] = mk3(-sx, sy, sz); }
271
+ else if (idx == 3) { c[0] = mk3(-sx, -sy, sz); c[1] = mk3(sx, -sy, sz); c[2] = mk3(sx, -sy, -sz); c[3] = mk3(-sx, -sy, -sz); }
272
+ else if (idx == 4) { c[0] = mk3(-sx, sy, sz); c[1] = mk3(sx, sy, sz); c[2] = mk3(sx, -sy, sz); c[3] = mk3(-sx, -sy, sz); }
273
+ else if (idx == 5) { c[0] = mk3(sx, sy, -sz); c[1] = mk3(-sx, sy, -sz); c[2] = mk3(-sx, -sy, -sz); c[3] = mk3(sx, -sy, -sz); }
274
+ else return 0;
275
+ for (int i = 0; i < 4; i++) f[i] = rmul(g.R, c[i]) + g.pos;
276
+ return 4;
277
+ }
278
+ __device__ __forceinline__ f3 cy_col(const float* R, int c) { return mk3(R[c], R[3 + c], R[6 + c]); } // mat[:, c]
279
+ __device__ int cy_cylinder_normals(int dim, const int* fi, const float* R, f3* nout, int* iout) {
280
+ if (dim == 1) {
281
+ float sgn = fi[0] != 0 ? -1.f : 1.f;
282
+ nout[0] = cy_col(R, 2) * sgn;
283
+ iout[0] = fi[0];
284
+ return 1;
285
+ }
286
+ return 0;
287
+ }
288
+ __device__ int cy_cylinder_edge_normals(int dim, const CGeom& g, f3 v, int v1i, f3* nout, f3* eout, f3* vout) {
289
+ *vout = v;
290
+ if (dim == 1 || dim == 2) {
291
+ float sgn = v1i != 0 ? 1.f : -1.f;
292
+ f3 res = cy_col(g.R, 2) * sgn;
293
+ nout[0] = res;
294
+ eout[0] = v + res * (2.f * g.size.y);
295
+ return 1;
296
+ }
297
+ return 0;
298
+ }
299
+ __device__ __forceinline__ void cy_cs16(int i, flt* c, flt* s) {
300
+ const flt C[16] = {@COS16@};
301
+ const flt S[16] = {@SIN16@};
302
+ *c = C[i]; *s = S[i];
303
+ }
304
+ __device__ int cy_cylinder_face(const CGeom& g, int idx, f3* f) {
305
+ float sgn = idx != 0 ? -1.f : 1.f;
306
+ f3 center = cy_col(g.R, 2) * (sgn * g.size.y) + g.pos;
307
+ f3 col0 = cy_col(g.R, 0) * g.size.x;
308
+ f3 col1 = cy_col(g.R, 1) * (g.size.x * sgn);
309
+ for (int i = 0; i < 16; i++) {
310
+ flt c, s;
311
+ cy_cs16(i, &c, &s);
312
+ f[i] = col0 * c - col1 * s + center;
313
+ }
314
+ return 16;
315
+ }
316
+ #if CY_HAS_MESH
317
+ __device__ __forceinline__ f3 cy_mvert(int q) { return mk3(c_mvert[3 * q], c_mvert[3 * q + 1], c_mvert[3 * q + 2]); }
318
+ __device__ __forceinline__ f3 cy_mpnorm(int q) { return mk3(c_mpnorm[3 * q], c_mpnorm[3 * q + 1], c_mpnorm[3 * q + 2]); }
319
+ // _intersect1 / _intersect2: up to 2 common entries of polymap ranges
320
+ __device__ int cy_intersect1(int s1, int s2, int l1, int l2, int* res) {
321
+ int count = 0;
322
+ for (int i = s1; i < s1 + l1; i++)
323
+ for (int j = s2; j < s2 + l2; j++)
324
+ if (c_mpmap[i] == c_mpmap[j]) { res[count++] = c_mpmap[i]; if (count == 2) return 2; }
325
+ return count;
326
+ }
327
+ __device__ int cy_intersect2(const int* a1, int s2, int l1, int l2, int* res) {
328
+ int count = 0;
329
+ for (int i = 0; i < l1; i++)
330
+ for (int j = s2; j < s2 + l2; j++)
331
+ if (a1[i] == c_mpmap[j]) { res[count++] = a1[i]; if (count == 2) return 2; }
332
+ return count;
333
+ }
334
+ __device__ int cy_mesh_normals(int dim, const int* fi, const CGeom& g, f3* nout, int* iout) { // _mesh_normals
335
+ const int va = c_mvadr[g.mesh], pa = c_mpadr[g.mesh];
336
+ if (dim == 3) {
337
+ int edgeset[2], faceset[2];
338
+ int n = cy_intersect1(c_mpmadr[va + fi[0]], c_mpmadr[va + fi[1]], c_mpmnum[va + fi[0]], c_mpmnum[va + fi[1]], edgeset);
339
+ if (n == 0) return 0;
340
+ n = cy_intersect2(edgeset, c_mpmadr[va + fi[2]], n, c_mpmnum[va + fi[2]], faceset);
341
+ if (n == 0) return 0;
342
+ nout[0] = rmul(g.R, cy_mpnorm(pa + faceset[0]));
343
+ iout[0] = faceset[0];
344
+ return 1;
345
+ }
346
+ if (dim == 2) {
347
+ int edgeset[2];
348
+ int n = cy_intersect1(c_mpmadr[va + fi[0]], c_mpmadr[va + fi[1]], c_mpmnum[va + fi[0]], c_mpmnum[va + fi[1]], edgeset);
349
+ if (n == 0) return 0;
350
+ for (int i = 0; i < n; i++) { nout[i] = rmul(g.R, cy_mpnorm(pa + edgeset[i])); iout[i] = edgeset[i]; }
351
+ return n;
352
+ }
353
+ if (dim == 1) {
354
+ const int adr = c_mpmadr[va + fi[0]], num = c_mpmnum[va + fi[0]];
355
+ for (int i = 0; i < num && i < CY_NDEG; i++) {
356
+ const int index = c_mpmap[adr + i];
357
+ nout[i] = rmul(g.R, cy_mpnorm(pa + index));
358
+ iout[i] = index;
359
+ }
360
+ return num < CY_NDEG ? num : CY_NDEG;
361
+ }
362
+ return 0;
363
+ }
364
+ __device__ int cy_mesh_edge_normals(int dim, const CGeom& g, int v1i, int v2i, f3* nout, f3* eout, f3* v) {
365
+ const int va = c_mvadr[g.mesh], pa = c_mpadr[g.mesh];
366
+ f3 v1 = rmul(g.R, cy_mvert(va + v1i)) + g.pos;
367
+ *v = v1;
368
+ if (dim == 2) {
369
+ f3 v2 = rmul(g.R, cy_mvert(va + v2i)) + g.pos;
370
+ eout[0] = v2;
371
+ nout[0] = nz3(v2 - v1);
372
+ return 1;
373
+ }
374
+ if (dim == 1) {
375
+ const int adr1 = c_mpmadr[va + v1i], num1 = c_mpmnum[va + v1i];
376
+ for (int i = 0; i < num1 && i < CY_NDEG; i++) {
377
+ const int idx = c_mpmap[adr1 + i], adr = c_mpvadr[pa + idx], nvert = c_mpvnum[pa + idx];
378
+ for (int j = 0; j < nvert; j++)
379
+ if (c_mpvert[adr + j] == v1i) {
380
+ const int k = j == 0 ? nvert - 1 : j - 1;
381
+ eout[i] = rmul(g.R, cy_mvert(va + c_mpvert[adr + k])) + g.pos;
382
+ nout[i] = nz3(eout[i] - v1);
383
+ }
384
+ }
385
+ return num1 < CY_NDEG ? num1 : CY_NDEG;
386
+ }
387
+ return 0;
388
+ }
389
+ __device__ int cy_mesh_face(const CGeom& g, int idx, f3* f) { // _mesh_face: the polygon's vertices reversed
390
+ const int va = c_mvadr[g.mesh], pa = c_mpadr[g.mesh];
391
+ const int adr = c_mpvadr[pa + idx], nvert = c_mpvnum[pa + idx];
392
+ int j = 0;
393
+ for (int i = nvert - 1; i >= 0; i--) f[j++] = rmul(g.R, cy_mvert(va + c_mpvert[adr + i])) + g.pos;
394
+ return nvert;
395
+ }
396
+ #else // (no meshes: never called)
397
+ __device__ __forceinline__ int cy_mesh_normals(int, const int*, const CGeom&, f3*, int*) { return 0; }
398
+ __device__ __forceinline__ int cy_mesh_edge_normals(int, const CGeom&, int, int, f3*, f3*, f3*) { return 0; }
399
+ __device__ __forceinline__ int cy_mesh_face(const CGeom&, int, f3*) { return 0; }
400
+ #endif
401
+ __device__ int cy_capsule_edge_normals(const CGeom& g, f3 w, f3* nout, f3* eout, f3* vout) {
402
+ f3 res = cy_col(g.R, 2);
403
+ float pr = dt3(w - g.pos, res);
404
+ float len = g.size.y;
405
+ nout[0] = res;
406
+ *vout = w + res * (-pr - len);
407
+ eout[0] = w + res * (-pr + len);
408
+ return 1;
409
+ }
410
+ __device__ __forceinline__ void cy_witness_on_face(f3 v, f3 p, f3 n, f3 dir, f3* w1, f3* w2, float* d) {
411
+ f3 dd = v - p;
412
+ f3 a = v - dt3(dd, n) * n;
413
+ float dist = dt3(a - v, dir);
414
+ *w1 = a;
415
+ *w2 = a - dist * dir;
416
+ *d = dist;
417
+ }
418
+ __device__ __forceinline__ float cy_area4(f3 a, f3 b, f3 c, f3 d) { return 0.5f * nm3(cr3(a - c, b - d)); }
419
+ __device__ void cy_polygon_quad(const f3* p, int np, int* q) { // MuJoCo Warp's _polygon_quad
420
+ int b = 1, c = 2, d = 3;
421
+ q[0] = 0; q[1] = b; q[2] = c; q[3] = d;
422
+ float m = cy_area4(p[0], p[b], p[c], p[d]);
423
+ for (int a = 0; a < np; a++) {
424
+ while (true) {
425
+ float m_next = cy_area4(p[a], p[b], p[c], p[(d + 1) % np]);
426
+ if (m_next <= m) break;
427
+ m = m_next; d = (d + 1) % np; q[0] = a; q[1] = b; q[2] = c; q[3] = d;
428
+ while (true) {
429
+ m_next = cy_area4(p[a], p[b], p[(c + 1) % np], p[d]);
430
+ if (m_next <= m) break;
431
+ m = m_next; c = (c + 1) % np; q[0] = a; q[1] = b; q[2] = c; q[3] = d;
432
+ }
433
+ while (true) {
434
+ m_next = cy_area4(p[a], p[(b + 1) % np], p[c], p[d]);
435
+ if (m_next <= m) break;
436
+ m = m_next; b = (b + 1) % np; q[0] = a; q[1] = b; q[2] = c; q[3] = d;
437
+ }
438
+ }
439
+ if (b == a) {
440
+ b = (b + 1) % np;
441
+ if (c == b) {
442
+ c = (c + 1) % np;
443
+ if (d == c) d = (d + 1) % np;
444
+ }
445
+ }
446
+ }
447
+ }
448
+ // clip polygon face2 against face1 (3.17's _polygon_clip, margin 0): the contacts (witnesses, distances), count
449
+ __device__ int cy_polygon_clip(CyBuf& mb, const f3* face1, int nface1, const f3* face2, int nface2, f3 n, f3 dir,
450
+ f3* w1o, f3* w2o, float* dists) {
451
+ if (nface1 < 3) return 0;
452
+ mb.cdir = dir; mb.cset = 1;
453
+ for (int i = 0; i < nface1; i++) {
454
+ f3 a = face1[i], b = face1[(i + 1) % nface1];
455
+ f3 v3 = a + n, res = cr3(b - a, v3 - a);
456
+ mb.pdist[i] = dt3(res, a);
457
+ mb.pnormal[i] = res;
458
+ }
459
+ f3* poly = mb.polygon;
460
+ f3* clip = mb.clipped;
461
+ int npoly = nface2, nclip = 0, over = 0;
462
+ for (int i = 0; i < nface2; i++) poly[i] = face2[i];
463
+ for (int e = 0; e < nface1; e++) {
464
+ for (int i = 0; i < npoly; i++) {
465
+ f3 P = poly[i], Q = poly[(i + 1) % npoly];
466
+ bool in1 = dt3(P - face1[e], mb.pnormal[e]) > -1e-10f, in2 = dt3(Q - face1[e], mb.pnormal[e]) > -1e-10f;
467
+ if (!in1 && !in2) continue;
468
+ if (in1 && in2) {
469
+ if (nclip < 2 * CY_NPOLY) clip[nclip++] = Q; else over = 1;
470
+ continue;
471
+ }
472
+ float dot = dt3(mb.pnormal[e], Q - P), t = fabsf(dot) < 1e-10f ? CV_FLOAT_MAX : (mb.pdist[e] - dt3(mb.pnormal[e], P)) / dot;
473
+ if (t > -CV_INTERSECT_TOL && t < 1.f + CV_INTERSECT_TOL) {
474
+ t = fminf(fmaxf(t, 0.f), 1.f);
475
+ if (nclip < 2 * CY_NPOLY) clip[nclip++] = P + t * (Q - P); else over = 1;
476
+ }
477
+ if (in2) { if (nclip < 2 * CY_NPOLY) clip[nclip++] = Q; else over = 1; }
478
+ }
479
+ f3* tmp = poly; poly = clip; clip = tmp;
480
+ npoly = nclip;
481
+ nclip = 0;
482
+ }
483
+ if (over) mb.cset = 2; // (a clipped polygon beyond MuJoCo Warp's buffer: flagged by the caller)
484
+ int m = npoly;
485
+ npoly = 0;
486
+ for (int i = 0; i < m; i++)
487
+ if (dt3(poly[i] - face1[0], n) <= 0.f) {
488
+ if (npoly != i) poly[npoly] = poly[i];
489
+ npoly++;
490
+ }
491
+ if (npoly < 1) return 0;
492
+ if (nface2 == 2 && npoly > 2) {
493
+ int b1 = 0, b2 = 1;
494
+ float max_d = 0.f;
495
+ for (int i = 0; i < npoly; i++)
496
+ for (int j = i + 1; j < npoly; j++) {
497
+ f3 df = poly[j] - poly[i];
498
+ float d2 = dt3(df, df);
499
+ if (d2 > max_d) { max_d = d2; b1 = i; b2 = j; }
500
+ }
501
+ cy_witness_on_face(poly[b1], face1[0], n, dir, &w1o[0], &w2o[0], &dists[0]);
502
+ cy_witness_on_face(poly[b2], face1[0], n, dir, &w1o[1], &w2o[1], &dists[1]);
503
+ return 2;
504
+ }
505
+ if (npoly > 4) {
506
+ int q[4];
507
+ cy_polygon_quad(poly, npoly, q);
508
+ for (int i = 0; i < 4; i++) cy_witness_on_face(poly[q[i]], face1[0], n, dir, &w1o[i], &w2o[i], &dists[i]);
509
+ return 4;
510
+ }
511
+ for (int i = 0; i < npoly; i++) cy_witness_on_face(poly[i], face1[0], n, dir, &w1o[i], &w2o[i], &dists[i]);
512
+ return npoly;
513
+ }
514
+ // 3.17's multicontact: up to 4 contacts (witnesses w1, w2, distances) from polytope face fidx; returns the count
515
+ // (1: the witnesses x1, x2 alone)
516
+ __device__ int cy_multicontact(CyBuf& mb, const Polytope& pt, int fidx, f3 x1, f3 x2, const CGeom& g1,
517
+ const CGeom& g2, f3* w1, f3* w2, float* dists) {
518
+ w1[0] = x1; w2[0] = x2;
519
+ mb.cset = 0;
520
+ int fv[3], fi1[3], fi2[3];
521
+ f3 fx1[3], fx2[3];
522
+ face_verts(pt.face[fidx], fv);
523
+ int nface1 = cy_feature_dim(fv, pt, 0, fi1, fx1), nface2 = cy_feature_dim(fv, pt, 1, fi2, fx2);
524
+ f3 v1 = fx1[0], v2 = fx2[0];
525
+ f3 dir = x2 - x1, dir_neg = -dir;
526
+ int nn1 = 0, nn2 = 0;
527
+ if (g1.type == 3) nn1 = cy_box_normals(nface1, fi1, g1.R, dir_neg, mb.n1, mb.idx1);
528
+ else if (g1.type == 6) nn1 = cy_mesh_normals(nface1, fi1, g1, mb.n1, mb.idx1);
529
+ else if (g1.type == 5) nn1 = cy_cylinder_normals(nface1, fi1, g1.R, mb.n1, mb.idx1);
530
+ if (g2.type == 3) nn2 = cy_box_normals(nface2, fi2, g2.R, dir, mb.n2, mb.idx2);
531
+ else if (g2.type == 6) nn2 = cy_mesh_normals(nface2, fi2, g2, mb.n2, mb.idx2);
532
+ else if (g2.type == 5) nn2 = cy_cylinder_normals(nface2, fi2, g2.R, mb.n2, mb.idx2);
533
+ int edge1 = 0, edge2 = 0, res[2] = {0, 0};
534
+ int nres = cy_aligned_faces(mb.n1, nn1, mb.n2, nn2, dir, res);
535
+ if (!nres) {
536
+ if (nface1 < 3 && nn2 && (nface1 <= nface2 || !nn1)) {
537
+ nn1 = 0;
538
+ if (g1.type == 3) nn1 = cy_box_edge_normals(nface1, g1, fi1[0], fi1[1], mb.n1, mb.endvert, &v1);
539
+ else if (g1.type == 6) nn1 = cy_mesh_edge_normals(nface1, g1, fi1[0], fi1[1], mb.n1, mb.endvert, &v1);
540
+ else if (g1.type == 5) nn1 = cy_cylinder_edge_normals(nface1, g1, fx1[0], fi1[0], mb.n1, mb.endvert, &v1);
541
+ else if (g1.type == 2) nn1 = cy_capsule_edge_normals(g1, x1, mb.n1, mb.endvert, &v1);
542
+ nres = cy_aligned_face_edge(mb.n1, nn1, mb.n2, nn2, dir, res);
543
+ if (!nres) return 1;
544
+ edge1 = 1;
545
+ } else if (nface2 < 3) {
546
+ nn2 = 0;
547
+ if (g2.type == 3) nn2 = cy_box_edge_normals(nface2, g2, fi2[0], fi2[1], mb.n2, mb.endvert, &v2);
548
+ else if (g2.type == 6) nn2 = cy_mesh_edge_normals(nface2, g2, fi2[0], fi2[1], mb.n2, mb.endvert, &v2);
549
+ else if (g2.type == 5) nn2 = cy_cylinder_edge_normals(nface2, g2, fx2[0], fi2[0], mb.n2, mb.endvert, &v2);
550
+ else if (g2.type == 2) nn2 = cy_capsule_edge_normals(g2, x2, mb.n2, mb.endvert, &v2);
551
+ nres = cy_aligned_face_edge(mb.n2, nn2, mb.n1, nn1, dir_neg, res);
552
+ if (!nres) return 1;
553
+ edge2 = 1;
554
+ } else {
555
+ return 1;
556
+ }
557
+ }
558
+ const int i = res[0], j = res[1];
559
+ int nf1 = 0, nf2 = 0;
560
+ if (edge1) { mb.face1[0] = v1; mb.face1[1] = mb.endvert[i]; nf1 = 2; }
561
+ else {
562
+ const int ind = edge2 ? mb.idx1[j] : mb.idx1[i];
563
+ if (g1.type == 3) nf1 = cy_box_face(g1, ind, mb.face1);
564
+ else if (g1.type == 6) nf1 = cy_mesh_face(g1, ind, mb.face1);
565
+ else if (g1.type == 5) nf1 = cy_cylinder_face(g1, ind, mb.face1);
566
+ }
567
+ if (edge2) { mb.face2[0] = v2; mb.face2[1] = mb.endvert[i]; nf2 = 2; }
568
+ else {
569
+ if (g2.type == 3) nf2 = cy_box_face(g2, mb.idx2[j], mb.face2);
570
+ else if (g2.type == 6) nf2 = cy_mesh_face(g2, mb.idx2[j], mb.face2);
571
+ else if (g2.type == 5) nf2 = cy_cylinder_face(g2, mb.idx2[j], mb.face2);
572
+ }
573
+ int nc;
574
+ if (edge1) { // face1 is an edge: clipped against face2, then flipped back
575
+ f3 c1[4], c2[4];
576
+ nc = cy_polygon_clip(mb, mb.face2, nf2, mb.face1, nf1, mb.n2[j], -mb.n2[j], c1, c2, dists);
577
+ for (int k = 0; k < nc; k++) { w1[k] = c2[k]; w2[k] = c1[k]; }
578
+ } else if (edge2) {
579
+ nc = cy_polygon_clip(mb, mb.face1, nf1, mb.face2, nf2, mb.n1[j], -mb.n1[j], w1, w2, dists);
580
+ } else {
581
+ nc = cy_polygon_clip(mb, mb.face1, nf1, mb.face2, nf2, mb.n1[i], mb.n2[j], w1, w2, dists);
582
+ }
583
+ if (nc < 1) { mb.cset = mb.cset == 2 ? 2 : 0; return 1; }
584
+ return nc;
585
+ }
586
+ """
587
+
588
+ ENTRY = r"""
589
+ // ------------------------------------------------------------- the pair (3.17's ccd_kernel; margin, gap 0)
590
+ // The adjoint's record (CyRec, g1_engine.cylccd): every branch of the pair reads only values, which the D1 replays
591
+ // share bit for bit with the RF replay, so a D1 replay's tangents are those of the straight-line program the RF replay
592
+ // ran. With supports at discrete features (box and mesh vertices, the shrunk sphere's centre and capsule's segment
593
+ // ends) the outputs depend on the poses only through the final EPA face's three vertex pairs (kind 1: the deep path)
594
+ // or the shrunk shapes' final GJK simplex (kind 2: the inflated path); a D1 replay with the record rebuilds those from
595
+ // their recorded features and runs the forward's own code from there (attach_face and epa_witness, or cv_gjk's last
596
+ // subdistance; then the multicontact and the assembly), without the searches. Smooth supports (the cylinder's rim, the
597
+ // full sphere and capsule) record kind 0: the full replay.
598
+ // a support point from its recorded feature: cv_support's expressions for a box vertex (v: the sign bits) and a mesh
599
+ // vertex (v: the mesh's local index); the shrunk sphere and capsule (size.x 0; geom 1, at the origin) through
600
+ // cv_support itself, at a direction of the recorded end (capsule: v -3 the +z end, -2 the -z end; the other terms
601
+ // zeros)
602
+ __device__ f3 cy_vertex(const CGeom& g, int v) {
603
+ if (g.type == 3) {
604
+ f3 tmp = mk3((v & 1) ? 1.f : -1.f, (v & 2) ? 1.f : -1.f, (v & 4) ? 1.f : -1.f);
605
+ f3 res = mk3(tmp.x * g.size.x, tmp.y * g.size.y, tmp.z * g.size.z);
606
+ return rmul(g.R, res) + g.pos;
607
+ }
608
+ #if CY_HAS_MESH
609
+ if (g.type == 6) {
610
+ const int q = c_mvadr[g.mesh] + v;
611
+ f3 pt = mk3(c_mvert[3 * q], c_mvert[3 * q + 1], c_mvert[3 * q + 2]);
612
+ return rmul(g.R, pt) + g.pos;
613
+ }
614
+ #endif
615
+ f3 dir = mk3(0.f, 0.f, 1.f);
616
+ if (g.type == 2) dir = mk3(cy_val(g.R[2]), cy_val(g.R[5]), cy_val(g.R[8])) * (v == -3 ? 1.f : -1.f);
617
+ return cv_support(g, dir).point;
618
+ }
619
+ // kind 2: the shrunk shapes' GJK result from cv_gjk's last subdistance call (its vertices rebuilt from their recorded
620
+ // features: the dropped ones too, so that the call is the same), then cv_gjk's compaction and combinations
621
+ __device__ void cy_gjk_rec(const CyRec& rc, CGeom& g1, CGeom& g2, GJKResult& r) {
622
+ f3 simplex[4], simplex1[4], simplex2[4];
623
+ int si1[4] = {0, 0, 0, 0}, si2[4] = {0, 0, 0, 0};
624
+ for (int i = 0; i < 4; i++) simplex[i] = simplex1[i] = simplex2[i] = mk3(0.f, 0.f, 0.f);
625
+ float l[4] = {1.f, 0.f, 0.f, 0.f};
626
+ int n = rc.n;
627
+ for (int i = 0; i < n; i++) {
628
+ simplex1[i] = cy_vertex(g1, rc.v1[i]); si1[i] = rc.v1[i];
629
+ simplex2[i] = cy_vertex(g2, rc.v2[i]); si2[i] = rc.v2[i];
630
+ simplex[i] = simplex1[i] - simplex2[i];
631
+ }
632
+ subdistance(n, simplex, l);
633
+ n = 0;
634
+ for (int i = 0; i < 4; i++) {
635
+ if (l[i] == 0.f) continue;
636
+ simplex[n] = simplex[i]; simplex1[n] = simplex1[i]; simplex2[n] = simplex2[i];
637
+ si1[n] = si1[i]; si2[n] = si2[i]; l[n] = l[i];
638
+ n++;
639
+ }
640
+ f3 x_k = lin_combine(n, l, simplex);
641
+ float xnorm = sqrtf(dt3(x_k, x_k));
642
+ r.separated = false;
643
+ r.x1 = lin_combine(n, l, simplex1);
644
+ r.x2 = lin_combine(n, l, simplex2);
645
+ r.dist = xnorm;
646
+ r.dim = n;
647
+ for (int i = 0; i < 4; i++) {
648
+ r.simplex[i] = simplex[i]; r.simplex1[i] = simplex1[i]; r.simplex2[i] = simplex2[i];
649
+ r.sidx1[i] = si1[i] < -1 ? -1 : si1[i]; r.sidx2[i] = si2[i];
650
+ }
651
+ r.index1 = g1.index;
652
+ r.index2 = g2.index;
653
+ }
654
+ // kind 2's record: the inflated path of a shrunk sphere or capsule (geom 1) against a box or mesh, cv_gjk's last
655
+ // subdistance call's vertices (r.ln, r.lv1, r.lv2; the final simplex at most a triangle)
656
+ __device__ void cy_record_gjk(CyRec& rc, const GJKResult& r, const CGeom& g1, const CGeom& g2) {
657
+ if (!((g1.type == 1 || g1.type == 2) && (g2.type == 3 || g2.type == 6)) || r.dim < 1 || r.dim > 3) return;
658
+ rc.kind = 2;
659
+ rc.n = r.ln;
660
+ for (int i = 0; i < r.ln; i++) { rc.v1[i] = r.lv1[i]; rc.v2[i] = r.lv2[i]; }
661
+ }
662
+ // kind 1: the final EPA face rebuilt in the polytope from its three vertex pairs (at their polytope indices fv, the
663
+ // face at its index n: the replay's layout), the polytope's centre the recorded values (attach_face's sign test),
664
+ // attached by attach_face; returns the face's index
665
+ __device__ int cy_face_rec(const CyRec& rc, CGeom& g1, CGeom& g2, Polytope& pt) {
666
+ for (int k = 0; k < 3; k++) {
667
+ pt.vert[2 * rc.fv[k]] = cy_vertex(g1, rc.v1[k]); pt.vidx[2 * rc.fv[k]] = rc.v1[k];
668
+ pt.vert[2 * rc.fv[k] + 1] = cy_vertex(g2, rc.v2[k]); pt.vidx[2 * rc.fv[k] + 1] = rc.v2[k];
669
+ }
670
+ pt.center = mk3(rc.c[0], rc.c[1], rc.c[2]);
671
+ attach_face(pt, rc.n, rc.fv[0], rc.fv[1], rc.fv[2]);
672
+ return rc.n;
673
+ }
674
+ // gjk_phase: true when EPA is needed; dist, x1, x2 otherwise the result (r.dim 0: no simplex for the multicontact);
675
+ // gn: the shrunk shapes' direction of an inflated contact (CLEAN_NORMAL)
676
+ // (the adjoint's record, CyRec: rec null in the forward; use false: the search runs and fills rec, true: rec's kind 1
677
+ // or 2 replaces the search, which the other kinds run)
678
+ __device__ bool cy_gjk_phase(float tol, int iters, CGeom& g1, CGeom& g2, float* dist, f3* x1, f3* x2, GJKResult& r,
679
+ f3* gn, CyRec* rec, bool use) {
680
+ const f3 s1 = g1.size, s2 = g2.size;
681
+ float fm1 = 0.f, fm2 = 0.f;
682
+ if (g1.type == 1 || g1.type == 2) { fm1 = g1.size.x; g1.size.x = 0.f; }
683
+ if (g2.type == 1 || g2.type == 2) { fm2 = g2.size.x; g2.size.x = 0.f; }
684
+ if (fm1 + fm2 > 0.f) {
685
+ if (use && rec->kind == 2) cy_gjk_rec(*rec, g1, g2, r);
686
+ else cv_gjk(tol, iters, g1, g2, g1.pos, g2.pos, fm1 + fm2, is_discrete(g1.type, g2.type), r);
687
+ g1.index = r.index1; g2.index = r.index2;
688
+ if (r.dist > tol) {
689
+ if (rec && !use && r.dist != CV_FLOAT_MAX) cy_record_gjk(*rec, r, g1, g2);
690
+ g1.size = s1; g2.size = s2;
691
+ if (r.dist == CV_FLOAT_MAX) { *dist = r.dist; *x1 = r.x1; *x2 = r.x2; r.dim = 0; return false; }
692
+ f3 n = nz3(r.x2 - r.x1); // _inflate
693
+ f3 a = r.x1, b = r.x2;
694
+ if (fm1 > 0.f) a = a + fm1 * n;
695
+ if (fm2 > 0.f) b = b - fm2 * n;
696
+ *dist = r.dist - (fm1 + fm2);
697
+ *x1 = a; *x2 = b;
698
+ *gn = -n;
699
+ return false;
700
+ }
701
+ g1.size = s1; g2.size = s2;
702
+ }
703
+ cv_gjk(tol, iters, g1, g2, g1.pos, g2.pos, 0.f, is_discrete(g1.type, g2.type), r);
704
+ g1.index = r.index1; g2.index = r.index2;
705
+ *dist = r.dist; *x1 = r.x1; *x2 = r.x2;
706
+ if (r.dist > tol || r.dim < 2 || r.separated) { r.dim = 0; return false; }
707
+ return true;
708
+ }
709
+ __device__ void cy_simplex_to_epa(const GJKResult& r, Polytope& pt) { // _gjk_simplex_to_epa
710
+ const int i2 = r.dim > 1 ? 1 : 0, i3 = r.dim > 2 ? 2 : 0;
711
+ pt.vert[0] = r.simplex1[0]; pt.vert[1] = r.simplex2[0];
712
+ pt.vert[2] = r.simplex1[i2]; pt.vert[3] = r.simplex2[i2];
713
+ pt.vert[4] = r.simplex1[i3]; pt.vert[5] = r.simplex2[i3];
714
+ pt.vidx[0] = r.sidx1[0]; pt.vidx[1] = r.sidx2[0];
715
+ pt.vidx[2] = r.sidx1[i2]; pt.vidx[3] = r.sidx2[i2];
716
+ pt.vidx[4] = r.sidx1[i3]; pt.vidx[5] = r.sidx2[i3];
717
+ pt.face[0] = 0u | (1u << 10) | (2u << 20);
718
+ }
719
+ // the contacts of convex pair (g1, g2) (types 2 capsule, 3 box, 5 cylinder, MuJoCo's order) with dist < 0 into o:
720
+ // slots the multicontact's points 0 .. 3, the frame from the first one's witnesses
721
+ // (rec, use: the adjoint's record, see cy_gjk_phase; rec null in the forward)
722
+ __device__ void cy_pair(CGeom g1, CGeom g2, Sink& o, CyRec* rec, bool use) {
723
+ o.n = 0; o.unsupported = 0;
724
+ if (rec && !use) rec->kind = 0;
725
+ const bool face_rec = use && rec->kind == 1; // (kind 1: the final EPA face from the record)
726
+ const float tol = CY_CCD_TOLERANCE;
727
+ const f3 origin = g1.pos; // (translation invariance: geom 1 at the origin)
728
+ g1.pos = mk3(0.f, 0.f, 0.f);
729
+ g2.pos = g2.pos - origin;
730
+ GJKResult r;
731
+ float dist;
732
+ f3 x1, x2, gn = mk3(0.f, 0.f, 0.f);
733
+ const bool needs_epa = face_rec || cy_gjk_phase(tol, CY_GJK_ITERATIONS, g1, g2, &dist, &x1, &x2, r, &gn, rec, use);
734
+ Polytope pt;
735
+ pt.nface = 0; pt.nvert = 0; pt.nhorizon = 0; pt.status = 0;
736
+ int midx = -1, efid = -1, tsrc = needs_epa ? 0 : 2; // the normal's tangent: 0 the EPA face (efid), 1 the clip,
737
+ // 2 GJK's direction
738
+ if (needs_epa) {
739
+ if (face_rec) {} // (the polytope from the record, below)
740
+ else if (r.dim == 2) { polytope2(pt, r, g1, g2); if (pt.status == -1) r.dim = 3; }
741
+ else if (r.dim == 4) { polytope4(pt, r); if (pt.status == -1) r.dim = 3; }
742
+ if (!face_rec && r.dim == 3) { pt.nface = 0; pt.nvert = 0; pt.nhorizon = 0; polytope3(pt, r, g1, g2); }
743
+ if (pt.status) {
744
+ dist = r.dist; x1 = r.x1; x2 = r.x2; // (the origin on the boundary: not penetrating)
745
+ } else {
746
+ midx = face_rec ? cy_face_rec(*rec, g1, g2, pt) : cv_epa(tol, CY_EPA_ITERATIONS, pt, g1, g2, is_discrete(g1.type, g2.type));
747
+ if (midx == -1) dist = CV_FLOAT_MAX;
748
+ else dist = epa_witness(pt, midx, &x1, &x2);
749
+ efid = midx;
750
+ if (rec && !use && midx > -1 && is_discrete(g1.type, g2.type)) { // kind 1's record (box, mesh)
751
+ int fv[3];
752
+ face_verts(pt.face[midx], fv);
753
+ rec->kind = 1;
754
+ rec->n = midx;
755
+ for (int k = 0; k < 3; k++) {
756
+ rec->v1[k] = pt.vidx[2 * fv[k]]; rec->v2[k] = pt.vidx[2 * fv[k] + 1]; rec->fv[k] = fv[k];
757
+ }
758
+ rec->c[0] = cy_val(pt.center.x); rec->c[1] = cy_val(pt.center.y); rec->c[2] = cy_val(pt.center.z);
759
+ }
760
+ }
761
+ }
762
+ if (!(dist < 0.f)) return;
763
+ const bool f1 = g1.type == 3 || g1.type == 5 || g1.type == 6, f2 = g2.type == 3 || g2.type == 5 || g2.type == 6;
764
+ if (!((f1 && f2) || (g1.type == 2 && f2) || (f1 && g2.type == 2))) midx = -1; // (_supports_multiccd)
765
+ else if (!needs_epa && r.dim > 0) { // the GJK simplex as the multicontact's polytope face
766
+ cy_simplex_to_epa(r, pt);
767
+ midx = 0;
768
+ }
769
+ f3 w1[4], w2[4];
770
+ float dists[4] = {0.f, 0.f, 0.f, 0.f};
771
+ int nc = 1;
772
+ w1[0] = x1; w2[0] = x2;
773
+ CyBuf mb;
774
+ mb.cset = 0;
775
+ if (midx > -1) {
776
+ nc = cy_multicontact(mb, pt, midx, x1, x2, g1, g2, w1, w2, dists);
777
+ if (nc < 1) { nc = 1; w1[0] = x1; w2[0] = x2; }
778
+ if (mb.cset == 2) o.unsupported |= 8;
779
+ if (nc > 1 || mb.cset) tsrc = mb.cset ? 1 : tsrc;
780
+ }
781
+ f3 nv = nz3(w1[0] - w2[0]);
782
+ f3 tn = nv; // (CLEAN_NORMAL) the direction whose tangent the normal takes
783
+ if (tsrc == 1) tn = mb.cdir;
784
+ else if (tsrc == 2) tn = gn;
785
+ else {
786
+ int fq[3];
787
+ face_verts(pt.face[efid], fq);
788
+ f3 m0 = pt.vert[2 * fq[0]] - pt.vert[2 * fq[0] + 1], m1 = pt.vert[2 * fq[1]] - pt.vert[2 * fq[1] + 1],
789
+ m2 = pt.vert[2 * fq[2]] - pt.vert[2 * fq[2] + 1];
790
+ tn = nz3(cr3(m1 - m0, m2 - m0));
791
+ }
792
+ nv = cy_clean(nv, tn);
793
+ float nrm[3] = {nv.x, nv.y, nv.z}, fr[9];
794
+ make_frame(nrm, fr);
795
+ for (int i = 0; i < nc; i++) {
796
+ const float di = nc > 1 ? dists[i] : dist;
797
+ if (di < 0.f) sink_put(o, i, di, 0.5f * (w1[i] + w2[i]) + origin, nrm, fr);
798
+ }
799
+ }
800
+ """
801
+
802
+
803
+ def instantiate(ns, real):
804
+ """core_text() + MULTI + ENTRY over scalar type real in namespace ns, with its sink (dist, pos, normal, frame) and
805
+ make_frame (step.py's arithmetic without the explicit roundings: the same function); cy_clean(nv, tn): nv, with
806
+ tn's tangent (sign matched) when real is D1 or DN (dual.dn_device: CY_NT tangents)."""
807
+ c16, s16 = _cs16()
808
+ body = core_text() + MULTI.replace("@COS16@", c16).replace("@SIN16@", s16) + ENTRY
809
+ body = re.sub(r"\bfloat\b", "real", body)
810
+ body = re.sub(r"\b(fabs|sqrt|fmin|fmax)f\(", r"t_\1(", body)
811
+ clean = ("__device__ __forceinline__ f3 cy_clean(f3 nv, f3 tn) { // (CLEAN_NORMAL)\n"
812
+ " const int sg = (nv.x * tn.x + nv.y * tn.y + nv.z * tn.z).v < 0.f ? -1 : 1;\n"
813
+ " nv.x.d = sg * tn.x.d; nv.y.d = sg * tn.y.d; nv.z.d = sg * tn.z.d;\n return nv;\n}\n"
814
+ if real == "D1" else
815
+ "__device__ __forceinline__ f3 cy_clean(f3 nv, f3 tn) { // (CLEAN_NORMAL; each tangent as D1's)\n"
816
+ " const int sg = (nv.x * tn.x + nv.y * tn.y + nv.z * tn.z).v < 0.f ? -1 : 1;\n"
817
+ " DN_SIGNED_TANGENTS(nv.x, sg, tn.x); DN_SIGNED_TANGENTS(nv.y, sg, tn.y); DN_SIGNED_TANGENTS(nv.z, sg, tn.z);\n"
818
+ " return nv;\n}\n"
819
+ if real == "DN" else "__device__ __forceinline__ f3 cy_clean(f3 nv, f3) { return nv; }\n")
820
+ head = r"""
821
+ namespace @NS@ { // g1_engine.cylccd over @REAL@
822
+ using real = @REAL@;
823
+ typedef float flt;
824
+ __device__ __forceinline__ flt cy_val(real x) { return @VAL@; } // (the value)
825
+ #define CY_SINK_MAX 4
826
+ struct Sink {
827
+ int n, unsupported;
828
+ int slot[CY_SINK_MAX];
829
+ real dist[CY_SINK_MAX], pos[CY_SINK_MAX][3], nrm[CY_SINK_MAX][3], fr[CY_SINK_MAX][9];
830
+ };
831
+ __device__ __forceinline__ void make_frame(const real* n, real* fr) { // (as step.py's, without explicit roundings)
832
+ real b[3] = {0.f, 0.f, 0.f};
833
+ if (-0.5f < n[1] && n[1] < 0.5f) b[1] = 1.f; else b[2] = 1.f;
834
+ real d = n[0] * b[0] + n[1] * b[1] + n[2] * b[2];
835
+ for (int k = 0; k < 3; k++) b[k] = b[k] - n[k] * d;
836
+ real bn = t_sqrt(b[0] * b[0] + b[1] * b[1] + b[2] * b[2]);
837
+ for (int k = 0; k < 3; k++) b[k] = b[k] / bn;
838
+ real c[3] = {n[1] * b[2] - n[2] * b[1], n[2] * b[0] - n[0] * b[2], n[0] * b[1] - n[1] * b[0]};
839
+ for (int k = 0; k < 3; k++) { fr[k] = n[k]; fr[3 + k] = b[k]; fr[6 + k] = c[k]; }
840
+ }
841
+ """
842
+ tail = r"""
843
+ } // namespace @NS@
844
+ """
845
+ sink = r"""
846
+ __device__ __forceinline__ void sink_put(Sink& o, int slot, real dist, f3 pc, const real* nrm, const real* frame) {
847
+ if (o.n >= CY_SINK_MAX) { o.unsupported |= 4; return; }
848
+ o.slot[o.n] = slot; o.dist[o.n] = dist;
849
+ o.pos[o.n][0] = pc.x; o.pos[o.n][1] = pc.y; o.pos[o.n][2] = pc.z;
850
+ for (int k = 0; k < 3; k++) o.nrm[o.n][k] = nrm[k];
851
+ for (int k = 0; k < 9; k++) o.fr[o.n][k] = frame[k];
852
+ o.n++;
853
+ }
854
+ """
855
+ i = body.index("// ------------------------------------------------------------- the pair")
856
+ body = body[:i] + clean + sink + body[i:]
857
+ if real == "DN":
858
+ outl = ("cv_gjk", "cy_gjk_rec", "polytope2", "cy_pair")
859
+ n = [0]
860
+
861
+ def mark(mt):
862
+ n[0] += mt.group(2) in outl
863
+ return f"__device__ {'__noinline__' if mt.group(2) in outl else ''} {mt.group(1)}{mt.group(2)}("
864
+ body = re.sub(r"^__device__ (?!__)([\w:]+[ *&]+)(\w+)\(", mark, body, flags=re.M)
865
+ if n[0] != len(outl):
866
+ raise RuntimeError("cylccd.instantiate: not every out-of-line function of the D1 instance found")
867
+ return ((head + body + tail).replace("@NS@", ns).replace("@REAL@", real)
868
+ .replace("@VAL@", "x" if real == "float" else "x.v"))
869
+
870
+
871
+ GLOBAL = r"""
872
+ // convex pairs with a cylinder (g1_engine.cylccd): the forward over RF (cycr), the adjoint's replay over D1 (cycd)
873
+ @CSINK@
874
+ template <class R>
875
+ __device__ __forceinline__ void cyc_geom(int t, const float* p, const float* M, const float* s, R* P, R* Q, R* S) {
876
+ for (int k = 0; k < 3; k++) { P[k] = R(p[k]); S[k] = R(s[k]); }
877
+ for (int k = 0; k < 9; k++) Q[k] = R(M[k]);
878
+ }
879
+ #if CY_HAS_MESH
880
+ #define CY_MESH(g) c_gmesh[g]
881
+ #else
882
+ #define CY_MESH(g) -1
883
+ #endif
884
+ template <class NS_GEOM, class R>
885
+ __device__ __forceinline__ NS_GEOM cyc_cgeom(int t, int gi, const R* P, const R* Q, const R* S) {
886
+ NS_GEOM c;
887
+ c.mesh = t == 6 ? CY_MESH(gi) : -1;
888
+ c.pos.x = P[0]; c.pos.y = P[1]; c.pos.z = P[2];
889
+ for (int k = 0; k < 9; k++) c.R[k] = Q[k];
890
+ c.size.x = S[0]; c.size.y = S[1]; c.size.z = S[2];
891
+ c.type = t;
892
+ c.index = -1;
893
+ return c;
894
+ }
895
+ // the forward's contacts of the pair (types t1, t2; centres, quaternions, sizes): the bits of the replay's values
896
+ // (rec, use: the adjoint's record, cycr::cy_pair's; null in the forward)
897
+ __device__ __noinline__ void cyc_pair_x(int t1, int g1, const float* p1, const float* q1, const float* s1, int t2,
898
+ int g2, const float* p2, const float* q2, const float* s2, CSink& o,
899
+ CyRec* rec, bool use) {
900
+ float R1[9], R2[9];
901
+ quat2mat(q1, R1);
902
+ quat2mat(q2, R2);
903
+ RF P1[3], Q1[9], S1[3], P2[3], Q2[9], S2[3];
904
+ cyc_geom<RF>(t1, p1, R1, s1, P1, Q1, S1);
905
+ cyc_geom<RF>(t2, p2, R2, s2, P2, Q2, S2);
906
+ cycr::Sink d;
907
+ cycr::cy_pair(cyc_cgeom<cycr::CGeom, RF>(t1, g1, P1, Q1, S1), cyc_cgeom<cycr::CGeom, RF>(t2, g2, P2, Q2, S2), d, rec,
908
+ use);
909
+ o.n = d.n; o.unsupported = d.unsupported;
910
+ for (int i = 0; i < d.n; i++) {
911
+ o.slot[i] = d.slot[i]; o.dist[i] = d.dist[i].v;
912
+ for (int k = 0; k < 3; k++) o.pos[i][k] = d.pos[i][k].v;
913
+ for (int k = 0; k < 9; k++) o.fr[i][k] = d.fr[i][k].v;
914
+ }
915
+ }
916
+ __device__ __forceinline__ void cyc_pair_r(int t1, int g1, const float* p1, const float* q1, const float* s1, int t2,
917
+ int g2, const float* p2, const float* q2, const float* s2, CSink& o) {
918
+ cyc_pair_x(t1, g1, p1, q1, s1, t2, g2, p2, q2, s2, o, nullptr, false);
919
+ }
920
+ """
921
+
922
+ FWD = """ if """ + COND + """ { // convex pairs with a cylinder (g1_engine.cylccd: MuJoCo Warp 3.17's CCD)
923
+ CSink o;
924
+ cyc_pair_r(t1, g1, p1, q1, sz1, t2, g2, p2, q2, sz2, o);
925
+ for (int i = 0; i < o.n; i++) add_contact(s, pair, o.slot[i], o.dist[i], o.pos[i], o.fr[i]);
926
+ if (o.unsupported) atomicOr(&s.unsupported, o.unsupported);
927
+ return;
928
+ }
929
+ """
930
+
931
+ ADJ_FN = r"""
932
+ // the forward's contact `slot` of a convex pair with a cylinder (dist, pos, fr: its bits) and, with cot, its VJP onto
933
+ // the geoms' poses gb (g1_engine.cylccd): the pair replayed over D1 once per pose direction of each geom (position;
934
+ // rotation about the world axes about the geom's centre: the rotation's columns turn with it). Returns -1 when the
935
+ // slot is not a contact. rec (may be null): the contact's record on this lane (CyRec; kind -1 before the replay):
936
+ // the replay fills it (the search's discrete choices, checked to reproduce the forward's contacts bit for bit over
937
+ // RF, else kind 0, and the slot's dist, pos, frame); a call with cot after the replay on the lane does not replay
938
+ // again, and with kind 1 or 2 the D1 replays rebuild the final EPA face or GJK simplex from it instead of searching
939
+ __device__ __noinline__ int cyc_adj(int t1, const float* p1, const float* q1, const float* s1, int t2, const float* p2,
940
+ const float* q2, const float* s2, int slot, const float* cot, float* gb,
941
+ float* dist, float* pos, float* fr, CyRec* rec) {
942
+ CyRec lrec;
943
+ if (!rec) { rec = &lrec; rec->kind = -1; }
944
+ const int g1 = (int)(s1 - c_gsize) / 3, g2 = (int)(s2 - c_gsize) / 3; // (the geoms' rows: their sizes' offsets)
945
+ if (cot && rec->kind >= 0) { // (the replay ran on this lane)
946
+ *dist = rec->dist;
947
+ for (int k = 0; k < 3; k++) pos[k] = rec->pos[k];
948
+ for (int k = 0; k < 9; k++) fr[k] = rec->fr[k];
949
+ } else {
950
+ CSink o;
951
+ #if CY_REC
952
+ cyc_pair_x(t1, g1, p1, q1, s1, t2, g2, p2, q2, s2, o, rec, false);
953
+ #else
954
+ cyc_pair_r(t1, g1, p1, q1, s1, t2, g2, p2, q2, s2, o);
955
+ rec->kind = 0;
956
+ #endif
957
+ int c = -1;
958
+ for (int i = 0; i < o.n; i++) if (o.slot[i] == slot) c = i;
959
+ if (c < 0) { rec->kind = -1; return -1; }
960
+ *dist = o.dist[c];
961
+ for (int k = 0; k < 3; k++) pos[k] = o.pos[c][k];
962
+ for (int k = 0; k < 9; k++) fr[k] = o.fr[c][k];
963
+ #if CY_REC
964
+ if (rec->kind > 0) { // the record's contact `slot` over RF: the forward's bits, else the full replay
965
+ cyc_pair_x(t1, g1, p1, q1, s1, t2, g2, p2, q2, s2, o, rec, true);
966
+ c = -1;
967
+ for (int i = 0; i < o.n; i++) if (o.slot[i] == slot) c = i;
968
+ bool same = c >= 0 && __float_as_int(o.dist[c]) == __float_as_int(*dist);
969
+ for (int k = 0; k < 3; k++) same = same && __float_as_int(o.pos[c][k]) == __float_as_int(pos[k]);
970
+ for (int k = 0; k < 9; k++) same = same && __float_as_int(o.fr[c][k]) == __float_as_int(fr[k]);
971
+ if (!same) rec->kind = 0;
972
+ }
973
+ #endif
974
+ rec->dist = *dist;
975
+ for (int k = 0; k < 3; k++) rec->pos[k] = pos[k];
976
+ for (int k = 0; k < 9; k++) rec->fr[k] = fr[k];
977
+ }
978
+ if (!cot) return 0;
979
+ const bool use = rec->kind > 0;
980
+ float nbar[3], R1[9], R2[9];
981
+ make_frame_vjp(fr, cot + 4, nbar);
982
+ quat2mat(q1, R1);
983
+ quat2mat(q2, R2);
984
+ #if CY_NT > 1
985
+ // CY_NT directions per pass, one tangent each (DN: the values computed once, each tangent by D1's expressions;
986
+ // not D1's bits, NT_HEAD)
987
+ for (int j0 = 0; j0 < 12; j0 += CY_NT) {
988
+ DN P1[3], Q1[9], S1[3], P2[3], Q2[9], S2[3];
989
+ cyc_geom<DN>(t1, p1, R1, s1, P1, Q1, S1);
990
+ cyc_geom<DN>(t2, p2, R2, s2, P2, Q2, S2);
991
+ for (int k = 0; k < CY_NT; k++) {
992
+ const int j = j0 + k, g = j / 6, jj = j % 6; // geom g, direction jj
993
+ const float* R = g == 0 ? R1 : R2;
994
+ float ea[3] = {0.f, 0.f, 0.f};
995
+ ea[jj % 3] = 1.f;
996
+ DN* P = g == 0 ? P1 : P2;
997
+ DN* Q = g == 0 ? Q1 : Q2;
998
+ if (jj < 3) DN_D(P[jj], k) = 1.f;
999
+ else
1000
+ for (int cc = 0; cc < 3; cc++) { // d col = e x col
1001
+ float col[3] = {R[cc], R[3 + cc], R[6 + cc]}, dc[3];
1002
+ cross(ea, col, dc);
1003
+ for (int r = 0; r < 3; r++) DN_D(Q[3 * r + cc], k) = dc[r];
1004
+ }
1005
+ }
1006
+ cycd::Sink d;
1007
+ cycd::cy_pair(cyc_cgeom<cycd::CGeom, DN>(t1, g1, P1, Q1, S1), cyc_cgeom<cycd::CGeom, DN>(t2, g2, P2, Q2, S2), d,
1008
+ use ? rec : nullptr, use);
1009
+ int cd = -1;
1010
+ for (int i = 0; i < d.n; i++) if (d.slot[i] == slot) cd = i;
1011
+ for (int k = 0; k < CY_NT; k++) {
1012
+ if (cd < 0) { gb[j0 + k] = 0.f; continue; } // (not reached: the replay's values are the forward's bits)
1013
+ float gj = cot[0] * DN_D(d.dist[cd], k);
1014
+ for (int t = 0; t < 3; t++) gj += cot[1 + t] * DN_D(d.pos[cd][t], k) + nbar[t] * DN_D(d.nrm[cd][t], k);
1015
+ gb[j0 + k] = gj;
1016
+ }
1017
+ }
1018
+ #else
1019
+ for (int j = 0; j < 12; j++) {
1020
+ const int g = j / 6, jj = j % 6; // geom g, direction jj
1021
+ const float* R = g == 0 ? R1 : R2;
1022
+ float ea[3] = {0.f, 0.f, 0.f};
1023
+ ea[jj % 3] = 1.f;
1024
+ D1 P1[3], Q1[9], S1[3], P2[3], Q2[9], S2[3];
1025
+ cyc_geom<D1>(t1, p1, R1, s1, P1, Q1, S1);
1026
+ cyc_geom<D1>(t2, p2, R2, s2, P2, Q2, S2);
1027
+ D1* P = g == 0 ? P1 : P2;
1028
+ D1* Q = g == 0 ? Q1 : Q2;
1029
+ if (jj < 3) P[jj].d = 1.f;
1030
+ else
1031
+ for (int cc = 0; cc < 3; cc++) { // d col = e x col
1032
+ float col[3] = {R[cc], R[3 + cc], R[6 + cc]}, dc[3];
1033
+ cross(ea, col, dc);
1034
+ for (int r = 0; r < 3; r++) Q[3 * r + cc].d = dc[r];
1035
+ }
1036
+ cycd::Sink d;
1037
+ cycd::cy_pair(cyc_cgeom<cycd::CGeom, D1>(t1, g1, P1, Q1, S1), cyc_cgeom<cycd::CGeom, D1>(t2, g2, P2, Q2, S2), d,
1038
+ use ? rec : nullptr, use);
1039
+ int cd = -1;
1040
+ for (int i = 0; i < d.n; i++) if (d.slot[i] == slot) cd = i;
1041
+ if (cd < 0) { gb[j] = 0.f; continue; } // (not reached: the replay's values are the forward's bits)
1042
+ float gj = cot[0] * d.dist[cd].d;
1043
+ for (int t = 0; t < 3; t++) gj += cot[1 + t] * d.pos[cd][t].d + nbar[t] * d.nrm[cd][t].d;
1044
+ gb[j] = gj;
1045
+ }
1046
+ #endif
1047
+ return 0;
1048
+ }
1049
+ """
1050
+
1051
+ ADJ = """ if """ + COND + """ { // convex pairs with a cylinder (g1_engine.cylccd): the forward's contact `slot`, VJP by D1
1052
+ if (cyc_adj(t1, p1, q1, sz1, t2, p2, q2, sz2, slot, cot, gb, dist, pos, fr, crec) < 0) return -1;
1053
+ if (!(-0.5f < fr[1] && fr[1] < 0.5f)) br |= ADJ_BR_FRAME_Z;
1054
+ return br;
1055
+ }
1056
+ """
1057
+
1058
+
1059
+ def device():
1060
+ """RF and D1 or DN (CY_NT > 1: the adjoint's replay with CY_NT tangents per pass) instances (with the duals' and
1061
+ RF's device code, once), and the forward's wrapper."""
1062
+ from nablaengine.dual import DUAL_DEVICE, RF_DEVICE, dn_device
1063
+ csink = ("#ifndef CSINK_DEFINED\n#define CSINK_DEFINED\n#define SINK_MAX 8\nstruct CSink {\n int n, unsupported;\n"
1064
+ " int slot[SINK_MAX];\n float dist[SINK_MAX], pos[SINK_MAX][3], fr[SINK_MAX][9];\n};\n#endif")
1065
+ return (DUAL_DEVICE + "#ifndef DK_RF_DEVICE\n#define DK_RF_DEVICE\n" + RF_DEVICE + "#endif\n" + CYREC
1066
+ + NT_HEAD.replace("@NT@", str(ccd_nt())) + "#if CY_NT > 1\n#define DN_K CY_NT\n" + dn_device() + "#endif\n"
1067
+ + instantiate("cycr", "RF") + "#if CY_NT > 1\n" + instantiate("cycd", "DN") + "#else\n"
1068
+ + instantiate("cycd", "D1") + "#endif\n" + GLOBAL.replace("@CSINK@", csink))
1069
+
1070
+
1071
+ def ccd_nt():
1072
+ """$DK_CCD_NT (default 4): the CCD replay's tangents per pass (CY_NT, NT_HEAD)."""
1073
+ import os
1074
+ v = (os.environ.get("DK_CCD_NT") or "4").strip()
1075
+ if v not in ("1", "2", "3", "4", "6", "12"):
1076
+ raise ValueError(f"DK_CCD_NT={v!r}: one of 1, 2, 3, 4, 6, 12")
1077
+ return int(v)
1078
+
1079
+
1080
+ NT_HEAD = """#ifndef CY_NT
1081
+ #define CY_NT @NT@
1082
+ #endif
1083
+ #if 12 % CY_NT != 0
1084
+ #error "CY_NT: one of 1, 2, 3, 4, 6, 12"
1085
+ #endif
1086
+ """
1087
+
1088
+
1089
+ CYREC = r"""
1090
+ #ifndef CY_REC
1091
+ #define CY_REC 1 // (0: cyc_adj without its record, model_hooks' DK_CCD_FLOAT experiment)
1092
+ #endif
1093
+ // a convex contact's record in the adjoint (g1_engine.cylccd, cy_pair, cyc_adj): kind -1 none, 0 the full replay,
1094
+ // 1 the final EPA face of discrete supports (v1, v2: its vertices' features on geom 1 and 2, fv: their polytope
1095
+ // indices, n: the face's, c: the polytope's centre), 2 the shrunk shapes' final GJK simplex (n vertices, v1, v2);
1096
+ // the slot's dist, pos, frame (the replay's)
1097
+ struct CyRec {
1098
+ int kind, n;
1099
+ int v1[4], v2[4], fv[3];
1100
+ float c[3];
1101
+ float dist, pos[3], fr[9];
1102
+ };
1103
+ """
1104
+
1105
+
1106
+ def apply_rec(src):
1107
+ """src (an adjoint text with cyc_adj) with the contact's record handed from adj_contact_one's replay call of
1108
+ adj_pair_geom to its VJP call (cyc_adj does not replay again): a parameter CyRec* crec after the last one of
1109
+ adj_contact_geom, adj_pair_geom (and adj_pair_geom_aux, terrain builds), passed through by them, the record a lane
1110
+ variable of adj_contact_one (its two calls), null for any other caller. Applied after every other edit."""
1111
+ heads = ("__device__ __noinline__ int adj_contact_geom(", "__device__ __forceinline__ int adj_pair_geom(",
1112
+ "__device__ __forceinline__ int adj_pair_geom_aux(")
1113
+ for h in heads:
1114
+ n = src.count(h)
1115
+ if n == 0 and h != heads[2]:
1116
+ raise RuntimeError(f"cylccd.apply_rec: no {h!r}")
1117
+ if n > 1:
1118
+ raise RuntimeError(f"cylccd.apply_rec: {h!r} {n} times")
1119
+ if n:
1120
+ j = src.index(") {", src.index(h))
1121
+ src = src[:j] + ", CyRec* crec" + src[j:]
1122
+ out, i, nrec = [], 0, 0
1123
+ for mt in re.finditer(r"\b(adj_contact_geom|adj_pair_geom|adj_pair_geom_aux)\(", src):
1124
+ if src[max(0, mt.start() - 4):mt.start()] == "int ":
1125
+ continue
1126
+ k, depth = mt.end(), 1
1127
+ while depth:
1128
+ depth += {"(": 1, ")": -1}.get(src[k], 0)
1129
+ k += 1
1130
+ args = src[mt.end():k - 1]
1131
+ if "&nu, nullptr, nullptr" in args or "&nu2, cot, gb" in args:
1132
+ arg, nrec = "&crec", nrec + 1
1133
+ elif re.search(r"\bcot, gb(, mvid)?$", args):
1134
+ arg = "crec"
1135
+ else:
1136
+ arg = "nullptr"
1137
+ out.append(src[i:k - 1] + ", " + arg)
1138
+ i = k - 1
1139
+ src = "".join(out) + src[i:]
1140
+ if nrec != 2:
1141
+ raise RuntimeError(f"cylccd.apply_rec: {nrec} adj_contact_one calls (expected 2)")
1142
+ first = re.search(r"\n( *)(const int br = adj_pair_geom(_aux)?\(pair, slot, [^\n]*&crec\);\n)", src)
1143
+ if first is None:
1144
+ raise RuntimeError("cylccd.apply_rec: no replay call in adj_contact_one")
1145
+ decl = f"\n{first.group(1)}CyRec crec; // (g1_engine.cylccd: the replay's record for the VJP's call)\n" \
1146
+ f"{first.group(1)}crec.kind = -1;\n{first.group(1)}"
1147
+ return src[:first.start()] + decl + first.group(2) + src[first.end():]
1148
+
1149
+
1150
+ def hooks():
1151
+ """The (anchor, replacement, count) edits of the engine text for convex pairs with a cylinder."""
1152
+ sphere_anchor = " atomicOr(&s.unsupported, 1); // other type combinations do not occur in the G1 model\n"
1153
+ dev_anchor = "template <class S>\n__device__ DK_INL_COLLIDE void collide_pair(S& s, int pair) {"
1154
+ adj_head = "__device__ __noinline__ int adj_contact_geom("
1155
+ return ((sphere_anchor, FWD + sphere_anchor, 1),
1156
+ (dev_anchor, device() + dev_anchor, 1),
1157
+ (adj_head, ADJ_FN + adj_head, 1),
1158
+ (" if (t1 != 2 || t2 != 2) return -1;\n", ADJ + " if (t1 != 2 || t2 != 2) return -1;\n", 1))