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
nablaengine/ccd.py ADDED
@@ -0,0 +1,1122 @@
1
+ """MuJoCo Warp's general convex collision for box-box pairs (native CCD: GJK, EPA and multicontact by polygon
2
+ clipping), translated to CUDA for one thread per pair (mujoco_warp/_src/collision_gjk.py and collision_convex.py,
3
+ Copyright 2025 The Newton Developers, Apache License 2.0; their order of operations, so that the contacts agree with
4
+ MuJoCo Warp's up to float rounding). Used by the G1 engine for models with box-box pairs (g1_engine.model_hooks)."""
5
+ import os
6
+
7
+
8
+ def gjk_mj4():
9
+ """$DK_GJK_MJ4 at source generation (docs/configuration.md): 0 (default) MuJoCo Warp 3.17's GJK, 1 MuJoCo Warp
10
+ 4.0's (collision_gjk.gjk): the termination tests read the search direction as tuned for discrete geoms (x_dir,
11
+ not x_k, whose own direction can be off by more than the gap in float32), and after the first iteration the
12
+ stall test does not compare with the initial guess's norm (no simplex point)."""
13
+ raw = os.environ.get("DK_GJK_MJ4", "") or "0"
14
+ if raw not in ("0", "1"):
15
+ raise ValueError(f"DK_GJK_MJ4={raw!r}: 0 or 1")
16
+ return raw == "1"
17
+
18
+
19
+ GJK_MJ4_HOOKS = (
20
+ ("f3 dir_neg = x_k / xnorm;", "f3 dir_neg = x_k / xnorm, x_dir = x_k; // (DK_GJK_MJ4)"),
21
+ ("if (dn > CV_MINVAL) dir_neg = dir_neg / dn;",
22
+ "if (dn > CV_MINVAL) { dir_neg = dir_neg / dn; x_dir = xnorm * dir_neg; }"),
23
+ ("if (nn > CV_MINVAL) dir_neg = cvsign(dt3(dir_neg, nrm)) * nrm / nn;",
24
+ "if (nn > CV_MINVAL) { dir_neg = cvsign(dt3(dir_neg, nrm)) * nrm / nn; x_dir = xnorm * dir_neg; }"),
25
+ ("if (dt3(x_k, x_k - simplex[n]) < epsilon) break;", "if (dt3(x_dir, x_dir - simplex[n]) < epsilon) break;"),
26
+ ("lower = dt3(x_k, simplex[n]);", "lower = dt3(x_dir, simplex[n]);"),
27
+ (" xnorm_prev = xnorm;\n", " xnorm_prev = xnorm;\n if (it == 0) xnorm_prev = 0.f; // (DK_GJK_MJ4: the guess is no simplex point)\n"),
28
+ )
29
+
30
+
31
+ def apply_gjk_mj4(src):
32
+ """src with MuJoCo Warp 4.0's GJK (GJK_MJ4_HOOKS in every copy) when $DK_GJK_MJ4 is 1; src itself otherwise (and
33
+ for a text without the GJK)."""
34
+ if not gjk_mj4():
35
+ return src
36
+ counts = [src.count(a) for a, _ in GJK_MJ4_HOOKS]
37
+ if not any(counts):
38
+ return src
39
+ if len(set(counts)) != 1:
40
+ raise RuntimeError(f"DK_GJK_MJ4: the GJK anchors occur {counts} times (expected equal counts)")
41
+ for a, b in GJK_MJ4_HOOKS:
42
+ src = src.replace(a, b)
43
+ return src
44
+
45
+ def header(m):
46
+ """#defines of the box-box CCD (the model's ccd_iterations and ccd_tolerance; MuJoCo Warp's EPA runs 16 iterations
47
+ when every convex pair is box-box, else ccd_iterations: g1_engine.cylccd's pairs)."""
48
+ from nablaengine.g1_engine import cylccd
49
+ epa = int(m.opt.ccd_iterations) if cylccd.pairs(m) else 16
50
+ return (f"#define GJK_ITERATIONS {int(m.opt.ccd_iterations)}\n#define EPA_ITERATIONS {epa}\n"
51
+ f"#define CCD_TOLERANCE {float(m.opt.ccd_tolerance):.9g}f\n#define NPOLYMAX 4\n#define NMESHDEG 3\n")
52
+
53
+
54
+ DEVICE = r"""
55
+ struct f3 { float x, y, z; };
56
+ __device__ __forceinline__ f3 mk3(float x, float y, float z) { f3 r; r.x = x; r.y = y; r.z = z; return r; }
57
+ __device__ __forceinline__ f3 ld3(const float* p) { return mk3(p[0], p[1], p[2]); }
58
+ __device__ __forceinline__ f3 operator+(f3 a, f3 b) { return mk3(a.x + b.x, a.y + b.y, a.z + b.z); }
59
+ __device__ __forceinline__ f3 operator-(f3 a, f3 b) { return mk3(a.x - b.x, a.y - b.y, a.z - b.z); }
60
+ __device__ __forceinline__ f3 operator-(f3 a) { return mk3(-a.x, -a.y, -a.z); }
61
+ __device__ __forceinline__ f3 operator*(float s, f3 a) { return mk3(s * a.x, s * a.y, s * a.z); }
62
+ __device__ __forceinline__ f3 operator*(f3 a, float s) { return mk3(a.x * s, a.y * s, a.z * s); }
63
+ __device__ __forceinline__ f3 operator/(f3 a, float s) { return mk3(a.x / s, a.y / s, a.z / s); }
64
+ __device__ __forceinline__ float dt3(f3 a, f3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
65
+ __device__ __forceinline__ f3 cr3(f3 a, f3 b) { return mk3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); }
66
+ __device__ __forceinline__ float nm3(f3 a) { return sqrtf(dt3(a, a)); }
67
+ __device__ __forceinline__ f3 nz3(f3 a) { float n = nm3(a); return n > 0.f ? a / n : mk3(0.f, 0.f, 0.f); } // wp.normalize
68
+ __device__ __forceinline__ float cvsign(float x) { return x < 0.f ? -1.f : 1.f; } // wp.sign
69
+ __device__ __forceinline__ float cget(f3 a, int i) { return i == 0 ? a.x : (i == 1 ? a.y : a.z); }
70
+ __device__ __forceinline__ void cset(f3& a, int i, float v) { if (i == 0) a.x = v; else if (i == 1) a.y = v; else a.z = v; }
71
+ // R (row-major 3x3) times v, and its transpose
72
+ __device__ __forceinline__ f3 rmul(const float* R, f3 v) {
73
+ return mk3(R[0] * v.x + R[1] * v.y + R[2] * v.z, R[3] * v.x + R[4] * v.y + R[5] * v.z, R[6] * v.x + R[7] * v.y + R[8] * v.z);
74
+ }
75
+ __device__ __forceinline__ f3 rtmul(const float* R, f3 v) {
76
+ return mk3(R[0] * v.x + R[3] * v.y + R[6] * v.z, R[1] * v.x + R[4] * v.y + R[7] * v.z, R[2] * v.x + R[5] * v.y + R[8] * v.z);
77
+ }
78
+
79
+
80
+ // ---------------------------------------------------------------- convex collisions (MuJoCo Warp's collision_gjk.py)
81
+ #define CV_FLOAT_MAX 1e30f
82
+ #define CV_FLOAT_MIN (-1e30f)
83
+ #define CV_MINVAL 1e-15f
84
+ #define CV_MINVAL2 1e-30f
85
+ #define CV_MIN_DIST2 1e-10f
86
+ #define CV_MIN_DIST3 1e-10f
87
+ #define CV_MIN_DIST4 1e-17f
88
+ #define CV_MIN_EPATOL 1e-7f
89
+ #define CV_FACE_TOL 0.99605140f // cos(0.0889)
90
+ #define CV_EDGE_TOL 0.08878295f // sin(0.0889)
91
+ #define CV_INTERSECT_TOL 0.0000003f
92
+ #define EPA_NV (10 + 2 * EPA_ITERATIONS) // polytope vertices (pairs: geom 1, geom 2)
93
+ #define EPA_NF (6 + 5 * EPA_ITERATIONS) // faces (MJ_MAX_EPAFACES = 5)
94
+ #define EPA_NH 24 // horizon edges (MJ_MAX_EPAHORIZON)
95
+ #define FACE_DELETED 0x80000000u
96
+ #define FACE_INVALID 0x40000000u
97
+
98
+ // a geom as MuJoCo Warp's collision_core.Geom (the fields the convex code reads); margins are 0
99
+ struct CGeom {
100
+ f3 pos;
101
+ float R[9];
102
+ f3 size;
103
+ int type; // the engine's: 1 sphere, 2 capsule, 3 box
104
+ int index; // the support's cached vertex (MuJoCo Warp's geom.index)
105
+ };
106
+ struct SupportPoint { f3 point; int cached; int vidx; };
107
+
108
+ // support point of a geom in direction dir (MuJoCo Warp's support)
109
+ __device__ SupportPoint cv_support(const CGeom& g, f3 dir) {
110
+ SupportPoint sp;
111
+ sp.cached = -1;
112
+ sp.vidx = -1;
113
+ if (g.type == 1) { sp.point = g.pos + g.size.x * dir; return sp; }
114
+ f3 ld = rtmul(g.R, dir);
115
+ if (g.type == 3) {
116
+ f3 tmp = mk3(cvsign(ld.x), cvsign(ld.y), cvsign(ld.z));
117
+ f3 res = mk3(tmp.x * g.size.x, tmp.y * g.size.y, tmp.z * g.size.z);
118
+ sp.point = rmul(g.R, res) + g.pos;
119
+ sp.vidx = (tmp.x > 0.f ? 1 : 0) + (tmp.y > 0.f ? 2 : 0) + (tmp.z > 0.f ? 4 : 0);
120
+ return sp;
121
+ }
122
+ if (g.type == 2) {
123
+ f3 res = g.size.x * ld;
124
+ res.z += cvsign(ld.z) * g.size.y;
125
+ sp.point = rmul(g.R, res) + g.pos;
126
+ return sp;
127
+ }
128
+ return sp; // (no meshes in this module)
129
+ }
130
+
131
+ struct Simplex { f3 v[4]; };
132
+ struct GJKResult {
133
+ bool separated;
134
+ float dist;
135
+ f3 x1, x2;
136
+ int dim;
137
+ f3 simplex[4], simplex1[4], simplex2[4];
138
+ int sidx1[4], sidx2[4];
139
+ int index1, index2;
140
+ };
141
+
142
+ __device__ __forceinline__ f3 lin_combine(int n, const float* l, const f3* m) {
143
+ if (n == 1) return l[0] * m[0];
144
+ if (n == 2) return l[0] * m[0] + l[1] * m[1];
145
+ if (n == 3) return l[0] * m[0] + l[1] * m[1] + l[2] * m[2];
146
+ return l[0] * m[0] + l[1] * m[1] + l[2] * m[2] + l[3] * m[3];
147
+ }
148
+ __device__ __forceinline__ float det3f(f3 a, f3 b, f3 c) { return dt3(a, cr3(b, c)); }
149
+ __device__ __forceinline__ int same_sign(float a, float b) {
150
+ if (a > 0.f && b > 0.f) return 1;
151
+ if (a < 0.f && b < 0.f) return -1;
152
+ return 0;
153
+ }
154
+ __device__ __forceinline__ f3 proj_origin_line(f3 v1, f3 v2) {
155
+ f3 diff = v2 - v1;
156
+ float scl = -(dt3(v2, diff) / dt3(diff, diff));
157
+ return v2 + scl * diff;
158
+ }
159
+ // returns ret (1: degenerate)
160
+ __device__ __forceinline__ int proj_origin_plane(f3 v1, f3 v2, f3 v3, f3* r) {
161
+ f3 d21 = v2 - v1, d31 = v3 - v1, d32 = v3 - v2;
162
+ f3 n = cr3(d32, d21);
163
+ float nv = dt3(n, v2), nn = dt3(n, n);
164
+ if (nn == 0.f) { *r = mk3(0.f, 0.f, 0.f); return 1; }
165
+ if (nv != 0.f && nn > CV_MINVAL) { *r = (nv / nn) * n; return 0; }
166
+ n = cr3(d21, d31);
167
+ nv = dt3(n, v1); nn = dt3(n, n);
168
+ if (nn == 0.f) { *r = mk3(0.f, 0.f, 0.f); return 1; }
169
+ if (nv != 0.f && nn > CV_MINVAL) { *r = (nv / nn) * n; return 0; }
170
+ n = cr3(d31, d32);
171
+ nv = dt3(n, v3); nn = dt3(n, n);
172
+ *r = (nv / nn) * n;
173
+ return 0;
174
+ }
175
+ __device__ void S1D(f3 s1, f3 s2, float* l) {
176
+ f3 p_o = proj_origin_line(s1, s2);
177
+ float mu_max = s1.x - s2.x;
178
+ int index = 0;
179
+ float mu = s1.y - s2.y;
180
+ if (fabsf(mu) >= fabsf(mu_max)) { mu_max = mu; index = 1; }
181
+ mu = s1.z - s2.z;
182
+ if (fabsf(mu) >= fabsf(mu_max)) { mu_max = mu; index = 2; }
183
+ float C1 = cget(p_o, index) - cget(s2, index), C2 = cget(s1, index) - cget(p_o, index);
184
+ if (same_sign(mu_max, C1) && same_sign(mu_max, C2)) { l[0] = C1 / mu_max; l[1] = C2 / mu_max; return; }
185
+ l[0] = 0.f; l[1] = 1.f;
186
+ }
187
+ __device__ void S2D(f3 s1, f3 s2, f3 s3, float* l) {
188
+ f3 p_o;
189
+ if (proj_origin_plane(s1, s2, s3, &p_o)) { S1D(s1, s2, l); l[2] = 0.f; return; }
190
+ float M_14 = s2.y * s3.z - s2.z * s3.y - s1.y * s3.z + s1.z * s3.y + s1.y * s2.z - s1.z * s2.y;
191
+ float M_24 = s2.x * s3.z - s2.z * s3.x - s1.x * s3.z + s1.z * s3.x + s1.x * s2.z - s1.z * s2.x;
192
+ float M_34 = s2.x * s3.y - s2.y * s3.x - s1.x * s3.y + s1.y * s3.x + s1.x * s2.y - s1.y * s2.x;
193
+ float M_max, a1, a2, b1, b2, c1, c2, p1, p2;
194
+ float mu1 = fabsf(M_14), mu2 = fabsf(M_24), mu3 = fabsf(M_34);
195
+ if (mu1 >= mu2 && mu1 >= mu3) { M_max = M_14; a1 = s1.y; a2 = s1.z; b1 = s2.y; b2 = s2.z; c1 = s3.y; c2 = s3.z; p1 = p_o.y; p2 = p_o.z; }
196
+ else if (mu2 >= mu3) { M_max = M_24; a1 = s1.x; a2 = s1.z; b1 = s2.x; b2 = s2.z; c1 = s3.x; c2 = s3.z; p1 = p_o.x; p2 = p_o.z; }
197
+ else { M_max = M_34; a1 = s1.x; a2 = s1.y; b1 = s2.x; b2 = s2.y; c1 = s3.x; c2 = s3.y; p1 = p_o.x; p2 = p_o.y; }
198
+ float C31 = p1 * b2 + p2 * c1 + b1 * c2 - p1 * c2 - p2 * b1 - c1 * b2;
199
+ float C32 = p1 * c2 + p2 * a1 + c1 * a2 - p1 * a2 - p2 * c1 - a1 * c2;
200
+ float C33 = p1 * a2 + p2 * b1 + a1 * b2 - p1 * b2 - p2 * a1 - b1 * a2;
201
+ int comp1 = same_sign(M_max, C31), comp2 = same_sign(M_max, C32), comp3 = same_sign(M_max, C33);
202
+ if (comp1 && comp2 && comp3) { l[0] = C31 / M_max; l[1] = C32 / M_max; l[2] = C33 / M_max; return; }
203
+ float dmin = CV_FLOAT_MAX, sub[2];
204
+ l[0] = l[1] = l[2] = 0.f;
205
+ if (!comp1) {
206
+ S1D(s2, s3, sub);
207
+ f3 x = sub[0] * s2 + sub[1] * s3;
208
+ l[0] = 0.f; l[1] = sub[0]; l[2] = sub[1];
209
+ dmin = dt3(x, x);
210
+ }
211
+ if (!comp2) {
212
+ S1D(s1, s3, sub);
213
+ f3 x = sub[0] * s1 + sub[1] * s3;
214
+ float d = dt3(x, x);
215
+ if (d < dmin) { l[0] = sub[0]; l[1] = 0.f; l[2] = sub[1]; dmin = d; }
216
+ }
217
+ if (!comp3) {
218
+ S1D(s1, s2, sub);
219
+ f3 x = sub[0] * s1 + sub[1] * s2;
220
+ float d = dt3(x, x);
221
+ if (d < dmin) { l[0] = sub[0]; l[1] = sub[1]; l[2] = 0.f; }
222
+ }
223
+ }
224
+ __device__ void S3D(f3 s1, f3 s2, f3 s3, f3 s4, float* l) {
225
+ float C41 = -det3f(s2, s3, s4), C42 = det3f(s1, s3, s4), C43 = -det3f(s1, s2, s4), C44 = det3f(s1, s2, s3);
226
+ float m_det = C41 + C42 + C43 + C44;
227
+ int comp1 = same_sign(m_det, C41), comp2 = same_sign(m_det, C42), comp3 = same_sign(m_det, C43),
228
+ comp4 = same_sign(m_det, C44);
229
+ if (comp1 && comp2 && comp3 && comp4) { l[0] = C41 / m_det; l[1] = C42 / m_det; l[2] = C43 / m_det; l[3] = C44 / m_det; return; }
230
+ l[0] = l[1] = l[2] = l[3] = 0.f;
231
+ float dmin = CV_FLOAT_MAX, sub[3];
232
+ if (!comp1) {
233
+ S2D(s2, s3, s4, sub);
234
+ f3 x = sub[0] * s2 + sub[1] * s3 + sub[2] * s4;
235
+ l[0] = 0.f; l[1] = sub[0]; l[2] = sub[1]; l[3] = sub[2];
236
+ dmin = dt3(x, x);
237
+ }
238
+ if (!comp2) {
239
+ S2D(s1, s3, s4, sub);
240
+ f3 x = sub[0] * s1 + sub[1] * s3 + sub[2] * s4;
241
+ float d = dt3(x, x);
242
+ if (d < dmin) { l[0] = sub[0]; l[1] = 0.f; l[2] = sub[1]; l[3] = sub[2]; dmin = d; }
243
+ }
244
+ if (!comp3) {
245
+ S2D(s1, s2, s4, sub);
246
+ f3 x = sub[0] * s1 + sub[1] * s2 + sub[2] * s4;
247
+ float d = dt3(x, x);
248
+ if (d < dmin) { l[0] = sub[0]; l[1] = sub[1]; l[2] = 0.f; l[3] = sub[2]; dmin = d; }
249
+ }
250
+ if (!comp4) {
251
+ S2D(s1, s2, s3, sub);
252
+ f3 x = sub[0] * s1 + sub[1] * s2 + sub[2] * s3;
253
+ float d = dt3(x, x);
254
+ if (d < dmin) { l[0] = sub[0]; l[1] = sub[1]; l[2] = sub[2]; l[3] = 0.f; }
255
+ }
256
+ }
257
+ __device__ __forceinline__ void subdistance(int n, const f3* s, float* l) {
258
+ if (n == 4) { S3D(s[0], s[1], s[2], s[3], l); return; }
259
+ if (n == 3) { S2D(s[0], s[1], s[2], l); l[3] = 0.f; return; }
260
+ if (n == 2) { S1D(s[0], s[1], l); l[2] = l[3] = 0.f; return; }
261
+ l[0] = 1.f; l[1] = l[2] = l[3] = 0.f;
262
+ }
263
+
264
+ __device__ __forceinline__ bool is_discrete(int t1, int t2) { return (t1 == 3 || t1 == 4) && (t2 == 3 || t2 == 4); }
265
+
266
+ // GJK (MuJoCo Warp's gjk), cutoff 0 or the capsule / sphere radii
267
+ __device__ void cv_gjk(float tol, int iters, CGeom& g1, CGeom& g2, f3 x1_0, f3 x2_0, float cutoff, bool disc,
268
+ GJKResult& r) {
269
+ f3 simplex[4], simplex1[4], simplex2[4];
270
+ int si1[4] = {0, 0, 0, 0}, si2[4] = {0, 0, 0, 0};
271
+ for (int i = 0; i < 4; i++) simplex[i] = simplex1[i] = simplex2[i] = mk3(0.f, 0.f, 0.f);
272
+ int n = 0;
273
+ float l[4] = {1.f, 0.f, 0.f, 0.f};
274
+ float epsilon = disc ? 0.f : 0.5f * tol * tol, min_norm = disc ? CV_MINVAL : tol;
275
+ f3 x_k = x1_0 - x2_0;
276
+ float xnorm = sqrtf(dt3(x_k, x_k)), xnorm_prev = 0.f;
277
+ for (int it = 0; it < iters; it++) {
278
+ if (xnorm < min_norm || fabsf(xnorm_prev - xnorm) < CV_MINVAL) break;
279
+ f3 dir_neg = x_k / xnorm; // (_gjk_support: direction tuning for discrete geoms)
280
+ if (disc && xnorm < 1e-4f) {
281
+ if (n == 2) {
282
+ f3 edge = simplex[1] - simplex[0];
283
+ float e2 = dt3(edge, edge);
284
+ if (e2 > CV_MINVAL2) {
285
+ float proj = dt3(dir_neg, edge) / e2;
286
+ dir_neg = dir_neg - proj * edge;
287
+ float dn = nm3(dir_neg);
288
+ if (dn > CV_MINVAL) dir_neg = dir_neg / dn;
289
+ }
290
+ } else if (n == 3) {
291
+ f3 e1 = simplex[1] - simplex[0], e2 = simplex[2] - simplex[0], nrm = cr3(e1, e2);
292
+ float nn = nm3(nrm);
293
+ if (nn > CV_MINVAL) dir_neg = cvsign(dt3(dir_neg, nrm)) * nrm / nn;
294
+ }
295
+ }
296
+ SupportPoint sp1 = cv_support(g1, -dir_neg), sp2 = cv_support(g2, dir_neg);
297
+ simplex1[n] = sp1.point; g1.index = sp1.cached; si1[n] = sp1.vidx;
298
+ simplex2[n] = sp2.point; g2.index = sp2.cached; si2[n] = sp2.vidx;
299
+ simplex[n] = simplex1[n] - simplex2[n];
300
+ if (dt3(x_k, x_k - simplex[n]) < epsilon) break;
301
+ float lower = dt3(x_k, simplex[n]);
302
+ if (cutoff == 0.f) {
303
+ if (lower > 0.f) { r.separated = true; r.dim = 0; r.dist = CV_FLOAT_MAX; r.index1 = g1.index; r.index2 = g2.index; return; }
304
+ } else if (cutoff < CV_FLOAT_MAX) {
305
+ if (lower > 0.f && lower >= cutoff * xnorm) {
306
+ r.separated = true; r.dim = 0; r.dist = CV_FLOAT_MAX; r.index1 = g1.index; r.index2 = g2.index; return;
307
+ }
308
+ }
309
+ subdistance(n + 1, simplex, l);
310
+ n = 0;
311
+ for (int i = 0; i < 4; i++) {
312
+ if (l[i] == 0.f) continue;
313
+ simplex[n] = simplex[i]; simplex1[n] = simplex1[i]; simplex2[n] = simplex2[i];
314
+ si1[n] = si1[i]; si2[n] = si2[i]; l[n] = l[i];
315
+ n++;
316
+ }
317
+ if (n < 1) break;
318
+ x_k = lin_combine(n, l, simplex);
319
+ xnorm_prev = xnorm;
320
+ xnorm = sqrtf(dt3(x_k, x_k));
321
+ if (n == 4) break;
322
+ }
323
+ r.separated = false;
324
+ r.x1 = n == 0 ? x1_0 : lin_combine(n, l, simplex1);
325
+ r.x2 = n == 0 ? x2_0 : lin_combine(n, l, simplex2);
326
+ if (xnorm > 0.f) {
327
+ f3 dir = x_k / xnorm;
328
+ SupportPoint sp1 = cv_support(g1, -dir), sp2 = cv_support(g2, dir);
329
+ r.separated = dt3(x_k, sp1.point - sp2.point) > 0.f;
330
+ }
331
+ r.dist = (n == 4 && !r.separated) ? 0.f : xnorm;
332
+ r.dim = n;
333
+ for (int i = 0; i < 4; i++) {
334
+ r.simplex[i] = simplex[i]; r.simplex1[i] = simplex1[i]; r.simplex2[i] = simplex2[i];
335
+ r.sidx1[i] = si1[i]; r.sidx2[i] = si2[i];
336
+ }
337
+ r.index1 = g1.index;
338
+ r.index2 = g2.index;
339
+ }
340
+
341
+ // ------------------------------------------------------------------------------------------------ EPA polytope
342
+ struct Polytope {
343
+ f3 vert[EPA_NV];
344
+ int vidx[EPA_NV];
345
+ int nvert;
346
+ f3 center;
347
+ unsigned face[EPA_NF];
348
+ f3 face_pr[EPA_NF];
349
+ float face_norm2[EPA_NF];
350
+ int nface;
351
+ int horizon[EPA_NH];
352
+ int nhorizon;
353
+ int status;
354
+ };
355
+ __device__ __forceinline__ void face_verts(unsigned f, int* v) { v[0] = f & 0x3FF; v[1] = (f >> 10) & 0x3FF; v[2] = (f >> 20) & 0x3FF; }
356
+ __device__ __forceinline__ bool face_deleted(unsigned f) { return f & FACE_DELETED; }
357
+ __device__ __forceinline__ bool face_invalid(unsigned f) { return f & (FACE_DELETED | FACE_INVALID); }
358
+
359
+ __device__ float attach_face(Polytope& pt, int idx, int v1, int v2, int v3) {
360
+ if (pt.nface == EPA_NF) return 0.f;
361
+ f3 p1 = pt.vert[2 * v1] - pt.vert[2 * v1 + 1], p2 = pt.vert[2 * v2] - pt.vert[2 * v2 + 1],
362
+ p3 = pt.vert[2 * v3] - pt.vert[2 * v3 + 1], r;
363
+ if (proj_origin_plane(p3, p2, p1, &r)) return 0.f;
364
+ if (dt3(r, p1 - pt.center) < 0.f) r = -r;
365
+ pt.face[idx] = (unsigned)(v1 + (v2 << 10) + (v3 << 20));
366
+ pt.face_pr[idx] = r;
367
+ pt.face_norm2[idx] = dt3(r, r);
368
+ return pt.face_norm2[idx];
369
+ }
370
+ __device__ void epa_support(Polytope& pt, int idx, CGeom& g1, CGeom& g2, f3 dir, int* i1, int* i2) {
371
+ SupportPoint sp = cv_support(g1, dir);
372
+ pt.vert[2 * idx] = sp.point; pt.vidx[2 * idx] = sp.vidx; *i1 = sp.cached;
373
+ sp = cv_support(g2, -dir);
374
+ pt.vert[2 * idx + 1] = sp.point; pt.vidx[2 * idx + 1] = sp.vidx; *i2 = sp.cached;
375
+ }
376
+ __device__ void replace_simplex3(const Polytope& pt, int v1, int v2, int v3, GJKResult& r) {
377
+ const int v[3] = {v1, v2, v3};
378
+ for (int i = 0; i < 3; i++) {
379
+ r.simplex1[i] = pt.vert[2 * v[i]];
380
+ r.simplex2[i] = pt.vert[2 * v[i] + 1];
381
+ r.simplex[i] = r.simplex1[i] - r.simplex2[i];
382
+ r.sidx1[i] = pt.vidx[2 * v[i]];
383
+ r.sidx2[i] = pt.vidx[2 * v[i] + 1];
384
+ }
385
+ }
386
+ __device__ void rotmat120(f3 axis, float* R) {
387
+ float n = nm3(axis), u1 = axis.x / n, u2 = axis.y / n, u3 = axis.z / n;
388
+ const float s = 0.86602540378f, c = -0.5f;
389
+ R[0] = c + u1 * u1 * (1.f - c); R[1] = u1 * u2 * (1.f - c) - u3 * s; R[2] = u1 * u3 * (1.f - c) + u2 * s;
390
+ R[3] = u2 * u1 * (1.f - c) + u3 * s; R[4] = c + u2 * u2 * (1.f - c); R[5] = u2 * u3 * (1.f - c) - u1 * s;
391
+ R[6] = u1 * u3 * (1.f - c) - u2 * s; R[7] = u2 * u3 * (1.f - c) + u1 * s; R[8] = c + u3 * u3 * (1.f - c);
392
+ }
393
+ __device__ int ray_triangle(f3 v1, f3 v2, f3 v3, f3 v4, f3 v5) {
394
+ float vol1 = det3f(v3 - v1, v4 - v1, v2 - v1), vol2 = det3f(v4 - v1, v5 - v1, v2 - v1), vol3 = det3f(v5 - v1, v3 - v1, v2 - v1);
395
+ if (vol1 >= 0.f && vol2 >= 0.f && vol3 >= 0.f) return 1;
396
+ if (vol1 <= 0.f && vol2 <= 0.f && vol3 <= 0.f) return -1;
397
+ return 0;
398
+ }
399
+ __device__ f3 tri_affine(f3 v1, f3 v2, f3 v3, f3 p) {
400
+ float M_14 = v2.y * v3.z - v2.z * v3.y - v1.y * v3.z + v1.z * v3.y + v1.y * v2.z - v1.z * v2.y;
401
+ float M_24 = v2.x * v3.z - v2.z * v3.x - v1.x * v3.z + v1.z * v3.x + v1.x * v2.z - v1.z * v2.x;
402
+ float M_34 = v2.x * v3.y - v2.y * v3.x - v1.x * v3.y + v1.y * v3.x + v1.x * v2.y - v1.y * v2.x;
403
+ float M_max;
404
+ int x, y;
405
+ float mu1 = fabsf(M_14), mu2 = fabsf(M_24), mu3 = fabsf(M_34);
406
+ if (mu1 >= mu2 && mu1 >= mu3) { M_max = M_14; x = 1; y = 2; }
407
+ else if (mu2 >= mu3) { M_max = M_24; x = 0; y = 2; }
408
+ else { M_max = M_34; x = 0; y = 1; }
409
+ float px = cget(p, x), py = cget(p, y), ax = cget(v1, x), ay = cget(v1, y), bx = cget(v2, x), by = cget(v2, y),
410
+ cx = cget(v3, x), cy = cget(v3, y);
411
+ float C31 = px * by + py * cx + bx * cy - px * cy - py * bx - cx * by;
412
+ float C32 = px * cy + py * ax + cx * ay - px * ay - py * cx - ax * cy;
413
+ float C33 = px * ay + py * bx + ax * by - px * by - py * ax - bx * ay;
414
+ return mk3(C31 / M_max, C32 / M_max, C33 / M_max);
415
+ }
416
+ __device__ bool tri_point_intersect(f3 v1, f3 v2, f3 v3, f3 p) {
417
+ f3 c = tri_affine(v1, v2, v3, p);
418
+ if (c.x < 0.f || c.y < 0.f || c.z < 0.f) return false;
419
+ f3 pr = mk3(v1.x * c.x + v2.x * c.y + v3.x * c.z, v1.y * c.x + v2.y * c.y + v3.y * c.z, v1.z * c.x + v2.z * c.y + v3.z * c.z);
420
+ return nm3(pr - p) < CV_MINVAL;
421
+ }
422
+ __device__ bool same_side(f3 p0, f3 p1, f3 p2, f3 p3) {
423
+ f3 n = cr3(p1 - p0, p2 - p0);
424
+ float d1 = dt3(n, p3 - p0), d2 = dt3(n, -p0);
425
+ return (d1 > 0.f && d2 > 0.f) || (d1 < 0.f && d2 < 0.f);
426
+ }
427
+ __device__ bool test_tetra(f3 p0, f3 p1, f3 p2, f3 p3) {
428
+ return same_side(p0, p1, p2, p3) && same_side(p1, p2, p3, p0) && same_side(p2, p3, p0, p1) && same_side(p3, p0, p1, p2);
429
+ }
430
+ __device__ int add_edge(Polytope& pt, int e1, int e2) {
431
+ int n = pt.nhorizon;
432
+ if (n < 0) return -1;
433
+ int edge = (min(e1, e2) << 10) | max(e1, e2);
434
+ for (int i = 0; i < n; i++)
435
+ if (edge == pt.horizon[i]) { pt.horizon[i] = pt.horizon[n - 1]; return n - 1; }
436
+ if (n == EPA_NH) return -1;
437
+ pt.horizon[n] = edge;
438
+ return n + 1;
439
+ }
440
+
441
+ __device__ void polytope2(Polytope& pt, GJKResult& r, CGeom& g1, CGeom& g2) {
442
+ f3 diff = r.simplex[1] - r.simplex[0];
443
+ pt.center = 0.5f * (r.simplex[0] + r.simplex[1]);
444
+ float value = CV_FLOAT_MAX;
445
+ int index = 0;
446
+ for (int i = 0; i < 3; i++)
447
+ if (fabsf(cget(diff, i)) < value) { value = fabsf(cget(diff, i)); index = i; }
448
+ f3 e = mk3(0.f, 0.f, 0.f);
449
+ cset(e, index, 1.f);
450
+ f3 d1 = cr3(e, diff);
451
+ float R[9];
452
+ rotmat120(diff, R);
453
+ f3 d2 = rmul(R, d1), d3 = rmul(R, d2);
454
+ pt.vert[0] = r.simplex1[0]; pt.vert[1] = r.simplex2[0]; pt.vert[2] = r.simplex1[1]; pt.vert[3] = r.simplex2[1];
455
+ pt.vidx[0] = r.sidx1[0]; pt.vidx[1] = r.sidx2[0]; pt.vidx[2] = r.sidx1[1]; pt.vidx[3] = r.sidx2[1];
456
+ int i1, i2;
457
+ epa_support(pt, 2, g1, g2, d1 / nm3(d1), &i1, &i2);
458
+ epa_support(pt, 3, g1, g2, d2 / nm3(d2), &i1, &i2);
459
+ epa_support(pt, 4, g1, g2, d3 / nm3(d3), &i1, &i2);
460
+ const int F[6][3] = {{0, 2, 3}, {0, 4, 2}, {0, 3, 4}, {1, 3, 2}, {1, 2, 4}, {1, 4, 3}};
461
+ for (int f = 0; f < 6; f++)
462
+ if (attach_face(pt, f, F[f][0], F[f][1], F[f][2]) < CV_MIN_DIST2) {
463
+ pt.status = -1;
464
+ replace_simplex3(pt, F[f][0], F[f][1], F[f][2], r);
465
+ return;
466
+ }
467
+ f3 v2 = pt.vert[4] - pt.vert[5], v3 = pt.vert[6] - pt.vert[7], v4 = pt.vert[8] - pt.vert[9];
468
+ if (!ray_triangle(r.simplex[0], r.simplex[1], v2, v3, v4)) { pt.status = 1; return; }
469
+ pt.nvert = 5; pt.nface = 6; pt.status = 0;
470
+ }
471
+
472
+ __device__ void polytope3(Polytope& pt, const GJKResult& r, CGeom& g1, CGeom& g2) {
473
+ pt.center = (r.simplex[0] + r.simplex[1] + r.simplex[2]) * (1.f / 3.f) ;
474
+ f3 n = cr3(r.simplex[1] - r.simplex[0], r.simplex[2] - r.simplex[0]);
475
+ float norm = nm3(n);
476
+ if (norm < CV_MINVAL) { pt.status = 2; return; }
477
+ n = n / norm;
478
+ for (int i = 0; i < 3; i++) {
479
+ pt.vert[2 * i] = r.simplex1[i]; pt.vert[2 * i + 1] = r.simplex2[i];
480
+ pt.vidx[2 * i] = r.sidx1[i]; pt.vidx[2 * i + 1] = r.sidx2[i];
481
+ }
482
+ int i1, i2;
483
+ epa_support(pt, 3, g1, g2, -n, &i1, &i2);
484
+ epa_support(pt, 4, g1, g2, n, &i1, &i2);
485
+ f3 v1 = r.simplex[0], v2 = r.simplex[1], v3 = r.simplex[2], v4 = pt.vert[6] - pt.vert[7], v5 = pt.vert[8] - pt.vert[9];
486
+ if (tri_point_intersect(v1, v2, v3, v4)) { pt.status = 3; return; }
487
+ if (tri_point_intersect(v1, v2, v3, v5)) { pt.status = 4; return; }
488
+ if (r.dist > 1e-5f && !test_tetra(v1, v2, v3, v4) && !test_tetra(v1, v2, v3, v5)) { pt.status = 5; return; }
489
+ const int F[6][3] = {{4, 0, 1}, {4, 2, 0}, {4, 1, 2}, {3, 1, 0}, {3, 0, 2}, {3, 2, 1}};
490
+ for (int f = 0; f < 6; f++)
491
+ if (attach_face(pt, f, F[f][0], F[f][1], F[f][2]) < CV_MIN_DIST3) { pt.status = 6 + f; return; }
492
+ pt.nvert = 5; pt.nface = 6; pt.status = 0;
493
+ }
494
+
495
+
496
+ __device__ void polytope4(Polytope& pt, GJKResult& r) {
497
+ pt.center = 0.25f * (r.simplex[0] + r.simplex[1] + r.simplex[2] + r.simplex[3]);
498
+ for (int i = 0; i < 4; i++) {
499
+ pt.vert[2 * i] = r.simplex1[i]; pt.vert[2 * i + 1] = r.simplex2[i];
500
+ pt.vidx[2 * i] = r.sidx1[i]; pt.vidx[2 * i + 1] = r.sidx2[i];
501
+ }
502
+ const int F[4][3] = {{0, 1, 2}, {0, 3, 1}, {0, 2, 3}, {3, 2, 1}};
503
+ float dist[4];
504
+ int idx = 0;
505
+ for (int f = 0; f < 4; f++) {
506
+ dist[f] = attach_face(pt, f, F[f][0], F[f][1], F[f][2]);
507
+ if (dist[f] < CV_MIN_DIST4) { pt.status = -1; replace_simplex3(pt, F[f][0], F[f][1], F[f][2], r); return; }
508
+ if (f == 1) idx = dist[0] < dist[1] ? 0 : 1;
509
+ else if (f > 1) idx = dist[f] < dist[idx] ? f : idx;
510
+ }
511
+ if (!test_tetra(r.simplex[0], r.simplex[1], r.simplex[2], r.simplex[3])) {
512
+ if (dist[idx] > CV_MINVAL) { pt.status = 12; return; }
513
+ pt.status = -1;
514
+ replace_simplex3(pt, F[idx][0], F[idx][1], F[idx][2], r);
515
+ return;
516
+ }
517
+ pt.nvert = 4; pt.nface = 4; pt.status = 0;
518
+ }
519
+
520
+ // EPA (MuJoCo Warp's _epa): the closest face idx (-1: none) and the witness points
521
+ __device__ int cv_epa(float tol, int iters, Polytope& pt, CGeom& g1, CGeom& g2, bool disc) {
522
+ float upper = CV_FLOAT_MAX, upper2 = CV_FLOAT_MAX;
523
+ int idx = -1, pidx = -1;
524
+ float epsilon = disc ? CV_MIN_EPATOL : tol;
525
+ int nvalid = pt.nface;
526
+ iters = min(iters, 1000);
527
+ for (int it = 0; it < iters; it++) {
528
+ pidx = idx;
529
+ idx = -1;
530
+ float lower2 = CV_FLOAT_MAX;
531
+ for (int i = 0; i < pt.nface; i++)
532
+ if (!face_invalid(pt.face[i]) && pt.face_norm2[i] < lower2) { idx = i; lower2 = pt.face_norm2[i]; }
533
+ if (lower2 > upper2 || idx < 0) { idx = pidx; break; }
534
+ if (lower2 <= 0.f) break;
535
+ float lower = sqrtf(lower2);
536
+ int wi = pt.nvert;
537
+ if (2 * wi + 1 >= EPA_NV) break; // (MuJoCo Warp's buffer holds iters + 5 vertices: not reached)
538
+ f3 face_pr = pt.face_pr[idx];
539
+ int i1, i2;
540
+ epa_support(pt, wi, g1, g2, face_pr / lower, &i1, &i2);
541
+ f3 w = pt.vert[2 * wi] - pt.vert[2 * wi + 1];
542
+ g1.index = i1; g2.index = i2;
543
+ pt.nvert++;
544
+ float upper_k = dt3(face_pr, w) / lower;
545
+ if (upper_k < upper) { upper = upper_k; upper2 = upper * upper; }
546
+ if (upper - lower < epsilon) break;
547
+ if (disc) {
548
+ bool rep = false;
549
+ for (int i = 0; i < pt.nvert - 1; i++)
550
+ if (pt.vidx[2 * i] == pt.vidx[2 * wi] && pt.vidx[2 * i + 1] == pt.vidx[2 * wi + 1]) { rep = true; break; }
551
+ if (rep) break;
552
+ }
553
+ nvalid--;
554
+ pt.face[idx] |= FACE_DELETED;
555
+ int fv[3];
556
+ face_verts(pt.face[idx], fv);
557
+ pt.nhorizon = add_edge(pt, fv[0], fv[1]);
558
+ pt.nhorizon = add_edge(pt, fv[1], fv[2]);
559
+ pt.nhorizon = add_edge(pt, fv[2], fv[0]);
560
+ if (pt.nhorizon == -1) { idx = -1; break; }
561
+ for (int i = 0; i < pt.nface; i++) {
562
+ if (face_deleted(pt.face[i])) continue;
563
+ if (dt3(pt.face_pr[i], w) - pt.face_norm2[i] > 1e-10f) {
564
+ if (!face_invalid(pt.face[i])) nvalid--;
565
+ pt.face[i] |= FACE_DELETED;
566
+ face_verts(pt.face[i], fv);
567
+ pt.nhorizon = add_edge(pt, fv[0], fv[1]);
568
+ pt.nhorizon = add_edge(pt, fv[1], fv[2]);
569
+ pt.nhorizon = add_edge(pt, fv[2], fv[0]);
570
+ if (pt.nhorizon == -1) { idx = -1; break; }
571
+ }
572
+ }
573
+ for (int i = 0; i < pt.nhorizon && idx != -1; i++) {
574
+ int e0 = pt.horizon[i] & 0x3FF, e1 = (pt.horizon[i] >> 10) & 0x3FF;
575
+ float d2 = attach_face(pt, pt.nface, wi, e0, e1);
576
+ if (d2 == 0.f) { idx = -1; break; }
577
+ pt.nface++;
578
+ if (d2 >= lower2 && d2 <= upper2) nvalid++;
579
+ else pt.face[pt.nface - 1] |= FACE_INVALID;
580
+ }
581
+ if (nvalid == 0 || idx == -1) break;
582
+ pt.nhorizon = 0;
583
+ }
584
+ return idx;
585
+ }
586
+ // the witness points of face idx (MuJoCo Warp's _epa_witness without the height field case); returns the distance
587
+ __device__ float epa_witness(const Polytope& pt, int idx, f3* x1, f3* x2) {
588
+ int fv[3];
589
+ face_verts(pt.face[idx], fv);
590
+ f3 v1 = pt.vert[2 * fv[0]] - pt.vert[2 * fv[0] + 1], v2 = pt.vert[2 * fv[1]] - pt.vert[2 * fv[1] + 1],
591
+ v3 = pt.vert[2 * fv[2]] - pt.vert[2 * fv[2] + 1];
592
+ f3 c = tri_affine(v1, v2, v3, pt.face_pr[idx]);
593
+ v1 = pt.vert[2 * fv[0] + 1]; v2 = pt.vert[2 * fv[1] + 1]; v3 = pt.vert[2 * fv[2] + 1];
594
+ *x2 = mk3(v1.x * c.x + v2.x * c.y + v3.x * c.z, v1.y * c.x + v2.y * c.y + v3.y * c.z, v1.z * c.x + v2.z * c.y + v3.z * c.z);
595
+ v1 = pt.vert[2 * fv[0]]; v2 = pt.vert[2 * fv[1]]; v3 = pt.vert[2 * fv[2]];
596
+ *x1 = mk3(v1.x * c.x + v2.x * c.y + v3.x * c.z, v1.y * c.x + v2.y * c.y + v3.y * c.z, v1.z * c.x + v2.z * c.y + v3.z * c.z);
597
+ return -sqrtf(pt.face_norm2[idx]);
598
+ }
599
+
600
+ // ------------------------------------------------------------------------------------- multicontact (polygon clip)
601
+ struct MultiBuf { // MuJoCo Warp's per-contact multiccd buffers (and the clipped points' provenance, for the VJP)
602
+ f3 polygon[2 * NPOLYMAX], clipped[2 * NPOLYMAX], pnormal[NPOLYMAX];
603
+ float pdist[NPOLYMAX];
604
+ int idx1[NMESHDEG], idx2[NMESHDEG];
605
+ f3 n1[NMESHDEG], n2[NMESHDEG], endvert[NMESHDEG], face1[NPOLYMAX], face2[NPOLYMAX];
606
+ // provenance: each polygon vertex lies on two lines (tags: 0..7 the subject polygon's edge k, 8 + e the clipping
607
+ // face's side plane e, 16 + i the subject segment's end i, 24 the subject segment's line), pin / cin: the line of
608
+ // the polygon edge that leads into it
609
+ unsigned char ptag[2 * NPOLYMAX][2], ctag[2 * NPOLYMAX][2], pin[2 * NPOLYMAX], cin[2 * NPOLYMAX];
610
+ unsigned char otag[4][2]; // the output points' tags
611
+ int mcase, mi, mj; // multicontact's case (0 none, 1 face-face, 2 an edge of geom 2, 3 an edge of geom 1), i, j
612
+ };
613
+ __device__ int feature_dim(const int* fv, const Polytope& pt, int off, int* fi, f3* fx) {
614
+ int v1i = pt.vidx[2 * fv[0] + off], v2i = pt.vidx[2 * fv[1] + off], v3i = pt.vidx[2 * fv[2] + off];
615
+ fi[0] = v1i; fi[1] = v2i; fi[2] = v3i;
616
+ fx[0] = pt.vert[2 * fv[0] + off]; fx[1] = pt.vert[2 * fv[1] + off]; fx[2] = pt.vert[2 * fv[2] + off];
617
+ if (v1i != v2i) return (v3i == v1i || v3i == v2i) ? 2 : 3;
618
+ fi[1] = v3i;
619
+ fx[1] = pt.vert[2 * fv[2] + off];
620
+ return v1i != v3i ? 2 : 1;
621
+ }
622
+ __device__ int aligned_faces(const f3* a, int la, const f3* b, int lb, int* res) {
623
+ for (int i = 0; i < la; i++)
624
+ for (int j = 0; j < lb; j++)
625
+ if (dt3(a[i], b[j]) < -CV_FACE_TOL) { res[0] = i; res[1] = j; return 1; }
626
+ return 0;
627
+ }
628
+ __device__ int aligned_face_edge(const f3* edge, int nedge, const f3* face, int nface, int* res) {
629
+ for (int i = 0; i < nface; i++)
630
+ for (int j = 0; j < nedge; j++)
631
+ if (fabsf(dt3(edge[j], face[i])) < CV_EDGE_TOL) { res[0] = j; res[1] = i; return 1; }
632
+ return 0;
633
+ }
634
+ __device__ __forceinline__ f3 box_fn(int i) { // mat63 face normals: +x, -x, +y, -y, +z, -z
635
+ 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));
636
+ }
637
+ __device__ int box_normals2(const float* R, f3 n, f3* nout, int* iout) {
638
+ f3 ln = nz3(rtmul(R, n));
639
+ for (int i = 0; i < 6; i++)
640
+ if (dt3(ln, box_fn(i)) > CV_FACE_TOL) { nout[0] = rmul(R, box_fn(i)); iout[0] = i; return 1; }
641
+ return 0;
642
+ }
643
+ __device__ int box_normals(int dim, const int* fi, const float* R, f3 dir, f3* nout, int* iout) {
644
+ int v1 = fi[0], v2 = fi[1], v3 = fi[2];
645
+ if (dim == 3) {
646
+ int c = 0;
647
+ float x = float((v1 & 1) && (v2 & 1) && (v3 & 1)) - float(!(v1 & 1) && !(v2 & 1) && !(v3 & 1));
648
+ float y = float((v1 & 2) && (v2 & 2) && (v3 & 2)) - float(!(v1 & 2) && !(v2 & 2) && !(v3 & 2));
649
+ float z = float((v1 & 4) && (v2 & 4) && (v3 & 4)) - float(!(v1 & 4) && !(v2 & 4) && !(v3 & 4));
650
+ nout[0] = rmul(R, mk3(x, y, z));
651
+ float sgn = x + y + z;
652
+ if (x != 0.f) iout[c++] = 0;
653
+ if (y != 0.f) iout[c++] = 2;
654
+ if (z != 0.f) iout[c++] = 4;
655
+ if (sgn == -1.f) iout[0] = iout[0] + 1;
656
+ if (c == 1) return 1;
657
+ return box_normals2(R, dir, nout, iout);
658
+ }
659
+ if (dim == 2) {
660
+ int c = 0;
661
+ float x = float((v1 & 1) && (v2 & 1)) - float(!(v1 & 1) && !(v2 & 1));
662
+ float y = float((v1 & 2) && (v2 & 2)) - float(!(v1 & 2) && !(v2 & 2));
663
+ float z = float((v1 & 4) && (v2 & 4)) - float(!(v1 & 4) && !(v2 & 4));
664
+ if (x != 0.f) { nout[c] = rmul(R, mk3(x, 0.f, 0.f)); iout[c] = x > 0.f ? 0 : 1; c++; }
665
+ if (y != 0.f) { nout[c] = rmul(R, mk3(0.f, y, 0.f)); iout[c] = y > 0.f ? 2 : 3; c++; }
666
+ if (z != 0.f) { nout[c] = rmul(R, mk3(0.f, 0.f, z)); iout[c] = z > 0.f ? 4 : 5; c++; }
667
+ if (c == 1 || c == 2) return c;
668
+ return box_normals2(R, dir, nout, iout);
669
+ }
670
+ if (dim == 1) {
671
+ float x = (v1 & 1) ? 1.f : -1.f, y = (v1 & 2) ? 1.f : -1.f, z = (v1 & 4) ? 1.f : -1.f;
672
+ 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));
673
+ iout[0] = x > 0.f ? 0 : 1; iout[1] = y > 0.f ? 2 : 3; iout[2] = z > 0.f ? 4 : 5;
674
+ return 3;
675
+ }
676
+ return 0;
677
+ }
678
+ __device__ int box_edge_normals(int dim, const CGeom& g, f3 v1, f3 v2, int v1i, f3* nout, f3* eout) {
679
+ if (dim == 2) { eout[0] = v2; nout[0] = nz3(v2 - v1); return 1; }
680
+ if (dim == 1) {
681
+ 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;
682
+ eout[0] = rmul(g.R, mk3(-x, y, z)) + g.pos; nout[0] = nz3(eout[0] - v1);
683
+ eout[1] = rmul(g.R, mk3(x, -y, z)) + g.pos; nout[1] = nz3(eout[1] - v1);
684
+ eout[2] = rmul(g.R, mk3(x, y, -z)) + g.pos; nout[2] = nz3(eout[2] - v1);
685
+ return 3;
686
+ }
687
+ return 0;
688
+ }
689
+ __device__ int box_face(const CGeom& g, int idx, f3* f) {
690
+ const float sx = g.size.x, sy = g.size.y, sz = g.size.z;
691
+ f3 c[4];
692
+ 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); }
693
+ 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); }
694
+ 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); }
695
+ 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); }
696
+ 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); }
697
+ 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); }
698
+ else return 0;
699
+ for (int i = 0; i < 4; i++) f[i] = rmul(g.R, c[i]) + g.pos;
700
+ return 4;
701
+ }
702
+ __device__ __forceinline__ float area4(f3 a, f3 b, f3 c, f3 d) { return 0.5f * nm3(cr3(a - c, b - d)); }
703
+ __device__ void polygon_quad(const f3* p, int np, int* q) { // MuJoCo Warp's _polygon_quad
704
+ int b = 1, c = 2, d = 3;
705
+ q[0] = 0; q[1] = b; q[2] = c; q[3] = d;
706
+ float m = area4(p[0], p[b], p[c], p[d]);
707
+ for (int a = 0; a < np; a++) {
708
+ while (true) {
709
+ float m_next = area4(p[a], p[b], p[c], p[(d + 1) % np]);
710
+ if (m_next <= m) break;
711
+ m = m_next; d = (d + 1) % np; q[0] = a; q[1] = b; q[2] = c; q[3] = d;
712
+ while (true) {
713
+ m_next = area4(p[a], p[b], p[(c + 1) % np], p[d]);
714
+ if (m_next <= m) break;
715
+ m = m_next; c = (c + 1) % np; q[0] = a; q[1] = b; q[2] = c; q[3] = d;
716
+ }
717
+ while (true) {
718
+ m_next = area4(p[a], p[(b + 1) % np], p[c], p[d]);
719
+ if (m_next <= m) break;
720
+ m = m_next; b = (b + 1) % np; q[0] = a; q[1] = b; q[2] = c; q[3] = d;
721
+ }
722
+ }
723
+ if (b == a) {
724
+ b = (b + 1) % np;
725
+ if (c == b) {
726
+ c = (c + 1) % np;
727
+ if (d == c) d = (d + 1) % np;
728
+ }
729
+ }
730
+ }
731
+ }
732
+ __device__ __forceinline__ void witness_on_face(f3 v, f3 p, f3 n, f3 dir, f3* w1, f3* w2, float* d) {
733
+ float dist = dt3(v - p, n);
734
+ *w1 = v - fabsf(dist) * dir;
735
+ *w2 = v;
736
+ *d = dist;
737
+ }
738
+ // clip polygon face2 against face1 (MuJoCo Warp's _polygon_clip): the contacts (witnesses, distances), count
739
+ __device__ int polygon_clip(MultiBuf& mb, const f3* face1, int nface1, const f3* face2, int nface2, f3 n, f3 dir,
740
+ f3* w1o, f3* w2o, float* dists) {
741
+ if (nface1 < 3) return 0;
742
+ for (int i = 0; i < nface1; i++) {
743
+ f3 a = face1[i], b = face1[(i + 1) % nface1];
744
+ f3 v3 = a + n, res = cr3(b - a, v3 - a);
745
+ mb.pdist[i] = dt3(res, a);
746
+ mb.pnormal[i] = res;
747
+ }
748
+ f3* poly = mb.polygon;
749
+ f3* clip = mb.clipped;
750
+ unsigned char (*ptag)[2] = mb.ptag;
751
+ unsigned char (*ctag)[2] = mb.ctag;
752
+ unsigned char* pin = mb.pin;
753
+ unsigned char* cin = mb.cin;
754
+ int npoly = nface2, nclip = 0;
755
+ for (int i = 0; i < nface2; i++) {
756
+ poly[i] = face2[i];
757
+ if (nface2 == 2) { ptag[i][0] = 24; ptag[i][1] = (unsigned char)(16 + i); pin[i] = 24; }
758
+ else { ptag[i][0] = (unsigned char)((i + nface2 - 1) % nface2); ptag[i][1] = (unsigned char)i;
759
+ pin[i] = (unsigned char)((i + nface2 - 1) % nface2); }
760
+ }
761
+ for (int e = 0; e < nface1; e++) {
762
+ for (int i = 0; i < npoly; i++) {
763
+ const int iq = (i + 1) % npoly;
764
+ f3 P = poly[i], Q = poly[iq];
765
+ const unsigned char li = pin[iq]; // the line of edge P Q
766
+ bool in1 = dt3(P - face1[e], mb.pnormal[e]) > -1e-10f, in2 = dt3(Q - face1[e], mb.pnormal[e]) > -1e-10f;
767
+ if (!in1 && !in2) continue;
768
+ if (in1 && in2) {
769
+ if (nclip < 2 * NPOLYMAX) { clip[nclip] = Q; ctag[nclip][0] = ptag[iq][0]; ctag[nclip][1] = ptag[iq][1];
770
+ cin[nclip] = li; nclip++; }
771
+ continue;
772
+ }
773
+ 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;
774
+ if (t > -CV_INTERSECT_TOL && t < 1.f + CV_INTERSECT_TOL) {
775
+ t = fminf(fmaxf(t, 0.f), 1.f);
776
+ if (nclip < 2 * NPOLYMAX) { clip[nclip] = P + t * (Q - P); ctag[nclip][0] = li;
777
+ ctag[nclip][1] = (unsigned char)(8 + e); cin[nclip] = in1 ? li : (unsigned char)(8 + e);
778
+ nclip++; }
779
+ }
780
+ if (in2 && nclip < 2 * NPOLYMAX) { clip[nclip] = Q; ctag[nclip][0] = ptag[iq][0]; ctag[nclip][1] = ptag[iq][1];
781
+ cin[nclip] = li; nclip++; }
782
+ }
783
+ f3* tmp = poly; poly = clip; clip = tmp;
784
+ unsigned char (*tt)[2] = ptag; ptag = ctag; ctag = tt;
785
+ unsigned char* ti = pin; pin = cin; cin = ti;
786
+ npoly = nclip;
787
+ nclip = 0;
788
+ }
789
+ int m = npoly;
790
+ npoly = 0;
791
+ for (int i = 0; i < m; i++)
792
+ if (dt3(poly[i] - face1[0], n) <= 0.f) {
793
+ if (npoly != i) { poly[npoly] = poly[i]; ptag[npoly][0] = ptag[i][0]; ptag[npoly][1] = ptag[i][1]; }
794
+ npoly++;
795
+ }
796
+ if (npoly < 1) return 0;
797
+ if (nface2 == 2 && npoly > 2) {
798
+ int b1 = 0, b2 = 1;
799
+ float max_d = 0.f;
800
+ for (int i = 0; i < npoly; i++)
801
+ for (int j = i + 1; j < npoly; j++) {
802
+ f3 df = poly[j] - poly[i];
803
+ float d2 = dt3(df, df);
804
+ if (d2 > max_d) { max_d = d2; b1 = i; b2 = j; }
805
+ }
806
+ witness_on_face(poly[b1], face1[0], n, dir, &w1o[0], &w2o[0], &dists[0]);
807
+ witness_on_face(poly[b2], face1[0], n, dir, &w1o[1], &w2o[1], &dists[1]);
808
+ mb.otag[0][0] = ptag[b1][0]; mb.otag[0][1] = ptag[b1][1]; mb.otag[1][0] = ptag[b2][0]; mb.otag[1][1] = ptag[b2][1];
809
+ return 2;
810
+ }
811
+ if (npoly > 4) {
812
+ int q[4];
813
+ polygon_quad(poly, npoly, q);
814
+ for (int i = 0; i < 4; i++) {
815
+ witness_on_face(poly[q[i]], face1[0], n, dir, &w1o[i], &w2o[i], &dists[i]);
816
+ mb.otag[i][0] = ptag[q[i]][0]; mb.otag[i][1] = ptag[q[i]][1];
817
+ }
818
+ return 4;
819
+ }
820
+ for (int i = 0; i < npoly; i++) {
821
+ witness_on_face(poly[i], face1[0], n, dir, &w1o[i], &w2o[i], &dists[i]);
822
+ mb.otag[i][0] = ptag[i][0]; mb.otag[i][1] = ptag[i][1];
823
+ }
824
+ return npoly;
825
+ }
826
+
827
+ // MuJoCo Warp's multicontact: up to 4 contacts (witnesses w1, w2, distances) from EPA face fidx; returns the count
828
+ // (1: the EPA witnesses x1, x2 alone)
829
+ __device__ int multicontact(MultiBuf& mb, const Polytope& pt, int fidx, f3 x1, f3 x2, const CGeom& g1,
830
+ const CGeom& g2, f3* w1, f3* w2, float* dists) {
831
+ w1[0] = x1; w2[0] = x2;
832
+ mb.mcase = 0;
833
+ int fv[3], fi1[3], fi2[3];
834
+ f3 fx1[3], fx2[3];
835
+ face_verts(pt.face[fidx], fv);
836
+ int nface1 = feature_dim(fv, pt, 0, fi1, fx1), nface2 = feature_dim(fv, pt, 1, fi2, fx2);
837
+ f3 dir = x2 - x1, dir_neg = -dir;
838
+ int nn1 = 0, nn2 = 0;
839
+ nn1 = box_normals(nface1, fi1, g1.R, dir_neg, mb.n1, mb.idx1); // (boxes only in this module)
840
+ nn2 = box_normals(nface2, fi2, g2.R, dir, mb.n2, mb.idx2);
841
+ int edge1 = 0, edge2 = 0, res[2] = {0, 0};
842
+ int nres = aligned_faces(mb.n1, nn1, mb.n2, nn2, res);
843
+ if (!nres) {
844
+ if (nface1 < 3 && nface1 <= nface2) {
845
+ nn1 = box_edge_normals(nface1, g1, fx1[0], fx1[1], fi1[0], mb.n1, mb.endvert);
846
+ nres = aligned_face_edge(mb.n1, nn1, mb.n2, nn2, res);
847
+ if (!nres) return 1;
848
+ edge1 = 1;
849
+ } else if (nface2 < 3) {
850
+ nn2 = box_edge_normals(nface2, g2, fx2[0], fx2[1], fi2[0], mb.n2, mb.endvert);
851
+ nres = aligned_face_edge(mb.n2, nn2, mb.n1, nn1, res);
852
+ if (!nres) return 1;
853
+ edge2 = 1;
854
+ } else {
855
+ return 1;
856
+ }
857
+ }
858
+ int i = res[0], j = res[1], nf1, nf2;
859
+ mb.mcase = edge1 ? 3 : (edge2 ? 2 : 1); mb.mi = i; mb.mj = j;
860
+ if (edge1) { mb.face1[0] = pt.vert[2 * fv[0]]; mb.face1[1] = mb.endvert[i]; nf1 = 2; }
861
+ else {
862
+ int ind = edge2 ? mb.idx1[j] : mb.idx1[i];
863
+ nf1 = box_face(g1, ind, mb.face1);
864
+ }
865
+ if (edge2) { mb.face2[0] = pt.vert[2 * fv[0] + 1]; mb.face2[1] = mb.endvert[i]; nf2 = 2; }
866
+ else nf2 = box_face(g2, mb.idx2[j], mb.face2);
867
+ if (edge1) {
868
+ f3 c1[4], c2[4];
869
+ int n = polygon_clip(mb, mb.face2, nf2, mb.face1, nf1, mb.n2[j], -mb.n2[j], c1, c2, dists);
870
+ for (int k = 0; k < n; k++) { w1[k] = c2[k]; w2[k] = c1[k]; } // (flipped back)
871
+ return n;
872
+ }
873
+ if (edge2) return polygon_clip(mb, mb.face1, nf1, mb.face2, nf2, mb.n1[j], -mb.n1[j], w1, w2, dists);
874
+ return polygon_clip(mb, mb.face1, nf1, mb.face2, nf2, mb.n1[i], mb.n2[j], w1, w2, dists);
875
+ }
876
+
877
+
878
+ // ----------------------------------------------------------------------------------------- box-box (ccd_kernel)
879
+ // A pair's contacts before they enter a world's table (up to 4: MuJoCo Warp's multicontact)
880
+ #ifndef CSINK_DEFINED
881
+ #define CSINK_DEFINED
882
+ #define SINK_MAX 8
883
+ struct CSink {
884
+ int n, unsupported;
885
+ int slot[SINK_MAX];
886
+ float dist[SINK_MAX], pos[SINK_MAX][3], fr[SINK_MAX][9];
887
+ };
888
+ __device__ __forceinline__ void sink_put(CSink& o, int slot, float dist, f3 pc, const float* frame) {
889
+ if (o.n >= SINK_MAX) { o.unsupported |= 4; return; }
890
+ o.slot[o.n] = slot; o.dist[o.n] = dist;
891
+ o.pos[o.n][0] = pc.x; o.pos[o.n][1] = pc.y; o.pos[o.n][2] = pc.z;
892
+ for (int k = 0; k < 9; k++) o.fr[o.n][k] = frame[k];
893
+ o.n++;
894
+ }
895
+ #endif
896
+
897
+ __device__ __forceinline__ CGeom cgeom_box(const float* p, const float* R, const float* s) {
898
+ CGeom c;
899
+ c.pos = ld3(p);
900
+ for (int k = 0; k < 9; k++) c.R[k] = R[k];
901
+ c.size = ld3(s);
902
+ c.type = 3;
903
+ c.index = -1;
904
+ return c;
905
+ }
906
+
907
+ // How a contact depends on the boxes' poses (ccd_box_box's wit, for the adjoint's exact VJP): own 0 / 1 = geom 1 / 2;
908
+ // vectors in ccd_box_box's frame (geom 1's centre at the origin; c1, c2 the centres)
909
+ // kind 1 (a clipped point): v the intersection of the planes g[0..2] . (x - x_r) = 0, each of a box (own[r]);
910
+ // kind 2 (EPA, a vertex in a face): v a vertex of box own[0];
911
+ // both: dist = nd . (v - xd) (nd, xd of box od), pos = v + dist dir / 2, the normal nsgn dir (dir of box odir);
912
+ // kind 3 (EPA, edge-edge): x1 = a1 + s e1 on box 1, x2 = a2 + t e2 on box 2 closest, dist = -|x1 - x2|, the
913
+ // normal normalize(x1 - x2), pos their midpoint; kind 4 (other EPA features): x1 = a1, x2 = a2 as points of their
914
+ // boxes (approximate)
915
+ struct CcdWit {
916
+ int kind;
917
+ f3 v, g[3];
918
+ int own[3];
919
+ f3 nd, xd, dir;
920
+ int od, odir;
921
+ float nsgn;
922
+ f3 a1, e1, a2, e2, c1, c2;
923
+ };
924
+
925
+ // the plane of tag t (MultiBuf's provenance) for kind-1 points: its normal and box
926
+ __device__ __forceinline__ void tag_plane(int t, int sel, const f3* subj, int nsubj, f3 nsub, int osub, const f3* cf,
927
+ int ncf, f3 ncl, int ocl, const CGeom& gs, f3* g, int* own) {
928
+ if (t < 8) { *g = cr3(subj[(t + 1) % nsubj] - subj[t], nsub); *own = osub; return; }
929
+ if (t < 16) { const int e = t - 8; *g = cr3(cf[(e + 1) % ncf] - cf[e], ncl); *own = ocl; return; }
930
+ if (t < 24) { *g = subj[1] - subj[0]; *own = osub; return; }
931
+ // the segment's line: the subject box's two axes most perpendicular to it (sel 0 / 1)
932
+ f3 d = subj[1] - subj[0];
933
+ float c[3];
934
+ for (int k = 0; k < 3; k++) c[k] = fabsf(gs.R[k] * d.x + gs.R[3 + k] * d.y + gs.R[6 + k] * d.z);
935
+ int ax = (c[0] >= c[1] && c[0] >= c[2]) ? 0 : (c[1] >= c[2] ? 1 : 2);
936
+ const int k = (ax + 1 + sel) % 3;
937
+ *g = mk3(gs.R[k], gs.R[3 + k], gs.R[6 + k]);
938
+ *own = osub;
939
+ }
940
+
941
+ // box-box as MuJoCo Warp's ccd_kernel (native CCD: GJK, EPA with EPA_ITERATIONS, then multicontact, which MuJoCo Warp
942
+ // runs for every box-box pair; margin and gap 0): the contacts with dist < 0 into o, their slots the multicontact's
943
+ // points (0 .. 3), their frame from the first one's witnesses. wit (null: none): the dependence of contact `slot`
944
+ // (the replay of the adjoint; the same arithmetic, so the same contacts)
945
+ __device__ __noinline__ void ccd_box_box(const float* p1, const float* R1, const float* s1, const float* p2,
946
+ const float* R2, const float* s2, CSink& o, int slot = -1,
947
+ CcdWit* wit = nullptr) {
948
+ o.n = 0; o.unsupported = 0;
949
+ CGeom g1 = cgeom_box(p1, R1, s1), g2 = cgeom_box(p2, R2, s2);
950
+ const float tol = CCD_TOLERANCE;
951
+ f3 origin = g1.pos; // (translation invariance: geom 1 at the origin)
952
+ g1.pos = mk3(0.f, 0.f, 0.f);
953
+ g2.pos = g2.pos - origin;
954
+ GJKResult r;
955
+ cv_gjk(tol, GJK_ITERATIONS, g1, g2, g1.pos, g2.pos, 0.f, true, r);
956
+ g1.index = r.index1; g2.index = r.index2;
957
+ if (r.dist > tol || r.dim < 2 || r.separated) return; // (no penetration depth to recover)
958
+ Polytope pt;
959
+ pt.nface = 0; pt.nvert = 0; pt.nhorizon = 0; pt.status = 0;
960
+ if (r.dim == 2) { polytope2(pt, r, g1, g2); if (pt.status == -1) r.dim = 3; }
961
+ else if (r.dim == 4) { polytope4(pt, r); if (pt.status == -1) r.dim = 3; }
962
+ if (r.dim == 3) { pt.nface = 0; pt.nvert = 0; pt.nhorizon = 0; polytope3(pt, r, g1, g2); }
963
+ if (pt.status) return; // (origin on the boundary: dist = the GJK distance, not penetrating)
964
+ const int fidx = cv_epa(tol, EPA_ITERATIONS, pt, g1, g2, true);
965
+ if (fidx == -1) return;
966
+ f3 x1, x2;
967
+ const float dist = epa_witness(pt, fidx, &x1, &x2);
968
+ if (!(dist < 0.f)) return;
969
+ f3 w1[4], w2[4];
970
+ float dists[4] = {0.f, 0.f, 0.f, 0.f};
971
+ MultiBuf mb;
972
+ int nc = multicontact(mb, pt, fidx, x1, x2, g1, g2, w1, w2, dists);
973
+ const bool clipped = nc >= 1 && mb.mcase != 0;
974
+ if (nc < 1) { nc = 1; w1[0] = x1; w2[0] = x2; }
975
+ float nrm[3], fr[9];
976
+ f3 nv = nz3(w1[0] - w2[0]);
977
+ nrm[0] = nv.x; nrm[1] = nv.y; nrm[2] = nv.z;
978
+ make_frame(nrm, fr);
979
+ for (int i = 0; i < nc; i++) {
980
+ const float di = nc > 1 ? dists[i] : dist;
981
+ if (di < 0.f) sink_put(o, i, di, 0.5f * (w1[i] + w2[i]) + origin, fr);
982
+ }
983
+ if (!wit || slot < 0 || slot >= nc) return;
984
+ CcdWit& W = *wit;
985
+ W.c1 = g1.pos; W.c2 = g2.pos;
986
+ if (clipped) { // kind 1: the clipped point `slot`
987
+ const int cs = mb.mcase, i = mb.mi, j = mb.mj;
988
+ const f3* cf = cs == 3 ? mb.face2 : mb.face1; // the clipping face
989
+ const f3* sb = cs == 3 ? mb.face1 : mb.face2; // the subject polygon / segment
990
+ const int ocl = cs == 3 ? 1 : 0, osub = 1 - ocl, nsub = cs == 1 ? 4 : 2;
991
+ const f3 ncl = cs == 1 ? mb.n1[i] : (cs == 2 ? mb.n1[j] : mb.n2[j]);
992
+ const f3 nsb = cs == 1 ? mb.n2[j] : mk3(0.f, 0.f, 0.f);
993
+ const CGeom& gs = osub ? g2 : g1;
994
+ W.kind = 1;
995
+ W.v = cs == 3 ? w1[slot] : w2[slot];
996
+ const int t0 = mb.otag[slot][0], t1 = mb.otag[slot][1];
997
+ if (cs == 1) {
998
+ W.g[0] = nsb; W.own[0] = osub;
999
+ tag_plane(t0, 0, sb, nsub, nsb, osub, cf, 4, ncl, ocl, gs, &W.g[1], &W.own[1]);
1000
+ tag_plane(t1, 0, sb, nsub, nsb, osub, cf, 4, ncl, ocl, gs, &W.g[2], &W.own[2]);
1001
+ } else {
1002
+ tag_plane(24, 0, sb, nsub, nsb, osub, cf, 4, ncl, ocl, gs, &W.g[0], &W.own[0]);
1003
+ tag_plane(24, 1, sb, nsub, nsb, osub, cf, 4, ncl, ocl, gs, &W.g[1], &W.own[1]);
1004
+ tag_plane(t0 == 24 ? t1 : t0, 0, sb, nsub, nsb, osub, cf, 4, ncl, ocl, gs, &W.g[2], &W.own[2]);
1005
+ }
1006
+ W.nd = ncl; W.xd = cf[0]; W.od = ocl;
1007
+ W.dir = cs == 1 ? mb.n2[j] : -ncl;
1008
+ W.odir = cs == 1 ? 1 : ocl;
1009
+ W.nsgn = cs == 3 ? 1.f : -1.f;
1010
+ return;
1011
+ }
1012
+ int fv[3], fi1[3], fi2[3];
1013
+ f3 fx1[3], fx2[3];
1014
+ face_verts(pt.face[fidx], fv);
1015
+ const int d1 = feature_dim(fv, pt, 0, fi1, fx1), d2 = feature_dim(fv, pt, 1, fi2, fx2);
1016
+ f3 nn[3];
1017
+ int ii[3];
1018
+ if (d1 == 3 && d2 == 1 && box_normals(3, fi1, g1.R, x1 - x2, nn, ii) >= 1) { // a vertex of box 2 in a face of box 1
1019
+ W.kind = 2; W.v = fx2[0]; W.own[0] = 1; W.nd = nn[0]; W.xd = fx1[0]; W.od = 0;
1020
+ W.dir = -nn[0]; W.odir = 0; W.nsgn = -1.f;
1021
+ } else if (d1 == 1 && d2 == 3 && box_normals(3, fi2, g2.R, x2 - x1, nn, ii) >= 1) { // a vertex of box 1 in a face of 2
1022
+ W.kind = 2; W.v = fx1[0]; W.own[0] = 0; W.nd = nn[0]; W.xd = fx2[0]; W.od = 1;
1023
+ W.dir = -nn[0]; W.odir = 1; W.nsgn = 1.f;
1024
+ } else if (d1 == 2 && d2 == 2) { // edge-edge
1025
+ W.kind = 3; W.a1 = fx1[0]; W.e1 = fx1[1] - fx1[0]; W.a2 = fx2[0]; W.e2 = fx2[1] - fx2[0];
1026
+ } else {
1027
+ W.kind = 4; W.a1 = x1; W.a2 = x2;
1028
+ }
1029
+ }
1030
+ """
1031
+
1032
+
1033
+ ADJ_DEVICE = r"""
1034
+ // ccd_box_box's contact `slot` again (dist, pos, fr: the forward's bits) and, with cot = (dbar, pbar[3], frbar[9]), its
1035
+ // exact VJP onto the boxes' poses: gb = (xbar1, tbar1, xbar2, tbar2), forces on the centres and torques about them,
1036
+ // from the contact's dependence (CcdWit): a point of a box p moves as dp = dx + dw x (p - c), a vector of it as dw x u.
1037
+ // Kind 4 (EPA features other than vertex-face and edge-edge) takes its witnesses as points of their boxes (not exact).
1038
+ // Returns the CcdWit kind (0: the slot is not a contact)
1039
+ __device__ __noinline__ int ccd_box_box_vjp(const float* p1, const float* R1, const float* s1, const float* p2,
1040
+ const float* R2, const float* s2, int slot, const float* cot, float* gb,
1041
+ float* dist, float* pos, float* fr) {
1042
+ CSink o;
1043
+ CcdWit W;
1044
+ W.kind = 0;
1045
+ ccd_box_box(p1, R1, s1, p2, R2, s2, o, slot, &W);
1046
+ int c = -1;
1047
+ for (int i = 0; i < o.n; i++) if (o.slot[i] == slot) c = i;
1048
+ if (c < 0) return 0;
1049
+ *dist = o.dist[c];
1050
+ for (int k = 0; k < 3; k++) pos[k] = o.pos[c][k];
1051
+ for (int k = 0; k < 9; k++) fr[k] = o.fr[c][k];
1052
+ if (!cot) return W.kind;
1053
+ f3 F[2] = {mk3(0.f, 0.f, 0.f), mk3(0.f, 0.f, 0.f)}, T[2] = {mk3(0.f, 0.f, 0.f), mk3(0.f, 0.f, 0.f)};
1054
+ const f3 C[2] = {W.c1, W.c2};
1055
+ auto point = [&](int own, f3 x, f3 b) { F[own] = F[own] + b; T[own] = T[own] + cr3(x - C[own], b); };
1056
+ auto vec = [&](int own, f3 u, f3 b) { T[own] = T[own] + cr3(u, b); };
1057
+ float nb[3];
1058
+ make_frame_vjp(fr, cot + 4, nb);
1059
+ const f3 nbv = ld3(nb), pbv = ld3(cot + 1);
1060
+ const float dbv = cot[0], d = *dist;
1061
+ if (W.kind == 1 || W.kind == 2) {
1062
+ // pos = v + d dir / 2, the normal nsgn dir, dist = nd . (v - xd)
1063
+ f3 vbar = pbv, dirbar = (0.5f * d) * pbv + W.nsgn * nbv;
1064
+ const float dtot = dbv + 0.5f * dt3(W.dir, pbv);
1065
+ vbar = vbar + dtot * W.nd;
1066
+ vec(W.odir, W.dir, dirbar);
1067
+ vec(W.od, W.nd, dtot * (W.v - W.xd));
1068
+ point(W.od, W.xd, -dtot * W.nd);
1069
+ if (W.kind == 2) {
1070
+ point(W.own[0], W.v, vbar);
1071
+ } else { // A v = b with the rows g_r (planes of their boxes): lambda = A^-T vbar, plane r gets lambda_r g_r at v
1072
+ const f3 a = W.g[0], b = W.g[1], cc = W.g[2];
1073
+ const f3 bc = cr3(b, cc), ca = cr3(cc, a), ab = cr3(a, b);
1074
+ const float det = dt3(a, bc);
1075
+ if (fabsf(det) > 1e-12f * nm3(a) * nm3(b) * nm3(cc)) {
1076
+ // A^-1 = [bc ca ab] / det (columns), so A^-T vbar = (bc . vbar, ca . vbar, ab . vbar) / det
1077
+ const float l0 = dt3(bc, vbar) / det, l1 = dt3(ca, vbar) / det, l2 = dt3(ab, vbar) / det;
1078
+ point(W.own[0], W.v, l0 * a);
1079
+ point(W.own[1], W.v, l1 * b);
1080
+ point(W.own[2], W.v, l2 * cc);
1081
+ } else {
1082
+ point(W.own[0], W.v, vbar); // (degenerate planes: the point as one of its first plane's box)
1083
+ }
1084
+ }
1085
+ } else {
1086
+ f3 x1 = W.a1, x2 = W.a2, e1 = W.e1, e2 = W.e2;
1087
+ float s = 0.f, t = 0.f, A = 0.f, B = 0.f, Cc = 0.f;
1088
+ if (W.kind == 3) { // the lines' closest points
1089
+ const f3 r = W.a1 - W.a2;
1090
+ A = dt3(e1, e1); B = dt3(e1, e2); Cc = dt3(e2, e2);
1091
+ const float den = B * B - A * Cc;
1092
+ s = (Cc * dt3(e1, r) - B * dt3(e2, r)) / den;
1093
+ t = (B * dt3(e1, r) - A * dt3(e2, r)) / den;
1094
+ x1 = W.a1 + s * e1; x2 = W.a2 + t * e2;
1095
+ }
1096
+ const f3 w = x1 - x2;
1097
+ const float L = nm3(w);
1098
+ const f3 n = L > 0.f ? w / L : mk3(0.f, 0.f, 0.f);
1099
+ // dist = -|w|, the normal w / |w|, pos = (x1 + x2) / 2
1100
+ const f3 wbar = (-dbv) * n + (L > 0.f ? (nbv - dt3(n, nbv) * n) / L : mk3(0.f, 0.f, 0.f));
1101
+ const f3 x1b = wbar + 0.5f * pbv, x2b = 0.5f * pbv - wbar;
1102
+ if (W.kind == 3) {
1103
+ // e1 . w = e2 . w = 0 at (s, t): mu = -J^-T (x1b . e1, x2b . e2), J = [[A, -B], [B, -C]]
1104
+ const float c1 = dt3(x1b, e1), c2 = dt3(x2b, e2), dj = -A * Cc + B * B;
1105
+ // J^T = [[A, B], [-B, -C]]: J^T y = c
1106
+ const float y1 = (-Cc * c1 - B * c2) / dj, y2 = (B * c1 + A * c2) / dj;
1107
+ const float m1 = -y1, m2 = -y2;
1108
+ const f3 q = m1 * e1 + m2 * e2;
1109
+ point(0, W.a1, x1b + q);
1110
+ vec(0, e1, s * x1b + m1 * w + s * q);
1111
+ point(1, W.a2, x2b - q);
1112
+ vec(1, e2, t * x2b + m2 * w - t * q);
1113
+ } else {
1114
+ point(0, x1, x1b);
1115
+ point(1, x2, x2b);
1116
+ }
1117
+ }
1118
+ gb[0] = F[0].x; gb[1] = F[0].y; gb[2] = F[0].z; gb[3] = T[0].x; gb[4] = T[0].y; gb[5] = T[0].z;
1119
+ gb[6] = F[1].x; gb[7] = F[1].y; gb[8] = F[1].z; gb[9] = T[1].x; gb[10] = T[1].y; gb[11] = T[1].z;
1120
+ return W.kind;
1121
+ }
1122
+ """