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,439 @@
1
+ """Collision mid-phase of the forest engine: skip whole groups of contact pairs whose bounding spheres are apart."""
2
+ import json
3
+ import os
4
+
5
+ import mujoco
6
+ import numpy as np
7
+
8
+ CHAIN = 4
9
+ PAD_REL, PAD_ABS = 1e-4, 1e-4
10
+ TEXT = "nablaengine_midphase"
11
+
12
+
13
+ def mode():
14
+ v = os.environ.get("DK_MIDPHASE", "auto").strip().lower() or "auto"
15
+ if v not in ("auto", "0", "1", "2"):
16
+ raise ValueError(f"DK_MIDPHASE={v!r}: auto, 0, 1 or 2")
17
+ return v
18
+
19
+
20
+ def group_level(t):
21
+ """Whether a build gets the group level: $DK_MIDPHASE=2, or a model with explicit groups (its text element)."""
22
+ return mode() == "2" or (mode() != "1" and t["explicit"])
23
+
24
+
25
+ def _explicit(m):
26
+ k = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_TEXT, TEXT)
27
+ if k < 0:
28
+ return []
29
+ raw = bytes(m.text_data[m.text_adr[k]:m.text_adr[k] + m.text_size[k] - 1]).decode()
30
+ out = []
31
+ for names in json.loads(raw):
32
+ ids = [mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, n) for n in names]
33
+ bad = [n for n, i in zip(names, ids) if i <= 0]
34
+ if bad:
35
+ raise ValueError(f"{TEXT}: unknown or world bodies {bad}")
36
+ out.append(ids)
37
+ return out
38
+
39
+
40
+ def groups(m, colbodies):
41
+ """Body -> group root (an id among the bodies; world bodies -1) by the default rule, explicit groups first."""
42
+ nb = m.nbody
43
+ par = np.asarray(m.body_parentid)
44
+ has = np.zeros(nb, bool)
45
+ for b in sorted(colbodies, reverse=True):
46
+ has[b] = True
47
+ for b in range(nb - 1, 0, -1):
48
+ if has[b]:
49
+ has[par[b]] = True
50
+ kids = [[] for _ in range(nb)]
51
+ for b in range(1, nb):
52
+ if has[b]:
53
+ kids[par[b]].append(b)
54
+
55
+ def chain_len(b):
56
+ n = 0
57
+ while True:
58
+ n += 1
59
+ if len(kids[b]) > 1:
60
+ return None
61
+ if not kids[b]:
62
+ return n
63
+ b = kids[b][0]
64
+
65
+ root = np.full(nb, -1)
66
+ for gi, ids in enumerate(_explicit(m)):
67
+ for b in ids:
68
+ if root[b] >= 0:
69
+ raise ValueError(f"{TEXT}: body {m.body(b).name} in two groups")
70
+ root[b] = nb + gi
71
+ for b in range(1, nb):
72
+ if root[b] >= 0:
73
+ continue
74
+ p = par[b]
75
+ hand = p > 0 and len(kids[p]) >= 2 and all((c := chain_len(k)) is not None and c <= CHAIN for k in kids[p])
76
+ phand = p > 0 and root[p] == p and _is_hand(p, kids, chain_len)
77
+ if p == 0 or (len(kids[p]) >= 2 and not hand and not phand) or (root[p] >= nb):
78
+ root[b] = b
79
+ elif _is_hand(b, kids, chain_len):
80
+ root[b] = b
81
+ else:
82
+ root[b] = root[p]
83
+ return root
84
+
85
+
86
+ def _is_hand(b, kids, chain_len):
87
+ return len(kids[b]) >= 2 and all((c := chain_len(k)) is not None and c <= CHAIN for k in kids[b])
88
+
89
+
90
+ def tables(m):
91
+ """The mid-phase tables of model m (dict), or None for a model without pairs or beyond the table limits (255
92
+ nodes, 255 groups)."""
93
+ from nablaengine.forest_engine import step
94
+ if m.npair == 0:
95
+ return None
96
+ cg = step.collision_geoms(m)
97
+ table = {g: i for i, g in enumerate(cg)}
98
+ gb = np.asarray(m.geom_bodyid)
99
+ fix = [-1] * len(cg)
100
+ for i, f in enumerate(step.fixture_groups(m)):
101
+ for g in f["geoms"]:
102
+ fix[g] = i
103
+ plane = int(mujoco.mjtGeom.mjGEOM_PLANE)
104
+ node_of, nodes = {}, []
105
+ for i, g in enumerate(cg):
106
+ key = ("g", g) if gb[g] == 0 or m.geom_type[g] == plane else ("b", int(gb[g]))
107
+ if key not in node_of:
108
+ node_of[key] = len(nodes)
109
+ nodes.append((key, []))
110
+ nodes[node_of[key]][1].append(i)
111
+ if len(nodes) > 255:
112
+ return None
113
+ nword, off = [], []
114
+ for key, gi in nodes:
115
+ assert len(set(fix[i] for i in gi)) == 1, "mid-phase node: fixture and non-fixture geoms on one body"
116
+ gs = [cg[i] for i in gi]
117
+ ref = gs[0]
118
+ isp = m.geom_type[ref] == plane
119
+ if isp:
120
+ assert len(gs) == 1
121
+ nword.append(gi[0] | 1 << 8)
122
+ off.append((0.0, 0.0, 0.0, 0.0))
123
+ continue
124
+ pos = np.asarray([m.geom_pos[g] for g in gs], np.float64)
125
+ rb = np.asarray([m.geom_rbound[g] for g in gs], np.float64)
126
+ c = ((pos - rb[:, None]).min(0) + (pos + rb[:, None]).max(0)) / 2
127
+ r = float(max(np.linalg.norm(pos - c, axis=1) + rb))
128
+ R = np.zeros(9)
129
+ mujoco.mju_quat2Mat(R, np.asarray(m.geom_quat[ref], np.float64))
130
+ o = R.reshape(3, 3).T @ (c - m.geom_pos[ref])
131
+ nword.append(gi[0])
132
+ off.append((*o, r * (1 + PAD_REL) + PAD_ABS))
133
+ colbodies = sorted({int(gb[g]) for g in cg if gb[g] != 0})
134
+ root = groups(m, colbodies)
135
+ gkey, group_of_node = {}, []
136
+ for (key, gi) in nodes:
137
+ k = ("n", key) if key[0] == "g" else ("r", int(root[key[1]]))
138
+ if k not in gkey:
139
+ gkey[k] = len(gkey)
140
+ group_of_node.append(gkey[k])
141
+ ngrp = len(gkey)
142
+ if ngrp > 255:
143
+ return None
144
+ gnodes = [[n for n in range(len(nodes)) if group_of_node[n] == gi] for gi in range(ngrp)]
145
+ gfirst = np.cumsum([0] + [len(x) for x in gnodes]).tolist()
146
+ runs, rstart = [], []
147
+ for p in range(m.npair):
148
+ g1, g2 = step.pair_order(m, int(m.pair_geom1[p]), int(m.pair_geom2[p]))
149
+ k1 = ("g", g1) if gb[g1] == 0 or m.geom_type[g1] == plane else ("b", int(gb[g1]))
150
+ k2 = ("g", g2) if gb[g2] == 0 or m.geom_type[g2] == plane else ("b", int(gb[g2]))
151
+ r = (node_of[k1], node_of[k2])
152
+ if not runs or runs[-1] != r:
153
+ runs.append(r)
154
+ rstart.append(p)
155
+ rstart.append(m.npair)
156
+ gp_of, gp_runs = {}, []
157
+ for ri, (n1, n2) in enumerate(runs):
158
+ a, b = group_of_node[n1], group_of_node[n2]
159
+ pa, pb = bool(nword[gnodes[a][0]] >> 8), bool(nword[gnodes[b][0]] >> 8)
160
+ assert not pb, "mid-phase: a plane as the second geom of a pair"
161
+ k = (a, b) if pa or a <= b else (b, a)
162
+ if k not in gp_of:
163
+ gp_of[k] = len(gp_of)
164
+ gp_runs.append([])
165
+ gp_runs[gp_of[k]].append(ri)
166
+ gpw = []
167
+ for (a, b) in gp_of:
168
+ pa = nword[gnodes[a][0]] >> 8
169
+ gpw.append(a | b << 8 | (pa << 16) | ((nword[gnodes[a][0]] & 255) << 17 if pa else 0))
170
+ rword = [n1 | n2 << 8 | ((nword[n1] >> 8) << 16 | (nword[n1] & 255) << 17 if nword[n1] >> 8 else 0)
171
+ for n1, n2 in runs]
172
+ gpfirst = np.cumsum([0] + [len(x) for x in gp_runs]).tolist()
173
+ return dict(nodes=nword, off=off, gfirst=gfirst, gnodes=sum(gnodes, []), gp=gpw, runs=rword, gpfirst=gpfirst,
174
+ gpruns=sum(gp_runs, []), rstart=rstart, explicit=bool(_explicit(m)), names=[_name(m, k, cg) for k, _ in nodes],
175
+ group_of_node=group_of_node)
176
+
177
+
178
+ def _name(m, key, cg):
179
+ return m.geom(key[1]).name or f"geom{key[1]}" if key[0] == "g" else m.body(key[1]).name
180
+
181
+
182
+ def enabled(m):
183
+ """Whether model m's forest build gets the mid-phase ($DK_MIDPHASE, module docstring)."""
184
+ v = mode()
185
+ if v == "0" or m.npair == 0:
186
+ return False
187
+ if v == "auto" and mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_TEXT, TEXT) < 0:
188
+ return False
189
+ return tables(m) is not None
190
+
191
+
192
+ def describe(m):
193
+ """Human-readable groups of model m: [(group, [node names])] (the default rule plus explicit groups)."""
194
+ t = tables(m)
195
+ if t is None:
196
+ return []
197
+ out = {}
198
+ for n, g in enumerate(t["group_of_node"]):
199
+ out.setdefault(g, []).append(t["names"][n])
200
+ return sorted(out.items())
201
+
202
+
203
+ def _arr(name, kind, vals):
204
+ return f"__device__ const {kind} {name}[{max(len(vals), 1)}] = {{{', '.join(map(str, vals or [0]))}}};\n"
205
+
206
+
207
+ def header(m, t=None):
208
+ """The mid-phase's #defines and tables (replaces step._groups_header's text when enabled)."""
209
+ from nablaengine.forest_engine import step
210
+ t = t or tables(m)
211
+ f32 = lambda x: repr(float(np.float32(x))) + "f"
212
+ nrun = len(t["runs"])
213
+ groups = group_level(t)
214
+ return (f"#define BROAD_GROUPS 0\n#define MIDPHASE 1 // the collision mid-phase (forest_engine.midphase)\n"
215
+ f"#define MP_NNODE {len(t['nodes'])}\n#define MP_NGRP {len(t['gfirst']) - 1}\n#define MP_NGP {len(t['gp'])}\n"
216
+ f"#define MP_NRUN {nrun}\n#define MP_NRW {(nrun + 31) // 32}\n#define NCAND {min(step.NCAND, m.npair)}\n"
217
+ f"#define MP_GROUPS {int(groups)} // the group level (midphase.group_level)\n"
218
+ f"#define MP_SCRATCH {scratch(m, t, groups)} // (midphase.scratch)\n"
219
+ + _arr("c_mpnode", "unsigned char", [w & 255 for w in t["nodes"]])
220
+ + _arr("c_mpoff", "float", [f32(x) for o in t["off"] for x in o])
221
+ + _arr("c_mpgfirst", "unsigned short", t["gfirst"])
222
+ + _arr("c_mpgnode", "unsigned char", t["gnodes"])
223
+ + _arr("c_mpgp", "unsigned", t["gp"])
224
+ + _arr("c_mprun", "unsigned", t["runs"])
225
+ + (_arr("c_mpgpfirst", "unsigned short", t["gpfirst"]) + _arr("c_mpgpruns", "unsigned short", t["gpruns"])
226
+ if groups else "")
227
+ + _arr("c_mprstart", "unsigned short", t["rstart"]))
228
+
229
+
230
+ def scratch(m, t, groups):
231
+ """The collision's shared-memory scratch (the MP_SCRATCH member list, in place of step.py's cand[NPAIR]). Where it
232
+ fits, it lives inside the candidate array, so the structs do not grow (a larger SimP costs k_pre a world per SM:
233
+ V100 G1 + rigid hands 11 -> 10, k_pre +15%): the node spheres (and the group level's arrays) at its head, which the
234
+ final pass overwrites with candidates only after the runs were tested, and the kept-run list at its tail, starting
235
+ at NPAIR - NRUN: the candidates written before kept run j is read come from the kept runs before it, at most
236
+ NPAIR - NRUN + j pairs (every run has at least one pair), so they never reach it. Without the room (or with a
237
+ candidate capacity below NPAIR) the arrays are separate."""
238
+ from nablaengine.forest_engine import step
239
+ nn, ng, ngp, nrun = len(t["nodes"]), len(t["gfirst"]) - 1, len(t["gp"]), len(t["runs"])
240
+ ncand = min(step.NCAND, m.npair)
241
+ head = ["float mpn[MP_NNODE][4];"]
242
+ hbytes = 16 * nn
243
+ if groups:
244
+ head += ["float mpg[MP_NGRP][4];", "unsigned mprm[MP_NRW];", "unsigned short mpk[MP_NGP];"]
245
+ hbytes += 16 * ng + 4 * ((nrun + 31) // 32) + 2 * ngp
246
+ hbytes += hbytes % 4
247
+ gap = ncand - nrun - hbytes // 2
248
+ if ncand == m.npair and gap >= 1:
249
+ return ("union { unsigned short cand[NCAND]; struct { " + " ".join(head)
250
+ + f" unsigned short mp_gap[{gap}], mprl[MP_NRUN]; }}; }};")
251
+ return " ".join(head) + " unsigned short mprl[MP_NRUN], cand[NCAND];"
252
+
253
+ HELPER = r"""// the mid-phase's sphere test (forest_engine.midphase): spheres A, B (centre, radius) overlap, or with pg > 0 A is the
254
+ // plane of geom pg - 1 (A: a point on it) and B's sphere reaches below it; conservative: the radii are padded
255
+ template <class S>
256
+ __device__ __forceinline__ bool mp_overlap(const S& s, const float* A, const float* B, int pg) {
257
+ float d[3] = {B[0] - A[0], B[1] - A[1], B[2] - A[2]};
258
+ if (pg) {
259
+ float n[3];
260
+ zaxis_rn(s.gq[pg - 1], n);
261
+ return d[0] * n[0] + d[1] * n[1] + d[2] * n[2] <= B[3];
262
+ }
263
+ const float rb = A[3] + B[3];
264
+ return d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= rb * rb;
265
+ }
266
+
267
+ """
268
+
269
+ DEVICE = r"""#if MIDPHASE
270
+ // the mid-phase (forest_engine.midphase): the node spheres (fixed in a geom's frame); with the group level the
271
+ // group spheres (around their nodes' bounding box) and the group pairs' overlap bits; the runs whose group pair
272
+ // overlaps and whose node spheres overlap, in run order = pair order; and their pairs through the per-pair test
273
+ // into s.cand: the candidates of the plain loop below, in the same order
274
+ for (int k = lane; k < MP_NNODE; k += 32) {
275
+ const int g = c_mpnode[k];
276
+ const float* o = c_mpoff + 4 * k;
277
+ float t[3];
278
+ qrot_rn(s.gq[g], o, t);
279
+ for (int i = 0; i < 3; i++) s.mpn[k][i] = s.gx[g][i] + t[i];
280
+ s.mpn[k][3] = o[3];
281
+ }
282
+ int nkr = 0;
283
+ #if MP_GROUPS
284
+ for (int i = lane; i < MP_NRW; i += 32) s.mprm[i] = 0u;
285
+ __syncwarp();
286
+ for (int k = lane; k < MP_NGRP; k += 32) {
287
+ const int a = c_mpgfirst[k], b = c_mpgfirst[k + 1];
288
+ float c[3], r;
289
+ if (b - a == 1) {
290
+ const int n = c_mpgnode[a];
291
+ for (int i = 0; i < 3; i++) c[i] = s.mpn[n][i];
292
+ r = s.mpn[n][3];
293
+ } else {
294
+ float lo[3] = {INFINITY, INFINITY, INFINITY}, hi[3] = {-INFINITY, -INFINITY, -INFINITY};
295
+ for (int j = a; j < b; j++) {
296
+ const int n = c_mpgnode[j];
297
+ for (int i = 0; i < 3; i++) {
298
+ lo[i] = fminf(lo[i], s.mpn[n][i] - s.mpn[n][3]);
299
+ hi[i] = fmaxf(hi[i], s.mpn[n][i] + s.mpn[n][3]);
300
+ }
301
+ }
302
+ float h[3]; // the box's centre and half diagonal: a sphere that contains the box, so every node sphere
303
+ for (int i = 0; i < 3; i++) { c[i] = 0.5f * (lo[i] + hi[i]); h[i] = 0.5f * (hi[i] - lo[i]); }
304
+ r = sqrtf(h[0] * h[0] + h[1] * h[1] + h[2] * h[2]) * (1.f + 1e-5f) + 1e-6f; // (+ the rounding of the above)
305
+ }
306
+ for (int i = 0; i < 3; i++) s.mpg[k][i] = c[i];
307
+ s.mpg[k][3] = r;
308
+ }
309
+ __syncwarp();
310
+ int nk = 0;
311
+ for (int k0 = 0; k0 < MP_NGP; k0 += 32) { // the group pairs, one per lane: the overlapping ones into s.mpk
312
+ const int k = k0 + lane;
313
+ bool keep = false;
314
+ if (k < MP_NGP) {
315
+ const unsigned e = c_mpgp[k];
316
+ keep = mp_overlap(s, s.mpg[e & 255u], s.mpg[(e >> 8) & 255u], (e >> 16) & 1u ? (int)(e >> 17) + 1 : 0);
317
+ }
318
+ const unsigned bal = __ballot_sync(0xffffffffu, keep);
319
+ if (keep) s.mpk[nk + __popc(bal & lanes_below)] = (unsigned short)k;
320
+ nk += __popc(bal);
321
+ }
322
+ __syncwarp();
323
+ for (int j0 = 0; j0 < nk; j0 += 32) { // the kept group pairs' runs (c_mpgpruns: the runs grouped by group pair;
324
+ // lane j: group pair j's runs at stream positions exc_j .. inc_j - 1), a kept run's bit set in s.mprm
325
+ const int j = j0 + lane, gp = j < nk ? s.mpk[j] : 0;
326
+ const int first = j < nk ? c_mpgpfirst[gp] : 0, cnt = j < nk ? c_mpgpfirst[gp + 1] - first : 0;
327
+ int inc = cnt;
328
+ #pragma unroll
329
+ for (int o = 1; o < 32; o <<= 1) {
330
+ int v = __shfl_up_sync(0xffffffffu, inc, o);
331
+ if (lane >= o) inc += v;
332
+ }
333
+ const int total = __shfl_sync(0xffffffffu, inc, 31), exc = inc - cnt;
334
+ for (int t0 = 0; t0 < total; t0 += 32) {
335
+ const int t = t0 + lane;
336
+ int lo = 0;
337
+ #pragma unroll
338
+ for (int st = 16; st; st >>= 1) {
339
+ int e = __shfl_sync(0xffffffffu, exc, (lo + st) & 31);
340
+ if (lo + st < 32 && e <= t) lo += st;
341
+ }
342
+ const int at = __shfl_sync(0xffffffffu, first, lo) + t - __shfl_sync(0xffffffffu, exc, lo);
343
+ if (t < total) {
344
+ const int ri = c_mpgpruns[at];
345
+ const unsigned e = c_mprun[ri];
346
+ if (mp_overlap(s, s.mpn[e & 255u], s.mpn[(e >> 8) & 255u], (e >> 16) & 1u ? (int)(e >> 17) + 1 : 0))
347
+ atomicOr(&s.mprm[ri >> 5], 1u << (ri & 31));
348
+ }
349
+ }
350
+ }
351
+ __syncwarp();
352
+ for (int w0 = 0; w0 < MP_NRW; w0 += 32) { // the kept runs in run order (= pair order)
353
+ const unsigned word = w0 + lane < MP_NRW ? s.mprm[w0 + lane] : 0u;
354
+ const int c = __popc(word);
355
+ int inc = c;
356
+ #pragma unroll
357
+ for (int o = 1; o < 32; o <<= 1) {
358
+ int v = __shfl_up_sync(0xffffffffu, inc, o);
359
+ if (lane >= o) inc += v;
360
+ }
361
+ int pos = nkr + inc - c;
362
+ for (unsigned x = word; x; x &= x - 1u) s.mprl[pos++] = (unsigned short)((w0 + lane) * 32 + __ffs(x) - 1);
363
+ nkr += __shfl_sync(0xffffffffu, inc, 31);
364
+ }
365
+ #else
366
+ __syncwarp();
367
+ #pragma unroll 4
368
+ for (int r0 = 0; r0 < MP_NRUN; r0 += 32) { // the runs, one per lane, the kept ones in run order (= pair order)
369
+ const int ri = r0 + lane;
370
+ bool keep = false;
371
+ if (ri < MP_NRUN) {
372
+ const unsigned e = c_mprun[ri];
373
+ keep = mp_overlap(s, s.mpn[e & 255u], s.mpn[(e >> 8) & 255u], (e >> 16) & 1u ? (int)(e >> 17) + 1 : 0);
374
+ }
375
+ const unsigned bal = __ballot_sync(0xffffffffu, keep);
376
+ if (keep) s.mprl[nkr + __popc(bal & lanes_below)] = (unsigned short)ri;
377
+ nkr += __popc(bal);
378
+ }
379
+ #endif
380
+ __syncwarp();
381
+ for (int j0 = 0; j0 < nkr; j0 += 32) { // their pairs (lane j: run j's pairs at stream positions exc_j .. inc_j - 1)
382
+ const int j = j0 + lane, ri = j < nkr ? s.mprl[j] : 0;
383
+ const int first = j < nkr ? c_mprstart[ri] : 0, cnt = j < nkr ? c_mprstart[ri + 1] - first : 0;
384
+ int inc = cnt;
385
+ #pragma unroll
386
+ for (int o = 1; o < 32; o <<= 1) {
387
+ int v = __shfl_up_sync(0xffffffffu, inc, o);
388
+ if (lane >= o) inc += v;
389
+ }
390
+ const int total = __shfl_sync(0xffffffffu, inc, 31), exc = inc - cnt;
391
+ for (int t0 = 0; t0 < total; t0 += 32) {
392
+ const int t = t0 + lane;
393
+ int lo = 0;
394
+ #pragma unroll
395
+ for (int st = 16; st; st >>= 1) {
396
+ int e = __shfl_sync(0xffffffffu, exc, (lo + st) & 31);
397
+ if (lo + st < 32 && e <= t) lo += st;
398
+ }
399
+ const int pr = __shfl_sync(0xffffffffu, first, lo) + t - __shfl_sync(0xffffffffu, exc, lo);
400
+ const bool keep = t < total && pair_bound(s, pr, FN);
401
+ const unsigned bal = __ballot_sync(0xffffffffu, keep);
402
+ const int at = ncand + __popc(bal & lanes_below);
403
+ if (keep && at < NCAND) s.cand[at] = (unsigned short)pr;
404
+ ncand += __popc(bal);
405
+ }
406
+ }
407
+ #if NCAND < NPAIR
408
+ if (ncand > NCAND) { // candidates beyond capacity: their contacts are dropped
409
+ if (lane == 0) s.unsupported |= 4;
410
+ ncand = NCAND;
411
+ }
412
+ #endif
413
+ #elif BROAD_GROUPS
414
+ """
415
+
416
+ EDITS = (
417
+ ("#if BROAD_GROUPS\n struct { unsigned short cand[NCAND], gcand[NGRP]; };\n",
418
+ "#if MIDPHASE\n struct { MP_SCRATCH };\n#elif BROAD_GROUPS\n"
419
+ " struct { unsigned short cand[NCAND], gcand[NGRP]; };\n"),
420
+ ("#if BROAD_GROUPS\n struct { float gx[NGEOMC][3], gq[NGEOMC][4], con_dot[MAXCON][CD]; unsigned short cand[NCAND], gcand[NGRP]; };\n",
421
+ "#if MIDPHASE\n struct { float gx[NGEOMC][3], gq[NGEOMC][4], con_dot[MAXCON][CD]; MP_SCRATCH };\n#elif BROAD_GROUPS\n"
422
+ " struct { float gx[NGEOMC][3], gq[NGEOMC][4], con_dot[MAXCON][CD]; unsigned short cand[NCAND], gcand[NGRP]; };\n"),
423
+ ("// world poses of the collision geoms (position, rotation quaternion) from the body poses\n",
424
+ HELPER + "// world poses of the collision geoms (position, rotation quaternion) from the body poses\n"),
425
+ (" int ncand = 0;\n#if BROAD_GROUPS\n", " int ncand = 0;\n" + DEVICE),
426
+ ("#if HAS_DEFER\n sort_contacts(s, lane); // (the order of the split forward's, whose k_ccd appends in no fixed order)\n",
427
+ "#if HAS_DEFER || MIDPHASE\n sort_contacts(s, lane); // (the order of the split forward's, whose k_ccd appends in no fixed "
428
+ "order;\n // the mid-phase: the lanes' order of arrival depends on the compiled code around collide_pair)\n"),
429
+ )
430
+
431
+
432
+ def apply(src, m):
433
+ """The mid-phase's edits of the forest engine's text (adjoint.cuda_source, first) when enabled(m); else src."""
434
+ if "#define MIDPHASE 1" not in src:
435
+ return src
436
+ for a, b in EDITS:
437
+ assert src.count(a) == 1, f"midphase anchor found {src.count(a)} times: {a[:70]!r}"
438
+ src = src.replace(a, b)
439
+ return src