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,3716 @@
1
+ # Third-party code: the collision primitives in STEP_DEVICE (plane against sphere / capsule / box, sphere-sphere,
2
+ # sphere-capsule, capsule-capsule, sphere-box, capsule-box, box-box) are translated to CUDA from MuJoCo Warp,
3
+ # mujoco_warp/_src/collision_primitive_core.py, and make_frame from mujoco_warp/_src/math.py (github.com/google-deepmind/
4
+ # mujoco_warp; the version used here: etaoxing/mujoco_warp 357a75d, the head of google-deepmind/mujoco_warp pull
5
+ # request 1535), Copyright 2025 The Newton Developers, Apache License 2.0; parts of those follow MuJoCo's C
6
+ # implementation (Copyright DeepMind Technologies Limited, Apache License 2.0). Modified: float32 with explicit
7
+ # roundings where the adjoint replays them, the pairs spread over a warp's lanes, margin 0 only. The constraint rows and
8
+ # the Newton solver implement MuJoCo's / MuJoCo Warp's definitions (constraint.py, solver.py) and are this engine's own
9
+ # code.
10
+ """CUDA source of one G1 physics substep (block per world): collision, constraints, Newton solver, implicitfast update."""
11
+
12
+ import math
13
+ import os
14
+ import warnings
15
+
16
+ import mujoco
17
+ import numpy as np
18
+
19
+ from nablaengine.model import invweight as _invw
20
+
21
+ NEFC = 192
22
+ MAX_CONTACTS = 64
23
+ MAX_ROWS = 1023
24
+ WIDE_PAIRS = 512
25
+
26
+
27
+ def nefc(max_rows=None):
28
+ """Constraint row capacity per world: max_rows (1 .. MAX_ROWS), else NEFC."""
29
+ return NEFC if max_rows is None else int(max_rows)
30
+
31
+
32
+ def check_capacity(m, max_contacts=None, max_rows=None, terrain=None):
33
+ """Raise ValueError unless max_contacts (1 .. MAX_CONTACTS) and max_rows (1 .. MAX_ROWS) fit this engine; with a
34
+ terrain build ((TerrainConfig, robot geoms)) the model's pairs and the terrain's virtual pairs below 1024 (the
35
+ tape's 10-bit pair index there)."""
36
+ if max_contacts is not None and not 1 <= int(max_contacts) <= MAX_CONTACTS:
37
+ raise ValueError(f"max_contacts={max_contacts}: the G1-class engine holds 1 .. {MAX_CONTACTS} contacts per world")
38
+ if max_rows is not None and not 1 <= int(max_rows) <= MAX_ROWS:
39
+ raise ValueError(f"max_rows={max_rows}: the G1-class engine holds 1 .. {MAX_ROWS} constraint rows per world")
40
+ if terrain is not None and m.npair + len(terrain[1]) >= 1024:
41
+ raise ValueError(f"{m.npair} contact pairs and {len(terrain[1])} terrain geoms: a terrain build holds fewer "
42
+ "than 1024 pairs (the tape's 10-bit pair index)")
43
+
44
+
45
+ _WIDE_ROWS_HOOKS = (
46
+ (" unsigned hd = (unsigned)ncon | (unsigned)s.nefc << 8 | (unsigned)(s.nefc_dof - NFLOSS) << 16\n",
47
+ " unsigned hd = (unsigned)ncon | (unsigned)min(s.nefc, 255) << 8 | (unsigned)(s.nefc_dof - NFLOSS) << 16\n"),
48
+ (" __stcs(rec + OFF_RESERVED, 0.f);\n",
49
+ " __stcs(rec + OFF_RESERVED, __uint_as_float((unsigned)s.nefc)); // (the header's row count saturates)\n"),
50
+ )
51
+ _WIDE_PAIRS_HOOKS = (
52
+ (" if (rec) // tape: the contact table in contact (= row) order, two 16-bit entries pair | slot << 9 per word\n"
53
+ " for (int i = lane; i < (MAXCON + 1) / 2; i += 32) {\n"
54
+ " unsigned e0 = 2 * i < ncon ? (unsigned)s.con_pair[2 * i] | (unsigned)s.con_slot[2 * i] << 9 : TAPE_CON_NONE;\n"
55
+ " unsigned e1 = 2 * i + 1 < ncon ? (unsigned)s.con_pair[2 * i + 1] | (unsigned)s.con_slot[2 * i + 1] << 9\n"
56
+ " : TAPE_CON_NONE;\n"
57
+ " __stcs(rec + OFF_CON + i, __uint_as_float(e0 | e1 << 16));\n"
58
+ " }\n",
59
+ " if (rec) // tape: the contact table in contact (= row) order, one 32-bit entry pair | slot << 16 per contact\n"
60
+ " for (int i = lane; i < MAXCON; i += 32)\n"
61
+ " __stcs(rec + OFF_CON + i, __uint_as_float(i < ncon ? (unsigned)s.con_pair[i] | (unsigned)s.con_slot[i] << 16\n"
62
+ " : TAPE_CON_NONE));\n"),
63
+ (" unsigned con[(MAXCON + 1) / 2]; // the record's contact table: pair | slot << 9 per 16 bits\n",
64
+ " unsigned con[MAXCON]; // the record's contact table: pair | slot << 16 per contact (step.capacity_hooks)\n"),
65
+ (" for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.con[i] = __float_as_uint(__ldcs(rec + OFF_CON + i));\n",
66
+ " for (int i = lane; i < MAXCON; i += 32) s.con[i] = __float_as_uint(__ldcs(rec + OFF_CON + i));\n"),
67
+ (" const unsigned e = on ? (s.con[c >> 1] >> (16 * (c & 1))) & 0xFFFFu : 0u;\n"
68
+ " const int pair = e & 511u, slot = e >> 9, dim = on ? PDIM(pair) : 0;\n",
69
+ " const unsigned e = on ? s.con[c] : 0u;\n"
70
+ " const int pair = e & 0xFFFFu, slot = e >> 16, dim = on ? PDIM(pair) : 0;\n"),
71
+ (" const int pair = (s.con[c >> 1] >> (16 * (c & 1))) & 511u;\n",
72
+ " const int pair = s.con[c] & 0xFFFFu;\n"),
73
+ )
74
+
75
+
76
+ _MANY_ROWS_HOOKS = (
77
+ (" unsigned zprev = 0u;\n bool newton = false;\n", " unsigned long long zprev = 0ull;\n bool newton = false;\n"),
78
+ (" unsigned z = 0u;\n#pragma unroll\n for (int t = 0; t < RT; t++) {\n if (32 * t >= nefc) break;\n"
79
+ " float ds, dd, jv = rj[t];\n z |= (unsigned)row_piece(",
80
+ " unsigned long long z = 0ull;\n#pragma unroll\n for (int t = 0; t < RT; t++) {\n if (32 * t >= nefc) break;\n"
81
+ " float ds, dd, jv = rj[t];\n z |= (unsigned long long)row_piece("),
82
+ )
83
+
84
+
85
+ def wide_pairs(m, terrain=None):
86
+ """The tape records (pair, slot) in 32 bits: WIDE_PAIRS pairs or more, no terrain."""
87
+ return terrain is None and m.npair >= WIDE_PAIRS
88
+
89
+
90
+ def capacity_hooks(m, max_rows=None, terrain=None):
91
+ """Edits (anchor, replacement) of the forward and adjoint text (adjoint.cuda_source) for capacities beyond the
92
+ tape's default field widths; none for the default ones (the text unchanged):
93
+ - more than 255 rows: the record header's row count (8 bits) saturates at 255 and the record's reserved word holds
94
+ the count (tape.decode reads it there; the adjoint does not read it);
95
+ - WIDE_PAIRS pairs or more (no terrain): the contact table holds one 32-bit entry pair | slot << 16 per contact
96
+ instead of two 16-bit entries pair | slot << 9 per word (tape.py);
97
+ - more than 512 rows (more than 16 per lane): the line search's record of the rows' pieces (2 bits each, its exact
98
+ stop) in 64 bits."""
99
+ hooks = ()
100
+ if nefc(max_rows) > 255:
101
+ hooks += _WIDE_ROWS_HOOKS
102
+ if wide_pairs(m, terrain):
103
+ hooks += _WIDE_PAIRS_HOOKS
104
+ if nefc(max_rows) > 512:
105
+ hooks += _MANY_ROWS_HOOKS
106
+ return hooks
107
+ PROF_PHASES = ("smooth", "qacc_smooth", "collision", "contact_jac", "rows", "newton_init", "newton_grad",
108
+ "newton_hessian", "newton_chol", "newton_linesearch", "newton_update", "integrate", "ls_jv_Mp",
109
+ "count_ls_steps",
110
+ "sm_kin", "sm_force", "sm_accum", "sm_crb",
111
+ "ni_matvec", "ni_rowsjv",
112
+ "ng_rows", "ng_jtf_conf", "ng_jtf_dof", "ng_jtf_scatter",
113
+ "ls_rowsjv", "ls_matvec",
114
+ "col_geom", "nh_conC", "nh_copy_dof", "col_broad")
115
+ PROF_PARTITION = 12
116
+ PAIR_LAYOUT = (
117
+ ("c_pword", "u", 1),
118
+ )
119
+ PSET_WIDTH = 8
120
+ GEOM_LAYOUT = (
121
+ ("c_gbody", "i", 1), ("c_gtype", "i", 1), ("c_gsize", "f", 3), ("c_gpos", "f", 3), ("c_gquat", "f", 4),
122
+ ("c_grbound", "f", 1),
123
+ )
124
+ SOLVER_LAYOUT = (
125
+ ("c_binvw", "f", "nb"), ("c_dinvw", "f", "nv"), ("c_floss", "f", "nv"), ("c_jrange", "f", "nv2"),
126
+ ("c_jlim", "f", "nv"), ("c_jsolref", "f", 2), ("c_jsolimp", "f", 5), ("c_dsolref", "f", 2), ("c_dsolimp", "f", 5),
127
+ ("c_sopt", "f", 4))
128
+ GEOM_TYPE = {int(mujoco.mjtGeom.mjGEOM_PLANE): 0, int(mujoco.mjtGeom.mjGEOM_SPHERE): 1,
129
+ int(mujoco.mjtGeom.mjGEOM_CAPSULE): 2, int(mujoco.mjtGeom.mjGEOM_BOX): 3,
130
+ int(mujoco.mjtGeom.mjGEOM_CYLINDER): 5,
131
+ int(mujoco.mjtGeom.mjGEOM_MESH): 6}
132
+
133
+
134
+ def maxcon(m):
135
+ """Contact capacity per world: 32 for the Menagerie model (49 pairs, at most 11 contacts seen), 64 for the mjlab
136
+ model (502 pairs; up to 28 foot contacts alone). $DK_MAXCON overrides it (experiments); it
137
+ changes every build, the FFI library included, so it warns."""
138
+ default = 32 if m.npair <= 64 else 64
139
+ if os.environ.get("DK_MAXCON"):
140
+ warnings.warn(f"DK_MAXCON={os.environ['DK_MAXCON']} overrides the contact capacity (default {default}) of the "
141
+ "engine builds and the FFI library (an experiment switch)", RuntimeWarning, stacklevel=2)
142
+ return int(os.environ["DK_MAXCON"])
143
+ return default
144
+
145
+
146
+ def max_support(m):
147
+ """Largest number of dofs a contact Jacobian can touch: the dofs on exactly one of the two bodies' chains, over all
148
+ pairs (16 for both G1 models: a hand on the floor, root 6 + waist 3 + arm 7)."""
149
+ dofbody, mask = extra_constants(m)
150
+ return max(sum(1 for i in range(m.nv) if ((mask[b1] >> int(dofbody[i])) ^ (mask[b2] >> int(dofbody[i]))) & 1)
151
+ for b1, b2 in ((m.geom_bodyid[m.pair_geom1[p]], m.geom_bodyid[m.pair_geom2[p]]) for p in range(m.npair)))
152
+
153
+
154
+ def collision_geoms(m):
155
+ """The geoms that appear in a contact pair, in model order (index into the geom table)."""
156
+ return sorted(set(int(g) for g in m.pair_geom1) | set(int(g) for g in m.pair_geom2))
157
+
158
+
159
+ def pair_word(g1, g2, pset, dim, foot, plane=0):
160
+ """A contact pair as one 32-bit word: geom table indices g1, g2 (8 bits each), parameter set (8 bits), condim (4 bits),
161
+ foot-floor flag (1 bit), plane flag (1 bit: g1 is a plane); decoded on the device by PG1 / PG2 / PSET / PDIM /
162
+ PFOOT / PPLANE."""
163
+ assert g1 < 256 and g2 < 256 and pset < 256 and dim < 16
164
+ return g1 | g2 << 8 | pset << 16 | dim << 24 | foot << 28 | plane << 29
165
+
166
+
167
+ def pair_param_sets(m):
168
+ """(unique (mu, solref, solimp) rows as an (n, PSET_WIDTH) array, index of each pair's row): the 502 mjlab pairs
169
+ share a handful of parameter sets, so the pair table is one word per pair."""
170
+ keys, index = {}, []
171
+ for i in range(m.npair):
172
+ key = (float(m.pair_friction[i, 0]), *map(float, m.pair_solref[i]), *map(float, m.pair_solimp[i]))
173
+ index.append(keys.setdefault(key, len(keys)))
174
+ return np.asarray(list(keys), np.float64).reshape(len(keys), PSET_WIDTH), index
175
+
176
+
177
+ def const_layout(m, terrain=None):
178
+ """[(symbol, kind, length)] of pair_constants(m, ..., terrain) in packing order (terrain: (TerrainConfig, the
179
+ robot geoms of terrain.robot_terrain_geoms): NTG more pairs and one more geom, the terrain's pseudo geom)."""
180
+ ng = len(collision_geoms(m)) + (1 if terrain else 0)
181
+ npair = m.npair + (len(terrain[1]) if terrain else 0)
182
+ sizes = {"nb": m.nbody, "nv": m.nv, "nv2": 2 * m.nv}
183
+ npset = len(pair_param_sets(m)[0])
184
+ return ([(s, k, npair * w) for s, k, w in PAIR_LAYOUT] + [("c_pset", "f", npset * PSET_WIDTH)]
185
+ + [(s, k, ng * w) for s, k, w in GEOM_LAYOUT]
186
+ + [(s, k, sizes[w] if isinstance(w, str) else w) for s, k, w in SOLVER_LAYOUT]
187
+ + ([("c_ginvw", "f", ng)] if _invw.table(m, collision_geoms(m)) is not None else []))
188
+
189
+
190
+ def pair_constants(m, foot_pairs, terrain=None):
191
+ """Contact-pair arrays (geoms ordered by type, as MuJoCo's collision table expects), the collision-geom table and
192
+ the solver constants, as one float32 array in const_layout(m, terrain) order. terrain: (TerrainConfig, [(robot
193
+ geom, floor pair, foot)]): after the model's pairs, one virtual pair per such geom (g1 = the terrain's pseudo geom
194
+ on the world body, the last geom table row; the floor pair's parameter set, condim and foot flag)."""
195
+ geoms = collision_geoms(m)
196
+ gid = {g: i for i, g in enumerate(geoms)}
197
+ sets, words = pair_param_sets(m), []
198
+ foot = set(int(x) for x in foot_pairs)
199
+ assert foot <= set(range(m.npair)), f"foot pairs {sorted(foot)}: not all contact pair indices (0..{m.npair - 1})"
200
+ for i in range(m.npair):
201
+ g1, g2 = int(m.pair_geom1[i]), int(m.pair_geom2[i])
202
+ if int(m.geom_type[g1]) > int(m.geom_type[g2]):
203
+ g1, g2 = g2, g1
204
+ assert m.pair_margin[i] == 0 and m.pair_gap[i] == 0 and m.pair_friction[i, 0] == m.pair_friction[i, 1]
205
+ words.append(pair_word(gid[g1], gid[g2], sets[1][i], int(m.pair_dim[i]), int(i in foot),
206
+ int(GEOM_TYPE[int(m.geom_type[g1])] == 0)))
207
+ if terrain:
208
+ tg = len(geoms)
209
+ for g, p, ft in terrain[1]:
210
+ words.append(pair_word(tg, gid[g], sets[1][p], int(m.pair_dim[p]), ft, 0))
211
+ words = np.asarray(words, np.int64)
212
+ out = [np.stack([words & 0xFFFF, words >> 16], 1).ravel(), np.asarray(sets[0], np.float64).ravel()]
213
+ gtab = [m.geom_bodyid[geoms], [GEOM_TYPE[int(m.geom_type[g])] for g in geoms], m.geom_size[geoms],
214
+ m.geom_pos[geoms], m.geom_quat[geoms], m.geom_rbound[geoms]]
215
+ if terrain:
216
+ extra = [[0], [4], [[0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0]], [[1.0, 0.0, 0.0, 0.0]], [0.0]]
217
+ gtab = [np.concatenate([np.asarray(a, np.float64).reshape(len(geoms), -1),
218
+ np.asarray(b, np.float64).reshape(1, -1)]) for a, b in zip(gtab, extra)]
219
+ out += gtab
220
+ jr = np.zeros((m.nv, 2))
221
+ jlim = np.zeros(m.nv)
222
+ for j in range(1, m.njnt):
223
+ jr[m.jnt_dofadr[j]], jlim[m.jnt_dofadr[j]] = m.jnt_range[j], m.jnt_limited[j]
224
+ assert not m.jnt_margin.any() and (m.jnt_solref[1:] == m.jnt_solref[1]).all()
225
+ assert (m.jnt_solimp[1:] == m.jnt_solimp[1]).all() and (m.dof_solref == m.dof_solref[0]).all()
226
+ assert (m.dof_solimp == m.dof_solimp[0]).all() and (m.opt.cone == mujoco.mjtCone.mjCONE_PYRAMIDAL
227
+ or m.opt.cone == mujoco.mjtCone.mjCONE_ELLIPTIC)
228
+ out += [m.body_invweight0[:, 0], m.dof_invweight0, m.dof_frictionloss, jr, jlim, m.jnt_solref[1], m.jnt_solimp[1],
229
+ m.dof_solref[0], m.dof_solimp[0],
230
+ [m.opt.impratio, m.stat.meaninertia, m.opt.tolerance, m.npair]]
231
+ tab = _invw.table(m, geoms, 1 if terrain else 0)
232
+ if tab is not None:
233
+ out += [tab]
234
+ return np.concatenate([np.asarray(x, np.float64).ravel() for x in out]).astype(np.float32)
235
+
236
+
237
+ def hess_columns(kdof, passes=3):
238
+ """Support pairs (a, b), b <= a < kdof, of the Hessian assembly per lane: one fixed column b per lane and set, so
239
+ that a lane computes G_b = C J_b once per contact. Set k covers the rows lo_k <= a < lo_(k+1), the largest range
240
+ whose columns (each split over ceil(rows / passes) lanes, rows interleaved) fit 32 lanes. Returns [(lo, hi, table)],
241
+ table[pass][lane] = (a, b, thr), the pair valid when a < nd, i.e. nd > thr (thr = 255: none)."""
242
+ sets, lo = [], 0
243
+ while lo < kdof:
244
+ def lanes(hi):
245
+ return sum(math.ceil((hi - max(lo, b)) / passes) for b in range(hi))
246
+ hi = max(h for h in range(lo + 1, kdof + 1) if lanes(h) <= 32)
247
+ tab = [[(0, 0, 255)] * 32 for _ in range(passes)]
248
+ lane = 0
249
+ for b in range(hi):
250
+ rows = math.ceil((hi - max(lo, b)) / passes)
251
+ for j in range(rows):
252
+ for t in range(passes):
253
+ a = max(lo, b) + j + rows * t
254
+ tab[t][lane] = (a, b, a) if a < hi else (b, b, 255)
255
+ lane += 1
256
+ sets.append((lo, hi, tab))
257
+ lo = hi
258
+ return sets
259
+
260
+
261
+ def floor_geom(m):
262
+ """Index in the collision-geom table of the model's only plane, or -1 (none or several)."""
263
+ planes = [i for i, g in enumerate(collision_geoms(m)) if GEOM_TYPE[int(m.geom_type[g])] == 0]
264
+ return planes[0] if len(planes) == 1 else -1
265
+
266
+
267
+ def solimp_pow2(m):
268
+ """Whether every solimp power the rows use (contact pairs, joint limits, dof frictionloss) is 2."""
269
+ pw = list(m.pair_solimp[:, 4]) + list(m.jnt_solimp[1:, 4]) + list(m.dof_solimp[m.dof_frictionloss > 0, 4])
270
+ return all(float(x) == 2.0 for x in pw)
271
+
272
+
273
+ def dof_body_root6(m):
274
+ """True when body 1 (the free root) has dofs 0-5 and every later dof i is the only dof of body i - 4 (bodies and
275
+ dofs in the same order): a contact's support mask is then a shift of its bodies' chain mask (support_mask)."""
276
+ d = np.asarray(m.dof_bodyid)
277
+ return m.nv >= 6 and bool((d[:6] == 1).all() and (d[6:] == np.arange(6, m.nv) - 4).all())
278
+
279
+
280
+ CLAMP_IMPLICIT_DELTA = 0.2
281
+
282
+
283
+ def clamp_implicit():
284
+ """(mode, delta) of the implicit actuator damping on dofs whose actuator force is clamped at jnt_actfrcrange, from
285
+ $DK_CLAMP_IMPLICIT and $DK_CLAMP_IMPLICIT_DELTA at source generation (docs/configuration.md):
286
+ 0 (default) the dof keeps kv in implicitfast's M + h kv (MuJoCo / MuJoCo Warp up to 3.17)
287
+ 1 a clamped dof drops it (MuJoCo / MuJoCo Warp 4.0: mjd_actuatorDerivSkip, _jnt_actfrc_clamped); the
288
+ dynamics jump where a force reaches its limit
289
+ 2 it fades: kv w with w = exp(-o / delta), o = (|f| - tau_max) / tau_max >= 0 the relative overshoot
290
+ of the unclamped PD force (w = 1 at the limit: continuous; 1's limit deep in saturation); the tape
291
+ records w per dof and the adjoint differentiates it
292
+ delta: $DK_CLAMP_IMPLICIT_DELTA (mode 2 only; default CLAMP_IMPLICIT_DELTA)."""
293
+ raw = os.environ.get("DK_CLAMP_IMPLICIT", "") or "0"
294
+ if raw not in ("0", "1", "2"):
295
+ raise ValueError(f"DK_CLAMP_IMPLICIT={raw!r}: 0, 1 or 2")
296
+ mode = int(raw)
297
+ draw = os.environ.get("DK_CLAMP_IMPLICIT_DELTA", "")
298
+ if draw and mode != 2:
299
+ raise ValueError("DK_CLAMP_IMPLICIT_DELTA is DK_CLAMP_IMPLICIT=2's width")
300
+ delta = float(np.float32(draw)) if draw else CLAMP_IMPLICIT_DELTA
301
+ if not (math.isfinite(delta) and delta > 0.0):
302
+ raise ValueError(f"DK_CLAMP_IMPLICIT_DELTA={draw!r}: finite and > 0")
303
+ return mode, delta
304
+
305
+
306
+ def clamp_implicit_defines():
307
+ """The #defines of clamp_implicit() (empty for the default mode 0: the source text unchanged)."""
308
+ mode, delta = clamp_implicit()
309
+ if mode == 0:
310
+ return ""
311
+ return (f"#define DK_CLAMP_IMPLICIT {mode} // clamped dofs' implicit kv (step.clamp_implicit)\n"
312
+ + (f"#define DK_CLAMP_IMPLICIT_DELTA {delta!r}f\n" if mode == 2 else ""))
313
+
314
+
315
+ def tree_chol():
316
+ """The tree-sparse Cholesky mode from $DK_TREE_CHOL at source generation (docs/configuration.md; experimental):
317
+ 0 (default) the dense factorizations (CHOL_SOLVE): the source text unchanged
318
+ mass the mass-matrix factorizations (substep_pre's qacc_smooth: M; implicitfast: M + h diag(kv),
319
+ the tape's L_Q) and the adjoint's L_Q solve as A = R' R on the tree pattern (source.tree_tables)
320
+ 1 those, and where tree_hessian(m) holds: the Newton factorization, its re-use
321
+ (NEWTON_REUSE: chol_resolve) and the adjoint's L_H solve too (the tape's L_H = R)
322
+ Not bitwise against the dense path (rounding)."""
323
+ raw = os.environ.get("DK_TREE_CHOL", "") or "0"
324
+ if raw not in ("0", "1", "mass"):
325
+ raise ValueError(f"DK_TREE_CHOL={raw!r}: 0, 1 or mass")
326
+ return raw
327
+
328
+
329
+ def tree_hessian(m):
330
+ """Whether every contact pair of model m is with the world or between two bodies on one root-to-leaf chain: a
331
+ contact's Jacobian columns are then one chain's dofs, and the Newton Hessian M + J' D J (with the limit and
332
+ frictionloss rows, single dofs) keeps the tree pattern of M. False for a model without pairs (nothing to gain).
333
+ Terrain builds add only pairs with the (static) terrain."""
334
+ def chain(b):
335
+ out = set()
336
+ while b > 0:
337
+ out.add(b)
338
+ b = int(m.body_parentid[b])
339
+ return out
340
+ for p in range(m.npair):
341
+ b1, b2 = int(m.geom_bodyid[m.pair_geom1[p]]), int(m.geom_bodyid[m.pair_geom2[p]])
342
+ if b1 and b2:
343
+ a1, a2 = chain(b1), chain(b2)
344
+ if not (a1 <= a2 or a2 <= a1):
345
+ return False
346
+ return m.npair > 0
347
+
348
+
349
+ def tree_chol_stages(m):
350
+ """The tree-sparse factorizations a build of model m uses under $DK_TREE_CHOL: None (off), or {"mass": True,
351
+ "newton": tree_hessian(m) with DK_TREE_CHOL=1} (jax_ffi / torch_ffi info "tree_chol"; tape.factor_forms)."""
352
+ mode = tree_chol()
353
+ if mode == "0":
354
+ return None
355
+ return {"mass": True, "newton": mode == "1" and tree_hessian(m)}
356
+
357
+
358
+ TREE_CHOL_HOOKS = (
359
+ (" CHOL_SOLVE(s.M, s.L, s.qacc0, lane, s.cbuf);\n",
360
+ " chol_tree_factor(s.M, s.L, 1, lane); // (DK_TREE_CHOL: M = R' R)\n chol_tree_solve(s.L, s.qacc0, lane);\n"),
361
+ (" CHOL_SOLVE(s.L, s.L, s.tmp, lane, s.cbuf);\n",
362
+ " chol_tree_factor(s.L, s.L, 0, lane); // (DK_TREE_CHOL: the tape's L_Q = R)\n"
363
+ " chol_tree_solve(s.L, s.tmp, lane);\n"),
364
+ )
365
+ TREE_CHOL_NEWTON_HOOKS = (
366
+ (" chol_resolve(s.L, s.p, lane, s.cbuf);\n",
367
+ " chol_tree_solve(s.L, s.p, lane); // (DK_TREE_CHOL stage 1a)\n"),
368
+ (" CHOL_SOLVE(s.L, s.L, s.p, lane, s.cbuf);\n",
369
+ " chol_tree_factor(s.L, s.L, 0, lane); // (DK_TREE_CHOL stage 1a: the tape's L_H = R)\n"
370
+ " chol_tree_solve(s.L, s.p, lane);\n"),
371
+ )
372
+ TREE_CHOL_ANCHOR = "// which Cholesky the engine uses: CHOL_SOLVE("
373
+
374
+
375
+ def tree_chol_hooks(m):
376
+ """The forward's DK_TREE_CHOL hooks for model m (() when off): the device code (source.tree_chol_device) before
377
+ CHOL_SOLVE's definition, the mass-matrix sites, and with the tree-pattern factor the Newton sites (the chol_resolve call is in the
378
+ text of every build; NEWTON_REUSE decides whether it is compiled)."""
379
+ st = tree_chol_stages(m)
380
+ if st is None:
381
+ return ()
382
+ from nablaengine.g1_engine import source
383
+ hooks = ((TREE_CHOL_ANCHOR, source.tree_chol_device(m) + TREE_CHOL_ANCHOR),) + TREE_CHOL_HOOKS
384
+ return hooks + (TREE_CHOL_NEWTON_HOOKS if st["newton"] else ())
385
+
386
+
387
+ def step_header(m, max_contacts=None, terrain=None, max_rows=None):
388
+ p, g, kdof = m.npair, len(collision_geoms(m)), max_support(m)
389
+ hs = hess_columns(kdof)
390
+ hcol = [a | b << 8 | thr << 16 for _, _, tab in hs for row in tab for a, b, thr in row]
391
+ ter, pt = "", p
392
+ if terrain:
393
+ cfg, tg = terrain
394
+ ter = (f"#define HAS_TERRAIN 1\n#define NTG {len(tg)} // robot geoms that collide with the terrain\n"
395
+ f"#define TERRAIN_FLOOR {int(cfg.floor)} // keep the model's floor plane pairs\n"
396
+ f"#define TERRAIN_CAP_PTS {int(cfg.cap_points)} // heightfield samples per capsule\n"
397
+ f"#define TERRAIN_HF_NATIVE {int(cfg.mode == 'native')} // heightfield contacts per prism\n"
398
+ f"#define TERRAIN_NOBJ {int(cfg.objects)} // per-world object slots (after the COM offset in com)\n"
399
+ f"#define COM_WORDS {cfg.com_words()} // floats per world of the com input\n"
400
+ f"#define OBJ_E0 {_terrain_mod().OBJ_E0} // the element index of object slot 0\n"
401
+ "#ifndef TERRAIN_SORT\n#define TERRAIN_SORT 1 // contacts sorted by (pair, element, slot)\n#endif\n")
402
+ pt, g = p + len(tg), g + 1
403
+ return ter + clamp_implicit_defines() + f"""
404
+ #define NPAIR {p}
405
+ #define NGEOMC {g}
406
+ #define MAXCON {max_contacts or maxcon(m)}
407
+ #define KDOF {kdof}
408
+ #define HSETS {len(hs)} // Hessian assembly (hess_columns(KDOF)): sets of 3 passes, their first rows, pairs per lane
409
+ #define HSET_LO {{{", ".join(str(lo) for lo, _, _ in hs)}}}
410
+ __device__ const unsigned c_hcol[{len(hcol)}] = {{{", ".join(map(str, hcol))}}}; // a | b << 8 | thr << 16
411
+ #define HAS_BOX {int(any(m.geom_type[g] == mujoco.mjtGeom.mjGEOM_BOX for g in collision_geoms(m)))} // compile box code
412
+ #define FLOOR_G {floor_geom(m)} // the geom table index of the only plane (-1: none or several)
413
+ #define NEFC {nefc(max_rows)}
414
+ #define DOF_BODY_ROOT6 {int(dof_body_root6(m))} // step.dof_body_root6 (support_mask in closed form)
415
+ #define NFLOSS {int((m.dof_frictionloss > 0).sum())} // dofs with a frictionloss row (the first rows)
416
+ #define SOLIMP_POW2 {int(solimp_pow2(m))} // every solimp power of the model is 2 (kbimp without the general powers)
417
+ #define NPROF {len(PROF_PHASES)}
418
+ DKC unsigned int c_pword[{pt}]; // pair_word(): g1 | g2 << 8 | pset << 16 | dim << 24 | foot << 28 | plane << 29
419
+ DKC float c_pset[{len(pair_param_sets(m)[0]) * PSET_WIDTH}]; // per parameter set: mu, solref[2], solimp[5]
420
+ #define PG1(pr) ((int)(c_pword[pr] & 255u))
421
+ #define PG2(pr) ((int)((c_pword[pr] >> 8) & 255u))
422
+ #define PSET(pr) ((int)((c_pword[pr] >> 16) & 255u))
423
+ #define PDIM(pr) ((int)((c_pword[pr] >> 24) & 15u))
424
+ #define PFOOT(pr) ((int)((c_pword[pr] >> 28) & 1u))
425
+ #define PPLANE(pr) ((int)((c_pword[pr] >> 29) & 1u))
426
+ #define PMU(pr) (c_pset[PSET_WIDTH * PSET(pr)])
427
+ #define PSOLREF(pr) (c_pset + PSET_WIDTH * PSET(pr) + 1)
428
+ #define PSOLIMP(pr) (c_pset + PSET_WIDTH * PSET(pr) + 3)
429
+ #define PSET_WIDTH {PSET_WIDTH}
430
+ DKC int c_gbody[{g}], c_gtype[{g}];
431
+ DKC float c_gsize[{g * 3}], c_gpos[{g * 3}], c_gquat[{g * 4}], c_grbound[{g}];
432
+ DKC float c_binvw[NB], c_dinvw[NV], c_floss[NV], c_jrange[NV * 2], c_jlim[NV], c_jsolref[2], c_jsolimp[5],
433
+ c_dsolref[2], c_dsolimp[5], c_sopt[4]; // impratio, meaninertia, tolerance, npair
434
+ {_invw.header(m, collision_geoms(m))}"""
435
+
436
+
437
+ STEP_DEVICE = r"""
438
+ // NEWTON_REUSE: a Newton iteration whose rows all kept their zones (a third of them on a 4096-state corpus) re-uses
439
+ // the last factor (chol_resolve). Split forward, ms per control step (that corpus, 10 iterations): RTX 3090 3.07
440
+ // against 3.34 without (1.66 / 1.77 at 1787 worlds, the waves of 4096 worlds on the target GPUs); V100 2% slower
441
+ // (6.34 / 6.20)
442
+ #ifndef NEWTON_REUSE
443
+ #define NEWTON_REUSE (NV > 32 && NV <= 35)
444
+ #endif
445
+ // DK_CLAMP_IMPLICIT (step.clamp_implicit): the implicit actuator damping of a dof whose actuator force is clamped;
446
+ // 0 keeps c_kv, 1 and 2 use the dof's s.kvi (set with the clamp test in substep_pre)
447
+ #ifndef DK_CLAMP_IMPLICIT
448
+ #define DK_CLAMP_IMPLICIT 0
449
+ #endif
450
+ static_assert(DK_CLAMP_IMPLICIT >= 0 && DK_CLAMP_IMPLICIT <= 2, "DK_CLAMP_IMPLICIT: 0, 1 or 2");
451
+ #if DK_CLAMP_IMPLICIT
452
+ #define KVI(i) s.kvi[i]
453
+ #else
454
+ #define KVI(i) c_kv[i]
455
+ #endif
456
+ struct Sim {
457
+ float Q[NB][4], X[NB][3]; // body poses
458
+ union { // the smooth phase's body quantities and the constraint rows are never alive at the same time
459
+ struct {
460
+ float W[NB][3], V[NB][3];
461
+ union { // the collision's candidate pairs (after the mass matrix)
462
+ struct { float AL[NB][3], A[NB][3], F[NB][3], N[NB][3], J[NB][10]; };
463
+ unsigned short cand[NPAIR];
464
+ };
465
+ };
466
+ struct {
467
+ unsigned char efc_kind[NEFC], efc_a[NEFC];
468
+ signed char efc_b[NEFC];
469
+ float efc_D[NEFC], efc_aref[NEFC], efc_jar[NEFC], efc_jv[NEFC]; // efc_jv: J p in the line search, else forces
470
+ };
471
+ };
472
+ float M[NTRI], L[NTRI]; // mass matrix and Cholesky scratch, packed lower triangles TRI(i, j)
473
+ float qpos[NQ], qvel[NV], zero[NV], qsm[NV], qacc0[NV], qacc[NV], Ma[NV], grad[NV], p[NV], Mp[NV], tmp[NV];
474
+ #if DK_CLAMP_IMPLICIT
475
+ float kvi[NV]; // implicitfast's actuator damping per dof (DK_CLAMP_IMPLICIT)
476
+ #endif
477
+ alignas(16) float cbuf[72]; // CHOL_SOLVE's scratch (chol_solve_bcast)
478
+ float com[3], fric;
479
+ float gx[NGEOMC][3], gq[NGEOMC][4]; // world poses of the collision geoms
480
+ int ncon, nefc, unsupported;
481
+ int min_nu_bits; // tape: smallest centre / axis distance (before the radii) of a sphere or capsule self contact, as
482
+ // float bits (non-negative: the integer order is the float order, so atomicMin works); +inf if none
483
+ int con_pair[MAXCON], con_dim[MAXCON], con_row[MAXCON], con_nrow[MAXCON], nefc_dof;
484
+ union { // per-contact scratch, each consumed right after it is written
485
+ float con_dot[MAXCON][3]; // J_c,d v (rows_jv)
486
+ float con_f[MAXCON][3]; // a contact's row forces combined per frame direction (rows_jtf)
487
+ float con_C[MAXCON][5]; // Hessian coefficients on (n n, n t1, t1 t1, n t2, t2 t2), see the Newton loop
488
+ };
489
+ // contact Jacobian rows (normal, two tangents) on the contact's support: the con_nd[c] dofs con_dof[c][k] (ascending)
490
+ float con_dist[MAXCON], con_pos[MAXCON][3], con_frame[MAXCON][9], con_mu[MAXCON];
491
+ alignas(16) float con_J[MAXCON][3][KDOF]; // (16-byte aligned: con_jv's 128-bit loads)
492
+ alignas(16) unsigned char con_dof[MAXCON][KDOF];
493
+ unsigned char con_slot[MAXCON]; // which contact of its pair (tape): plane-capsule end, parallel capsule-capsule candidate
494
+ int con_nd[MAXCON];
495
+ unsigned long long con_mask[MAXCON]; // the support as dof bits (bit i: dof i; con_dof[c][k] is the k-th set bit)
496
+ #ifdef DK_PROFILE
497
+ long long prof[NPROF], prof_t, prof_u;
498
+ #endif
499
+ #ifdef DK_TAPE_VERIFY
500
+ float Lv[NTRI]; // debug: the factor of the last Newton assembly, compared with a re-assembly at the final zones
501
+ #endif
502
+ };
503
+
504
+ // a condition that is the same on every lane (from warp_sum or the like), as a vote: the compiler then knows the branch
505
+ // is uniform. Without it the Newton loop counts as divergent control flow and every shuffle and __syncwarp() in it, and
506
+ // in the functions it calls (CHOL_SOLVE), gets a divergence check (BRA.DIV / BRA.CONV, and no scheduling across it):
507
+ // chol_solve_bcast 8.2k cycles from a uniform caller, 12.9k from a divergent one (V100). The other source of such
508
+ // checks is add_contact's shared atomicAdd, whose result is used in the divergent collision code: in k_substep it costs
509
+ // the whole kernel its convergence, in the split forward only k_pre. Split forward, ms per control step (a 4096-state
510
+ // corpus, 10 iterations, alternating runs): V100 6.34 against 7.27 without (-DDK_UNIFORM=0), RTX 3090 3.07 against
511
+ // 3.14
512
+ #ifndef DK_UNIFORM
513
+ #define DK_UNIFORM 1
514
+ #endif
515
+ #if DK_UNIFORM
516
+ #define UNIFORM(c) __all_sync(0xffffffffu, (c))
517
+ #else
518
+ #define UNIFORM(c) (c)
519
+ #endif
520
+ // the same for an integer that is the same on every lane (a count in shared memory): its bits through votes, for loop
521
+ // bounds around shuffles and ballots
522
+ __device__ __forceinline__ int uniform_int(int x, int bits) {
523
+ #if DK_UNIFORM
524
+ int u = 0;
525
+ #pragma unroll
526
+ for (int b = 0; b < bits; b++) u |= (int)__any_sync(0xffffffffu, (x >> b) & 1) << b;
527
+ return u;
528
+ #else
529
+ return x;
530
+ #endif
531
+ }
532
+
533
+ // phase boundary: a __syncwarp() in every build (the code relies on it), plus per-phase cycle counters of one world
534
+ // (lane 0) with -DDK_PROFILE; phases: PROF_PHASES in step.py
535
+ #ifdef DK_PROFILE
536
+ #define PROF_START() do { __syncwarp(); if (lane == 0) s.prof_t = s.prof_u = clock64(); } while (0)
537
+ #define PROF(k) do { __syncwarp(); if (lane == 0) { long long t_ = clock64(); s.prof[k] += t_ - s.prof_t; s.prof_t = s.prof_u = t_; } __syncwarp(); } while (0)
538
+ #define SUBPROF(k) do { __syncwarp(); if (lane == 0) { long long t_ = clock64(); s.prof[k] += t_ - s.prof_u; s.prof_u = t_; } __syncwarp(); } while (0)
539
+ #else
540
+ #define SUBPROF(k)
541
+ #define PROF_START() __syncwarp()
542
+ #define PROF(k) __syncwarp()
543
+ #endif
544
+
545
+ // inlining of the larger helpers: code size (instruction fetch) against call overhead (an A / B switch, e.g.
546
+ // -DDK_INL_MATVEC=__noinline__). newton_grad not inlined (one copy instead of two): RTX 3090 1.3% faster, V100 0.2%;
547
+ // matvec, total_cost or refresh not inlined: no gain beyond the noise on the RTX 3090
548
+ // DK_JTF_GATHER: rows_jtf's contact part J' f as a per-dof gather over the contacts' support masks (con_mask, written
549
+ // by substep_pre), in registers and without a __syncwarp() per contact, instead of a scatter of each contact over its
550
+ // support (0). Split forward, ms per control step (a 4096-state corpus, 10 iterations, alternating runs, the other
551
+ // switches of this group on):
552
+ // V100 6.22 against 6.31 for the scatter (1787 worlds 2.60 / 2.64), RTX 3090 -1.3% (1787 worlds -0.7%)
553
+ #ifndef DK_JTF_GATHER
554
+ #define DK_JTF_GATHER 1
555
+ #endif
556
+ // DK_JV_VEC: con_jv reads a contact row's Jacobian entries and support dofs from Hand with 128-bit loads (con_J,
557
+ // con_dof 16-byte aligned; RTX 3090 -1.2 to -1.5%, V100 -0.4%); DK_GRAD_COST: the line search's new cost is summed
558
+ // in newton_grad's |grad| reduction (one interleaved butterfly; -0.1 to -0.2%); DK_HESS_DOFPAR: the Hessian's dof-row
559
+ // curvatures added to L by one lane per row (the dof rows' diagonals are distinct when there are no frictionloss rows:
560
+ // one limit row per dof) instead of one row at a time with two shuffles each (RTX 3090 -0.6%, V100 -0.3%)
561
+ #ifndef DK_JV_VEC
562
+ #define DK_JV_VEC 1
563
+ #endif
564
+ #ifndef DK_GRAD_COST
565
+ #define DK_GRAD_COST 1
566
+ #endif
567
+ #ifndef DK_HESS_DOFPAR
568
+ #define DK_HESS_DOFPAR 1
569
+ #endif
570
+ #ifndef DK_INL_COLLIDE
571
+ #define DK_INL_COLLIDE
572
+ #endif
573
+ #ifndef DK_INL_ROWSJV
574
+ #define DK_INL_ROWSJV
575
+ #endif
576
+ #ifndef DK_INL_GRAD
577
+ #define DK_INL_GRAD __noinline__
578
+ #endif
579
+ #ifndef DK_INL_MATVEC
580
+ #define DK_INL_MATVEC __forceinline__
581
+ #endif
582
+ #ifndef DK_INL_COST
583
+ #define DK_INL_COST
584
+ #endif
585
+
586
+ __device__ __forceinline__ void normalize3_rn(float* v) {
587
+ float n = sqrtf(dot3_rn(v, v));
588
+ if (n > 0.f) { v[0] /= n; v[1] /= n; v[2] /= n; }
589
+ }
590
+
591
+ // MuJoCo's orthogonals(a) / make_frame(a): rows n, b, c (explicit roundings, as all of the contact geometry below:
592
+ // the adjoint's replay computes the same bits, see source.DEVICE)
593
+ __device__ __forceinline__ void make_frame(const float* n, float* fr) {
594
+ float b[3] = {0.f, 0.f, 0.f};
595
+ if (-0.5f < n[1] && n[1] < 0.5f) b[1] = 1.f; else b[2] = 1.f;
596
+ float d = dot3_rn(n, b);
597
+ for (int k = 0; k < 3; k++) b[k] = RFMS(n[k], d, b[k]);
598
+ normalize3_rn(b);
599
+ float c[3];
600
+ cross_rn(n, b, c);
601
+ for (int k = 0; k < 3; k++) { fr[k] = n[k]; fr[3 + k] = b[k]; fr[6 + k] = c[k]; }
602
+ }
603
+
604
+ // slot: which contact of the pair this is (the tape's contact table, tape.py): the end e of a plane-capsule pair
605
+ // (0: +axis, 1: -axis), the candidate e = 0..3 of a parallel capsule-capsule pair, a box corner / clip point; else 0.
606
+ // (The atomicAdd's result in divergent code: see UNIFORM)
607
+ template <class S>
608
+ __device__ __forceinline__ bool add_contact(S& s, int pair, int slot, float dist, const float* pos,
609
+ const float* frame) {
610
+ int c = atomicAdd(&s.ncon, 1);
611
+ if (c >= MAXCON) return false;
612
+ s.con_pair[c] = pair;
613
+ s.con_slot[c] = (unsigned char)slot;
614
+ s.con_dim[c] = PDIM(pair);
615
+ s.con_dist[c] = dist;
616
+ for (int k = 0; k < 3; k++) s.con_pos[c][k] = pos[k];
617
+ for (int k = 0; k < 9; k++) s.con_frame[c][k] = frame[k];
618
+ s.con_mu[c] = PFOOT(pair) ? s.fric : PMU(pair);
619
+ return true;
620
+ }
621
+
622
+ // a contact from the sphere core (sphere-sphere, sphere-capsule, capsule-capsule): frame from the normal n, and the tape's
623
+ // min_nu (nu: the centre or axis distance)
624
+ template <class S>
625
+ __device__ __forceinline__ void add_sphere_contact(S& s, int pair, int slot, float nu, float dist, const float* pos,
626
+ const float* n) {
627
+ float fr[9];
628
+ make_frame(n, fr);
629
+ if (add_contact(s, pair, slot, dist, pos, fr)) atomicMin(&s.min_nu_bits, __float_as_int(nu));
630
+ }
631
+
632
+ // world pose (centre gx, rotation quaternion gq) of collision geom g on its body's pose (Qb, Xb): the forward's
633
+ // geom_poses and the adjoint's replay (adjoint.py adj_contacts)
634
+ __device__ __forceinline__ void geom_pose(int g, const float* Qb, const float* Xb, float* gx, float* gq) {
635
+ float t[3];
636
+ qrot_rn(Qb, c_gpos + 3 * g, t);
637
+ for (int i = 0; i < 3; i++) gx[i] = RADD(Xb[i], t[i]);
638
+ qmul_rn(Qb, c_gquat + 4 * g, gq);
639
+ }
640
+
641
+ // world poses of the collision geoms (position, rotation quaternion) from the body poses
642
+ template <class S>
643
+ __device__ __forceinline__ void geom_poses(S& s, int lane) {
644
+ for (int g = lane; g < NGEOMC; g += 32) {
645
+ int b = c_gbody[g];
646
+ geom_pose(g, s.Q[b], s.X[b], s.gx[g], s.gq[g]);
647
+ }
648
+ }
649
+
650
+ // returns the centre distance nu = |p2 - p1| (the tape's min_nu: the contact normal's derivative is of order 1 / nu)
651
+ __device__ __forceinline__ float sphere_sphere(const float* p1, float r1, const float* p2, float r2, float* dist,
652
+ float* pos, float* n) {
653
+ float dir[3] = {RSUB(p2[0], p1[0]), RSUB(p2[1], p1[1]), RSUB(p2[2], p1[2])};
654
+ float d = sqrtf(dot3_rn(dir, dir));
655
+ if (d == 0.f) { n[0] = 1.f; n[1] = 0.f; n[2] = 0.f; } else { for (int k = 0; k < 3; k++) n[k] = dir[k] / d; }
656
+ *dist = RSUB(d, RADD(r1, r2));
657
+ float hp = RFMA(0.5f, *dist, r1);
658
+ for (int k = 0; k < 3; k++) pos[k] = RFMA(n[k], hp, p1[k]);
659
+ return d;
660
+ }
661
+
662
+ // The contact geometry of the mjlab model's primitives (MuJoCo Warp's collision_primitive_core), shared by the
663
+ // forward's collide_pair and the adjoint's replay (adjoint_contact.adj_contact_geom): the intermediates the VJP needs
664
+ // are outputs (the forward drops them).
665
+
666
+ // a sphere of radius r at c on the plane through p1 with normal n (plane-sphere; plane-capsule: an end of the
667
+ // capsule): the distance, and the contact point pos, midway in the penetration
668
+ __device__ __forceinline__ float plane_point(const float* p1, const float* n, const float* c, float r, float* pos) {
669
+ float dist = RSUB(RSUB(dot3_rn(c, n), dot3_rn(p1, n)), r), hp = RFMA(0.5f, dist, r);
670
+ for (int k = 0; k < 3; k++) pos[k] = RFMS(n[k], hp, c[k]);
671
+ return dist;
672
+ }
673
+
674
+ // the frame of a plane-capsule contact: rows n, b = the capsule axis projected on the plane and normalized (make_frame's
675
+ // basis vector where the projection is shorter than 0.5), n x b; returns the projection's length
676
+ __device__ __forceinline__ float plane_capsule_frame(const float* n, const float* axis, float* fr) {
677
+ float na = dot3_rn(n, axis), b[3];
678
+ for (int k = 0; k < 3; k++) b[k] = RFMS(n[k], na, axis[k]);
679
+ float bn = sqrtf(dot3_rn(b, b));
680
+ if (bn > 0.f) for (int k = 0; k < 3; k++) b[k] /= bn;
681
+ if (bn < 0.5f) {
682
+ b[0] = 0.f; b[1] = 0.f; b[2] = 0.f;
683
+ if (-0.5f < n[1] && n[1] < 0.5f) b[1] = 1.f; else b[2] = 1.f;
684
+ }
685
+ float c[3];
686
+ cross_rn(n, b, c);
687
+ for (int k = 0; k < 3; k++) { fr[k] = n[k]; fr[3 + k] = b[k]; fr[6 + k] = c[k]; }
688
+ return bn;
689
+ }
690
+
691
+ // end e of a capsule (centre p, unit axis, half length hl): e = 0 the +axis end, 1 the -axis end
692
+ __device__ __forceinline__ void capsule_end(const float* p, const float* axis, float hl, int e, float* ce) {
693
+ for (int k = 0; k < 3; k++) {
694
+ float l = RMUL(axis[k], hl);
695
+ ce[k] = e == 0 ? RADD(p[k], l) : RSUB(p[k], l);
696
+ }
697
+ }
698
+
699
+ // sphere-capsule (MuJoCo Warp's sphere_capsule): the closest point pt = a + t ab of the capsule's segment (centre p2,
700
+ // unit axis, half length hl; a = p2 - hl axis, ab = 2 hl axis) to the sphere's centre p1, t = clamp(raw, 0, 1),
701
+ // raw = ap . ab / gam with ap = p1 - a and MuJoCo Warp's regularizer gam = ab . ab + 1e-6; returns raw
702
+ __device__ __forceinline__ float segment_point(const float* p1, const float* p2, const float* axis, float hl, float* a,
703
+ float* ab, float* ap, float* gam, float* t, float* pt) {
704
+ for (int k = 0; k < 3; k++) {
705
+ a[k] = RFMS(axis[k], hl, p2[k]); ab[k] = RMUL(RMUL(2.f, axis[k]), hl); ap[k] = RSUB(p1[k], a[k]);
706
+ }
707
+ *gam = RADD(dot3_rn(ab, ab), 1e-6f);
708
+ float raw = dot3_rn(ap, ab) / *gam;
709
+ *t = fminf(fmaxf(raw, 0.f), 1.f);
710
+ for (int k = 0; k < 3; k++) pt[k] = RFMA(*t, ab[k], a[k]);
711
+ return raw;
712
+ }
713
+
714
+ // capsule-capsule (MuJoCo Warp's capsule_capsule): the segments p_k + x_k a_k, x_k in [-1, 1], with the scaled axes
715
+ // a_k = hl_k R_k e_z, dif = p1 - p2, the normal equations [ma mb; mb mc] x = (u, v) and det = ma mc - mb^2
716
+ struct CapCap { float a1[3], a2[3], dif[3], ma, mb, mc, u, v, det; };
717
+ __device__ __forceinline__ void capcap_setup(const float* p1, const float* q1, float hl1, const float* p2,
718
+ const float* q2, float hl2, CapCap& c) {
719
+ zaxis_rn(q1, c.a1);
720
+ zaxis_rn(q2, c.a2);
721
+ for (int k = 0; k < 3; k++) { c.a1[k] = RMUL(c.a1[k], hl1); c.a2[k] = RMUL(c.a2[k], hl2); c.dif[k] = RSUB(p1[k], p2[k]); }
722
+ c.ma = dot3_rn(c.a1, c.a1); c.mb = -dot3_rn(c.a1, c.a2); c.mc = dot3_rn(c.a2, c.a2);
723
+ c.u = -dot3_rn(c.a1, c.dif); c.v = dot3_rn(c.a2, c.dif);
724
+ c.det = RFMA(c.ma, c.mc, -RMUL(c.mb, c.mb));
725
+ }
726
+ // the segment parameters where |det| >= 1e-15: the unconstrained minimum, then the clamp cascade. f1, f2: x1 / x2 free
727
+ // (not fixed at +-1; wp.clamp's gradient rule lo <= raw < hi for the clamp of x1 in the cascade's second stage), raw:
728
+ // x1 before that clamp (0 if it did not happen)
729
+ __device__ __forceinline__ void capcap_params(const CapCap& c, float* x1o, float* x2o, bool* f1, bool* f2, float* raw) {
730
+ float x1 = RFMA(c.mc, c.u, -RMUL(c.mb, c.v)) / c.det, x2 = RFMA(c.ma, c.v, -RMUL(c.mb, c.u)) / c.det;
731
+ *f1 = *f2 = true;
732
+ *raw = 0.f;
733
+ if (x1 > 1.f) { x1 = 1.f; x2 = RSUB(c.v, c.mb) / c.mc; *f1 = false; }
734
+ else if (x1 < -1.f) { x1 = -1.f; x2 = RADD(c.v, c.mb) / c.mc; *f1 = false; }
735
+ if (x2 > 1.f || x2 < -1.f) {
736
+ bool hi = x2 > 1.f;
737
+ x2 = hi ? 1.f : -1.f;
738
+ *raw = hi ? RSUB(c.u, c.mb) / c.ma : RADD(c.u, c.mb) / c.ma;
739
+ x1 = fminf(fmaxf(*raw, -1.f), 1.f);
740
+ *f1 = *raw >= -1.f && *raw < 1.f;
741
+ *f2 = false;
742
+ }
743
+ *x1o = x1; *x2o = x2;
744
+ }
745
+ // candidate e = 0..3 of the parallel case (|det| < 1e-15): an end of one segment (e = 0, 1: x1 = +1, -1; 2, 3: x2 =
746
+ // +1, -1) and the other's clamped closest parameter (raw before its clamp); f1, f2 as capcap_params
747
+ __device__ __forceinline__ void capcap_candidate(const CapCap& c, int e, float* x1, float* x2, bool* f1, bool* f2,
748
+ float* raw) {
749
+ if (e < 2) {
750
+ *x1 = e == 0 ? 1.f : -1.f;
751
+ *raw = e == 0 ? RSUB(c.v, c.mb) / c.mc : RADD(c.v, c.mb) / c.mc;
752
+ *x2 = fminf(fmaxf(*raw, -1.f), 1.f);
753
+ *f1 = false;
754
+ *f2 = *raw >= -1.f && *raw < 1.f;
755
+ } else {
756
+ *x2 = e == 2 ? 1.f : -1.f;
757
+ *raw = e == 2 ? RSUB(c.u, c.mb) / c.ma : RADD(c.u, c.mb) / c.ma;
758
+ *x1 = fminf(fmaxf(*raw, -1.f), 1.f);
759
+ *f2 = false;
760
+ *f1 = *raw >= -1.f && *raw < 1.f;
761
+ }
762
+ }
763
+ // the sphere core on the closest points p_k + x_k a_k (radii r1, r2): returns nu, as sphere_sphere
764
+ __device__ __forceinline__ float capcap_core(const float* p1, const float* p2, const CapCap& c, float x1, float x2,
765
+ float r1, float r2, float* dist, float* pos, float* n) {
766
+ float v1[3], v2[3];
767
+ for (int k = 0; k < 3; k++) { v1[k] = RFMA(c.a1[k], x1, p1[k]); v2[k] = RFMA(c.a2[k], x2, p2[k]); }
768
+ return sphere_sphere(v1, r1, v2, r2, dist, pos, n);
769
+ }
770
+
771
+ // 3x3 helpers (row-major float[9]) for the box collisions, MuJoCo Warp's quat_to_mat convention
772
+ __device__ __forceinline__ void quat2mat(const float* q, float* R) {
773
+ float q00 = q[0] * q[0], q01 = q[0] * q[1], q02 = q[0] * q[2], q03 = q[0] * q[3], q11 = q[1] * q[1];
774
+ float q12 = q[1] * q[2], q13 = q[1] * q[3], q22 = q[2] * q[2], q23 = q[2] * q[3], q33 = q[3] * q[3];
775
+ R[0] = q00 + q11 - q22 - q33; R[1] = 2.f * (q12 - q03); R[2] = 2.f * (q13 + q02);
776
+ R[3] = 2.f * (q12 + q03); R[4] = q00 - q11 + q22 - q33; R[5] = 2.f * (q23 - q01);
777
+ R[6] = 2.f * (q13 - q02); R[7] = 2.f * (q23 + q01); R[8] = q00 - q11 - q22 + q33;
778
+ }
779
+ __device__ __forceinline__ void mv3(const float* A, const float* v, float* o) {
780
+ for (int i = 0; i < 3; i++) o[i] = A[3 * i] * v[0] + A[3 * i + 1] * v[1] + A[3 * i + 2] * v[2];
781
+ }
782
+ __device__ __forceinline__ void mtv3(const float* A, const float* v, float* o) {
783
+ for (int i = 0; i < 3; i++) o[i] = A[i] * v[0] + A[3 + i] * v[1] + A[6 + i] * v[2];
784
+ }
785
+ __device__ __forceinline__ void mm3(const float* A, const float* B, float* C) { // C = A B
786
+ for (int i = 0; i < 3; i++)
787
+ for (int j = 0; j < 3; j++) C[3 * i + j] = A[3 * i] * B[j] + A[3 * i + 1] * B[3 + j] + A[3 * i + 2] * B[6 + j];
788
+ }
789
+ __device__ __forceinline__ void mmt3(const float* A, const float* B, float* C) { // C = A B'
790
+ for (int i = 0; i < 3; i++)
791
+ for (int j = 0; j < 3; j++) C[3 * i + j] = A[3 * i] * B[3 * j] + A[3 * i + 1] * B[3 * j + 1] + A[3 * i + 2] * B[3 * j + 2];
792
+ }
793
+ __device__ __forceinline__ float safe_div(float x, float y) { return x / (y != 0.f ? y : 1e-15f); }
794
+
795
+ // sphere-box (MuJoCo Warp's sphere_box): distance, position, normal (from the sphere towards the box)
796
+ __device__ void sphere_box(const float* sp, float r, const float* bp, const float* R, const float* bs, float* dist,
797
+ float* pos, float* n) {
798
+ float d[3] = {sp[0] - bp[0], sp[1] - bp[1], sp[2] - bp[2]}, c[3], cl[3], dir[3], pl[3], nl[3] = {0.f, 0.f, 0.f};
799
+ mtv3(R, d, c);
800
+ for (int k = 0; k < 3; k++) { cl[k] = fmaxf(-bs[k], fminf(bs[k], c[k])); dir[k] = cl[k] - c[k]; }
801
+ float dd = sqrtf(dot3(dir, dir));
802
+ if (dd <= 1e-15f) {
803
+ float closest = 2.f * (bs[0] + bs[1] + bs[2]);
804
+ int kk = 0;
805
+ for (int i = 0; i < 6; i++) {
806
+ float fd = fabsf(((i % 2) ? 1.f : -1.f) * bs[i / 2] - c[i / 2]);
807
+ if (closest > fd) { closest = fd; kk = i; }
808
+ }
809
+ nl[kk / 2] = (kk % 2) ? -1.f : 1.f;
810
+ for (int k = 0; k < 3; k++) pl[k] = c[k] + nl[k] * (r - closest) / 2.f;
811
+ *dist = -closest - r;
812
+ } else {
813
+ for (int k = 0; k < 3; k++) { nl[k] = dir[k] / dd; pl[k] = 0.5f * (cl[k] + c[k] + nl[k] * r); }
814
+ *dist = dd - r;
815
+ }
816
+ mv3(R, nl, n);
817
+ float t[3];
818
+ mv3(R, pl, t);
819
+ for (int k = 0; k < 3; k++) pos[k] = bp[k] + t[k];
820
+ }
821
+
822
+ // capsule-box (MuJoCo Warp's capsule_box_witness + capsule_box): up to two sphere-box contacts along the segment
823
+ template <class S>
824
+ __device__ void capsule_box(S& s, int pair, const float* cp, const float* axisw, float cr, float hl, const float* bp,
825
+ const float* R, const float* bs) {
826
+ float d[3] = {cp[0] - bp[0], cp[1] - bp[1], cp[2] - bp[2]}, pos[3], axis[3], ha[3];
827
+ mtv3(R, d, pos);
828
+ mtv3(R, axisw, axis);
829
+ for (int k = 0; k < 3; k++) ha[k] = axis[k] * hl;
830
+ int axisdir = int(ha[0] > 0.f) + 2 * int(ha[1] > 0.f) + 4 * int(ha[2] > 0.f);
831
+ float bestdist = 1e32f, bestseg = -12.f, bestbox = 0.f;
832
+ int cltype = -4, clface = -12, clcorner = -123, cledge = -123;
833
+ for (int i = -1; i < 2; i += 2) { // a capsule end closest to a face
834
+ float tip[3], bpnt[3];
835
+ int nout = 0, axout = -1;
836
+ for (int j = 0; j < 3; j++) {
837
+ tip[j] = pos[j] + float(i) * ha[j];
838
+ bpnt[j] = tip[j];
839
+ if (bpnt[j] < -bs[j]) { nout++; axout = j; bpnt[j] = -bs[j]; }
840
+ else if (bpnt[j] > bs[j]) { nout++; axout = j; bpnt[j] = bs[j]; }
841
+ }
842
+ if (nout > 1) continue;
843
+ float dist = 0.f;
844
+ for (int j = 0; j < 3; j++) dist += (bpnt[j] - tip[j]) * (bpnt[j] - tip[j]);
845
+ if (dist < bestdist) { bestdist = dist; bestseg = float(i); cltype = -2 + i; clface = axout; }
846
+ }
847
+ for (int i = 0; i < 8; i++) // a box edge closest
848
+ for (int j = 0; j < 3; j++) {
849
+ if (i & (1 << j)) continue;
850
+ float bpt[3] = {((i & 1) ? 1.f : -1.f) * bs[0], ((i & 2) ? 1.f : -1.f) * bs[1], ((i & 4) ? 1.f : -1.f) * bs[2]};
851
+ bpt[j] = 0.f;
852
+ float dif[3] = {bpt[0] - pos[0], bpt[1] - pos[1], bpt[2] - pos[2]};
853
+ float u = -bs[j] * dif[j], v = dot3(ha, dif), ma = bs[j] * bs[j], mb = -bs[j] * ha[j], mc = hl * hl;
854
+ float det = ma * mc - mb * mb;
855
+ if (fabsf(det) < 1e-15f) continue;
856
+ float idet = 1.f / det, x1 = (mc * u - mb * v) * idet, x2 = (ma * v - mb * u) * idet;
857
+ int s1 = 1, s2 = 1;
858
+ if (x1 > 1.f) { x1 = 1.f; s1 = 2; x2 = safe_div(v - mb, mc); }
859
+ else if (x1 < -1.f) { x1 = -1.f; s1 = 0; x2 = safe_div(v + mb, mc); }
860
+ bool over = x2 > 1.f;
861
+ if (over || x2 < -1.f) {
862
+ if (over) { x2 = 1.f; s2 = 2; x1 = safe_div(u - mb, ma); }
863
+ else { x2 = -1.f; s2 = 0; x1 = safe_div(u + mb, ma); }
864
+ if (x1 > 1.f) { x1 = 1.f; s1 = 2; } else if (x1 < -1.f) { x1 = -1.f; s1 = 0; }
865
+ }
866
+ for (int k = 0; k < 3; k++) dif[k] -= ha[k] * x2;
867
+ dif[j] += bs[j] * x1;
868
+ int ct = s1 * 3 + s2;
869
+ float dsq = dot3(dif, dif);
870
+ if (dsq < bestdist - 1e-15f) {
871
+ bestdist = dsq; bestseg = x2; bestbox = x1;
872
+ clcorner = i + (1 << j) * (ct / 6); cledge = j; cltype = ct;
873
+ }
874
+ }
875
+ if (cltype == -4) return;
876
+ float second = -4.f;
877
+ if (cltype >= 0 && cltype / 3 != 1) { // closest to a box corner
878
+ int c1 = axisdir ^ clcorner;
879
+ if (c1 != 0 && c1 != 7) {
880
+ int mul, ax = 0, ax1 = 1, ax2 = 2;
881
+ if (c1 == 1 || c1 == 2 || c1 == 4) mul = 1; else { mul = -1; c1 = 7 - c1; }
882
+ if (c1 == 1) { ax = 0; ax1 = 1; ax2 = 2; } else if (c1 == 2) { ax = 1; ax1 = 2; ax2 = 0; }
883
+ else if (c1 == 4) { ax = 2; ax1 = 0; ax2 = 1; }
884
+ if (axis[ax] * axis[ax] > 0.5f) {
885
+ float m = 2.f * safe_div(bs[ax], fabsf(ha[ax]));
886
+ second = fminf(1.f - float(mul) * bestseg, m);
887
+ } else {
888
+ float m = 2.f * fminf(safe_div(bs[ax1], fabsf(ha[ax1])), safe_div(bs[ax2], fabsf(ha[ax2])));
889
+ second = -fminf(1.f + float(mul) * bestseg, m);
890
+ }
891
+ second *= float(mul);
892
+ }
893
+ } else if (cltype >= 0 && cltype / 3 == 1) { // on a box edge
894
+ int c1 = (axisdir ^ clcorner) & (7 - (1 << cledge));
895
+ if (c1 == 1 || c1 == 2 || c1 == 4) {
896
+ int ax1 = 1, ax2 = 2, ax = cledge, mul;
897
+ if (cledge == 0) { ax1 = 1; ax2 = 2; }
898
+ if (cledge == 1) { ax1 = 2; ax2 = 0; }
899
+ if (cledge == 2) { ax1 = 0; ax2 = 1; }
900
+ if (fabsf(axis[ax1]) > fabsf(axis[ax2])) ax1 = ax2;
901
+ ax2 = 3 - ax - ax1;
902
+ if (c1 & (1 << ax2)) { mul = 1; second = 1.f - bestseg; } else { mul = -1; second = 1.f + bestseg; }
903
+ float e1 = 2.f * safe_div(bs[ax2], fabsf(ha[ax2]));
904
+ second = fminf(e1, second);
905
+ float e2 = (((axisdir & (1 << ax)) != 0) == ((c1 & (1 << ax2)) != 0)) ? 1.f - bestbox : 1.f + bestbox;
906
+ e1 = bs[ax] * safe_div(e2, fabsf(ha[ax]));
907
+ second = fminf(e1, second);
908
+ second *= float(mul);
909
+ }
910
+ } else if (clface != -1) { // a capsule end closest to a face
911
+ int mul = cltype == -3 ? 1 : -1;
912
+ second = 2.f;
913
+ float t1[3];
914
+ for (int k = 0; k < 3; k++) t1[k] = pos[k] - ha[k] * float(mul);
915
+ for (int i = 0; i < 3; i++) {
916
+ if (i == clface) continue;
917
+ float har = safe_div(float(mul), ha[i]);
918
+ float e1 = (bs[i] - t1[i]) * har;
919
+ if (0.f < e1 && e1 < second) second = e1;
920
+ e1 = (-bs[i] - t1[i]) * har;
921
+ if (0.f < e1 && e1 < second) second = e1;
922
+ }
923
+ second *= float(mul);
924
+ }
925
+ for (int e = 0; e < 2; e++) {
926
+ if (e == 1 && !(second > -3.f)) break;
927
+ float seg = e == 0 ? bestseg : bestseg + second, ce[3], dist, pc[3], n[3], fr[9];
928
+ for (int k = 0; k < 3; k++) ce[k] = bp[k];
929
+ float lc[3], t[3];
930
+ for (int k = 0; k < 3; k++) lc[k] = pos[k] + ha[k] * seg;
931
+ mv3(R, lc, t);
932
+ for (int k = 0; k < 3; k++) ce[k] += t[k];
933
+ sphere_box(ce, cr, bp, R, bs, &dist, pc, n);
934
+ if (dist < 0.f) { make_frame(n, fr); add_contact(s, pair, e, dist, pc, fr); }
935
+ }
936
+ }
937
+
938
+ __device__ __forceinline__ void rotmore_of(int f, float* r) {
939
+ for (int k = 0; k < 9; k++) r[k] = 0.f;
940
+ if (f == 0) { r[2] = -1.f; r[4] = 1.f; r[6] = 1.f; }
941
+ else if (f == 1) { r[0] = 1.f; r[5] = -1.f; r[7] = 1.f; }
942
+ else if (f == 2) { r[0] = 1.f; r[4] = 1.f; r[8] = 1.f; }
943
+ else if (f == 3) { r[2] = 1.f; r[4] = 1.f; r[6] = -1.f; }
944
+ else if (f == 4) { r[0] = 1.f; r[5] = 1.f; r[7] = -1.f; }
945
+ else if (f == 5) { r[0] = -1.f; r[4] = 1.f; r[8] = -1.f; }
946
+ }
947
+
948
+ // box-box (MuJoCo Warp's box_box, margin 0): separating-axis test, then face-vertex or edge-edge clipping
949
+ #define BB_MAXPT 24
950
+ #ifndef BOX_BOX_CCD
951
+ #define BOX_BOX_CCD 1 // 1: MuJoCo Warp default (native CCD); 0: the separating-axis primitive (NATIVECCD disabled)
952
+ #endif
953
+ template <class S>
954
+ __device__ void box_box(S& s, int pair, const float* p1, const float* R1, const float* s1, const float* p2,
955
+ const float* R2, const float* s2) {
956
+ const float margin = 0.f;
957
+ float d[3] = {p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2]}, dn[3] = {-d[0], -d[1], -d[2]}, pos21[3], pos12[3];
958
+ mtv3(R1, d, pos21);
959
+ mtv3(R2, dn, pos12);
960
+ float rot21[9], rot12[9], a21[9], a12[9], plen2[3], plen1[3];
961
+ for (int i = 0; i < 3; i++)
962
+ for (int j = 0; j < 3; j++) rot21[3 * i + j] = R1[i] * R2[j] + R1[3 + i] * R2[3 + j] + R1[6 + i] * R2[6 + j];
963
+ for (int i = 0; i < 3; i++)
964
+ for (int j = 0; j < 3; j++) { rot12[3 * i + j] = rot21[3 * j + i]; a21[3 * i + j] = fabsf(rot21[3 * i + j]); }
965
+ for (int i = 0; i < 3; i++)
966
+ for (int j = 0; j < 3; j++) a12[3 * i + j] = a21[3 * j + i];
967
+ mv3(a21, s2, plen2);
968
+ mv3(a12, s1, plen1);
969
+ float sep = margin + 3.f * (s1[0] + s2[0]) + 3.f * (s1[1] + s2[1]) + 3.f * (s1[2] + s2[2]);
970
+ int code = -1;
971
+ for (int i = 0; i < 3; i++) {
972
+ float c1 = -fabsf(pos21[i]) + s1[i] + plen2[i], c2 = -fabsf(pos12[i]) + s2[i] + plen1[i];
973
+ if (c1 < -margin || c2 < -margin) return;
974
+ if (c1 < sep) { sep = c1; code = i + 3 * int(pos21[i] < 0.f); }
975
+ if (c2 < sep) { sep = c2; code = i + 3 * int(pos12[i] < 0.f) + 6; }
976
+ }
977
+ float clnorm[3] = {0.f, 0.f, 0.f};
978
+ bool inv = false;
979
+ int cle1 = 0, cle2 = 0;
980
+ for (int i = 0; i < 3; i++)
981
+ for (int j = 0; j < 3; j++) {
982
+ float ca[3];
983
+ if (i == 0) { ca[0] = 0.f; ca[1] = -rot12[3 * j + 2]; ca[2] = rot12[3 * j + 1]; }
984
+ else if (i == 1) { ca[0] = rot12[3 * j + 2]; ca[1] = 0.f; ca[2] = -rot12[3 * j]; }
985
+ else { ca[0] = -rot12[3 * j + 1]; ca[1] = rot12[3 * j]; ca[2] = 0.f; }
986
+ float cl = sqrtf(dot3(ca, ca));
987
+ if (cl < 1e-15f) continue;
988
+ for (int k = 0; k < 3; k++) ca[k] /= cl;
989
+ float bd = dot3(pos21, ca), c3 = 0.f;
990
+ for (int k = 0; k < 3; k++) {
991
+ if (k != i) c3 += s1[k] * fabsf(ca[k]);
992
+ if (k != j) c3 += s2[k] * a21[3 * i + 3 - k - j] / cl;
993
+ }
994
+ c3 -= fabsf(bd);
995
+ if (c3 < -margin) return;
996
+ if (c3 < sep * (1.f - 1e-12f)) {
997
+ sep = c3; cle1 = 0; cle2 = 0;
998
+ for (int k = 0; k < 3; k++) {
999
+ if (k != i && (int(ca[k] > 0.f) ^ int(bd < 0.f))) cle1 += 1 << k;
1000
+ if (k != j && (int(rot21[3 * i + 3 - k - j] > 0.f) ^ int(bd < 0.f) ^ int((k - j + 3) % 3 == 1))) cle2 += 1 << k;
1001
+ }
1002
+ code = 12 + i * 3 + j;
1003
+ for (int k = 0; k < 3; k++) clnorm[k] = ca[k];
1004
+ inv = bd < 0.f;
1005
+ }
1006
+ }
1007
+ if (code == -1) return;
1008
+ float pts[BB_MAXPT][3], depth[BB_MAXPT], rw[9], pw[3], nrm[3], hz;
1009
+ int n = 0;
1010
+ if (code < 12) { // face-vertex
1011
+ int face = code % 6, bi = code / 6;
1012
+ float rm[9], r[9], p[3], ss[3], sv[3], t[3];
1013
+ rotmore_of(face, rm);
1014
+ mm3(rm, bi ? rot12 : rot21, r);
1015
+ mv3(rm, bi ? pos12 : pos21, p);
1016
+ mv3(rm, bi ? s2 : s1, t);
1017
+ for (int k = 0; k < 3; k++) { ss[k] = fabsf(t[k]); sv[k] = bi ? s1[k] : s2[k]; }
1018
+ float lx = ss[0], ly = ss[1];
1019
+ hz = ss[2];
1020
+ p[2] -= hz;
1021
+ int clc = 0;
1022
+ for (int i = 0; i < 3; i++) if (r[6 + i] < 0.f) clc += 1 << i;
1023
+ float lp[3] = {p[0], p[1], p[2]};
1024
+ for (int i = 0; i < 3; i++)
1025
+ for (int k = 0; k < 3; k++) lp[k] += r[3 * k + i] * sv[i] * ((clc & (1 << i)) ? 1.f : -1.f);
1026
+ int dirs = 0;
1027
+ float cn1[3] = {0.f, 0.f, 0.f}, cn2[3] = {0.f, 0.f, 0.f};
1028
+ for (int i = 0; i < 3; i++)
1029
+ if (fabsf(r[6 + i]) < 0.5f) {
1030
+ float* cn = dirs ? cn2 : cn1;
1031
+ for (int k = 0; k < 3; k++) cn[k] = r[3 * k + i] * sv[i] * ((clc & (1 << i)) ? -2.f : 2.f);
1032
+ dirs++;
1033
+ }
1034
+ for (int i = 0; i < dirs * dirs; i++)
1035
+ for (int q = 0; q < 2; q++) {
1036
+ float la[3], lb[3];
1037
+ for (int k = 0; k < 3; k++) {
1038
+ la[k] = lp[k] + (i < 2 ? 0.f : (i == 2 ? cn1[k] : cn2[k]));
1039
+ lb[k] = (i == 0 || i == 3) ? cn1[k] : cn2[k];
1040
+ }
1041
+ if (fabsf(lb[q]) > 1e-15f) {
1042
+ float br = 1.f / lb[q];
1043
+ for (int j = -1; j < 2; j += 2) {
1044
+ float l = ss[q] * float(j), c1 = (l - la[q]) * br;
1045
+ if (c1 < 0.f || c1 > 1.f) continue;
1046
+ float c2 = la[1 - q] + lb[1 - q] * c1;
1047
+ if (fabsf(c2) > ss[1 - q]) continue;
1048
+ if (n < BB_MAXPT) { for (int k = 0; k < 3; k++) pts[n][k] = la[k] + c1 * lb[k]; }
1049
+ n++;
1050
+ }
1051
+ }
1052
+ }
1053
+ if (dirs == 2) {
1054
+ float ax = cn1[0], bx = cn2[0], ay = cn1[1], by = cn2[1], C = safe_div(1.f, ax * by - bx * ay);
1055
+ for (int i = 0; i < 4; i++) {
1056
+ float llx = (i / 2) ? lx : -lx, lly = (i % 2) ? ly : -ly, x = llx - lp[0], y = lly - lp[1];
1057
+ float u = (x * by - y * bx) * C, v = (y * ax - x * ay) * C;
1058
+ if (u > 0.f && v > 0.f && u < 1.f && v < 1.f) {
1059
+ if (n < BB_MAXPT) { pts[n][0] = llx; pts[n][1] = lly; pts[n][2] = lp[2] + u * cn1[2] + v * cn2[2]; }
1060
+ n++;
1061
+ }
1062
+ }
1063
+ }
1064
+ for (int i = 0; i < (1 << dirs); i++) {
1065
+ float tv[3];
1066
+ for (int k = 0; k < 3; k++) tv[k] = lp[k] + float(i & 1) * cn1[k] + float((i & 2) != 0) * cn2[k];
1067
+ if (tv[0] > -lx && tv[0] < lx && tv[1] > -ly && tv[1] < ly) {
1068
+ if (n < BB_MAXPT) { for (int k = 0; k < 3; k++) pts[n][k] = tv[k]; }
1069
+ n++;
1070
+ }
1071
+ }
1072
+ if (n > BB_MAXPT) atomicOr(&s.unsupported, 2);
1073
+ int m = min(n, BB_MAXPT);
1074
+ n = 0;
1075
+ for (int i = 0; i < m; i++) {
1076
+ if (pts[i][2] > margin) continue;
1077
+ for (int k = 0; k < 3; k++) pts[n][k] = pts[i][k];
1078
+ depth[n] = pts[n][2];
1079
+ pts[n][2] *= 0.5f;
1080
+ n++;
1081
+ }
1082
+ mmt3(bi ? R2 : R1, rm, rw);
1083
+ for (int k = 0; k < 3; k++) { pw[k] = bi ? p2[k] : p1[k]; nrm[k] = (bi ? -1.f : 1.f) * rw[3 * k + 2]; }
1084
+ } else { // edge-edge
1085
+ int e1 = (code - 12) / 3, e2 = (code - 12) % 3;
1086
+ int ax1 = 1 - (e2 & 1), ax2 = 2 - (e2 & 2), pax1 = 1 - (e1 & 1), pax2 = 2 - (e1 & 2);
1087
+ if (a21[3 * e1 + ax1] < a21[3 * e1 + ax2]) { int t = ax1; ax1 = ax2; ax2 = t; }
1088
+ if (a12[3 * e2 + pax1] < a12[3 * e2 + pax2]) { int t = pax1; pax1 = pax2; pax2 = t; }
1089
+ float rm[9], p[3], rn[3], r[9], sv[3], t[3];
1090
+ rotmore_of((cle1 & (1 << pax2)) ? pax2 : pax2 + 3, rm);
1091
+ mv3(rm, pos21, p);
1092
+ mv3(rm, clnorm, rn);
1093
+ mm3(rm, rot21, r);
1094
+ mtv3(rm, s1, t);
1095
+ for (int k = 0; k < 3; k++) sv[k] = fabsf(t[k]);
1096
+ float lx = sv[0], ly = sv[1];
1097
+ hz = sv[2];
1098
+ p[2] -= hz;
1099
+ float pu[4][3];
1100
+ float g1 = (cle2 & (1 << ax1)) ? 1.f : -1.f, g2 = (cle2 & (1 << ax2)) ? 1.f : -1.f;
1101
+ for (int k = 0; k < 3; k++) {
1102
+ float b0 = p[k] + r[3 * k + ax1] * s2[ax1] * g1 + r[3 * k + ax2] * s2[ax2] * g2;
1103
+ float b2 = p[k] - r[3 * k + ax1] * s2[ax1] * g1 + r[3 * k + ax2] * s2[ax2] * g2;
1104
+ float de = r[3 * k + e2] * s2[e2];
1105
+ pu[0][k] = b0 + de; pu[1][k] = b0 - de; pu[2][k] = b2 + de; pu[3][k] = b2 - de;
1106
+ }
1107
+ float alp[3], acn1[3], acn2[3];
1108
+ for (int k = 0; k < 3; k++) { alp[k] = pu[0][k]; acn1[k] = pu[1][k] - pu[0][k]; acn2[k] = pu[2][k] - pu[0][k]; }
1109
+ if (fabsf(rn[2]) < 1e-15f) return;
1110
+ float sg = inv ? -1.f : 1.f, innorm = sg / rn[2], pp[4][3];
1111
+ for (int i = 0; i < 4; i++) {
1112
+ float cs = pu[i][2] * sg * innorm;
1113
+ for (int k = 0; k < 3; k++) pp[i][k] = pu[i][k] - rn[k] * cs;
1114
+ }
1115
+ float plp[3], pcn1[3], pcn2[3];
1116
+ for (int k = 0; k < 3; k++) { plp[k] = pp[0][k]; pcn1[k] = pp[1][k] - pp[0][k]; pcn2[k] = pp[2][k] - pp[0][k]; }
1117
+ for (int i = 0; i < 4; i++)
1118
+ for (int q = 0; q < 2; q++) {
1119
+ float la = plp[q] + (i < 2 ? 0.f : (i == 2 ? pcn1[q] : pcn2[q]));
1120
+ float lb = (i == 0 || i == 3) ? pcn1[q] : pcn2[q];
1121
+ float lc = plp[1 - q] + (i < 2 ? 0.f : (i == 2 ? pcn1[1 - q] : pcn2[1 - q]));
1122
+ float ld = (i == 0 || i == 3) ? pcn1[1 - q] : pcn2[1 - q];
1123
+ float lua[3], lub[3];
1124
+ for (int k = 0; k < 3; k++) {
1125
+ lua[k] = alp[k] + (i < 2 ? 0.f : (i == 2 ? acn1[k] : acn2[k]));
1126
+ lub[k] = (i == 0 || i == 3) ? acn1[k] : acn2[k];
1127
+ }
1128
+ if (fabsf(lb) > 1e-15f) {
1129
+ float br = 1.f / lb;
1130
+ for (int j = -1; j < 2; j += 2) {
1131
+ if (n == 8) break;
1132
+ float l = sv[q] * float(j), c1 = (l - la) * br;
1133
+ if (c1 < 0.f || c1 > 1.f) continue;
1134
+ float c2 = lc + ld * c1;
1135
+ if (fabsf(c2) > sv[1 - q]) continue;
1136
+ if ((lua[2] + lub[2] * c1) * innorm > margin) continue;
1137
+ for (int k = 0; k < 3; k++) pts[n][k] = lua[k] * 0.5f + c1 * lub[k] * 0.5f;
1138
+ pts[n][q] += 0.5f * l;
1139
+ pts[n][1 - q] += 0.5f * c2;
1140
+ depth[n] = pts[n][2] * innorm * 2.f;
1141
+ n++;
1142
+ }
1143
+ }
1144
+ }
1145
+ int nl = n;
1146
+ float ax = pcn1[0], bx = pcn2[0], ay = pcn1[1], by = pcn2[1], C = safe_div(1.f, ax * by - bx * ay);
1147
+ for (int i = 0; i < 4; i++) {
1148
+ if (n == 8) break;
1149
+ float llx = (i / 2) ? lx : -lx, lly = (i % 2) ? ly : -ly, x = llx - plp[0], y = lly - plp[1];
1150
+ float u = (x * by - y * bx) * C, v = (y * ax - x * ay) * C;
1151
+ if (nl == 0) { if ((u < 0.f || u > 1.f) && (v < 0.f || v > 1.f)) continue; }
1152
+ else if (u < 0.f || v < 0.f || u > 1.f || v > 1.f) continue;
1153
+ u = fminf(fmaxf(u, 0.f), 1.f);
1154
+ v = fminf(fmaxf(v, 0.f), 1.f);
1155
+ float w = 1.f - u - v, vt[3], q2[3] = {llx, lly, 0.f};
1156
+ for (int k = 0; k < 3; k++) vt[k] = pu[0][k] * w + pu[1][k] * u + pu[2][k] * v;
1157
+ float tc1 = 0.f;
1158
+ for (int k = 0; k < 3; k++) tc1 += (q2[k] - vt[k]) * (q2[k] - vt[k]);
1159
+ if (vt[2] > 0.f && tc1 > margin * margin) continue;
1160
+ for (int k = 0; k < 3; k++) pts[n][k] = 0.5f * (q2[k] + vt[k]);
1161
+ depth[n] = sqrtf(tc1) * (vt[2] < 0.f ? -1.f : 1.f);
1162
+ n++;
1163
+ }
1164
+ int nf = n;
1165
+ for (int i = 0; i < 4; i++) {
1166
+ if (n >= 8) break;
1167
+ float x = pu[i][0], y = pu[i][1];
1168
+ if (nl == 0 && nf != 0) { if ((x < -lx || x > lx) && (y < -ly || y > ly)) continue; }
1169
+ else if (x < -lx || x > lx || y < -ly || y > ly) continue;
1170
+ float c1 = 0.f;
1171
+ for (int j = 0; j < 2; j++) {
1172
+ if (pu[i][j] < -sv[j]) c1 += (pu[i][j] + sv[j]) * (pu[i][j] + sv[j]);
1173
+ else if (pu[i][j] > sv[j]) c1 += (pu[i][j] - sv[j]) * (pu[i][j] - sv[j]);
1174
+ }
1175
+ c1 += pu[i][2] * innorm * pu[i][2] * innorm;
1176
+ if (pu[i][2] > 0.f && c1 > margin * margin) continue;
1177
+ float tp[3] = {pu[i][0], pu[i][1], 0.f};
1178
+ for (int j = 0; j < 2; j++) {
1179
+ if (pu[i][j] < -sv[j]) tp[j] = -sv[j] * 0.5f;
1180
+ else if (pu[i][j] > sv[j]) tp[j] = sv[j] * 0.5f;
1181
+ }
1182
+ for (int k = 0; k < 3; k++) pts[n][k] = (tp[k] + pu[i][k]) * 0.5f;
1183
+ depth[n] = sqrtf(c1) * (pu[i][2] < 0.f ? -1.f : 1.f);
1184
+ n++;
1185
+ }
1186
+ mmt3(R1, rm, rw);
1187
+ float t2[3];
1188
+ mv3(rw, rn, t2);
1189
+ for (int k = 0; k < 3; k++) { pw[k] = p1[k]; nrm[k] = sg * t2[k]; }
1190
+ }
1191
+ if (n > 8) { atomicOr(&s.unsupported, 2); n = 8; }
1192
+ float fr[9];
1193
+ make_frame(nrm, fr);
1194
+ #if BOX_BOX_CCD
1195
+ // MuJoCo Warp collides box-box with GJK/EPA (native CCD): one contact at the minimum-penetration axis, which is the
1196
+ // separating-axis result above, unless multiccd finds two faces within 0.0889 rad of facing each other or an edge
1197
+ // within that angle of lying on a face; those near-aligned cases are flagged (bit 8), not emulated
1198
+ const float ftol = 0.99605107f, etol = 0.08878297f; // cos(0.0889), sin(0.0889)
1199
+ bool multi = false;
1200
+ if (code < 12) { // face of one box against a vertex of the other: any axis of the vertex box near-perpendicular to n
1201
+ const float* Rv = (code / 6) ? R1 : R2;
1202
+ for (int k = 0; k < 3; k++) {
1203
+ float c = fabsf(Rv[k] * nrm[0] + Rv[3 + k] * nrm[1] + Rv[6 + k] * nrm[2]);
1204
+ if (c > ftol || c < etol) multi = true;
1205
+ }
1206
+ int best = -1;
1207
+ for (int i = 0; i < n; i++) if (depth[i] < 0.f && (best < 0 || depth[i] < depth[best])) best = i;
1208
+ if (multi) atomicOr(&s.unsupported, 8);
1209
+ if (best < 0) return;
1210
+ float pl[3] = {pts[best][0], pts[best][1], pts[best][2] + hz}, pc[3];
1211
+ mv3(rw, pl, pc);
1212
+ for (int k = 0; k < 3; k++) pc[k] += pw[k];
1213
+ add_contact(s, pair, 0, depth[best], pc, fr);
1214
+ } else { // edge-edge: the midpoint of the two edges' closest points
1215
+ int e1 = (code - 12) / 3, e2 = (code - 12) % 3;
1216
+ for (int a = 0; a < 3; a++)
1217
+ for (int b = 0; b < 3; b++) {
1218
+ float c = fabsf(R1[a] * R2[b] + R1[3 + a] * R2[3 + b] + R1[6 + a] * R2[6 + b]);
1219
+ if (a != e1 && b != e2 && c > ftol) multi = true; // adjacent faces facing each other
1220
+ if (a == e1 && b != e2 && c < etol) multi = true; // edge 1 lying on a face of box 2
1221
+ if (b == e2 && a != e1 && c < etol) multi = true; // edge 2 lying on a face of box 1
1222
+ }
1223
+ if (multi) atomicOr(&s.unsupported, 8);
1224
+ float l1[3], l2[3], c1[3], c2[3], d1[3], d2[3];
1225
+ for (int k = 0; k < 3; k++) {
1226
+ l1[k] = k == e1 ? 0.f : ((cle1 & (1 << k)) ? s1[k] : -s1[k]);
1227
+ l2[k] = k == e2 ? 0.f : ((cle2 & (1 << k)) ? s2[k] : -s2[k]);
1228
+ }
1229
+ mv3(R1, l1, c1);
1230
+ mv3(R2, l2, c2);
1231
+ for (int k = 0; k < 3; k++) {
1232
+ c1[k] += p1[k]; c2[k] += p2[k];
1233
+ d1[k] = R1[3 * k + e1] * s1[e1]; d2[k] = R2[3 * k + e2] * s2[e2];
1234
+ }
1235
+ // closest points of the segments c1 + t1 d1, c2 + t2 d2 with t in [-1, 1]
1236
+ float r[3] = {c1[0] - c2[0], c1[1] - c2[1], c1[2] - c2[2]};
1237
+ float a11 = dot3(d1, d1), a12 = dot3(d1, d2), a22 = dot3(d2, d2), b1 = dot3(d1, r), b2 = dot3(d2, r);
1238
+ float det = a11 * a22 - a12 * a12, t1 = 0.f, t2 = 0.f;
1239
+ if (det > 1e-12f) t1 = fminf(fmaxf((a12 * b2 - a22 * b1) / det, -1.f), 1.f);
1240
+ t2 = fminf(fmaxf((b2 + a12 * t1) / a22, -1.f), 1.f);
1241
+ t1 = fminf(fmaxf((a12 * t2 - b1) / a11, -1.f), 1.f);
1242
+ float pc[3];
1243
+ for (int k = 0; k < 3; k++) pc[k] = 0.5f * (c1[k] + t1 * d1[k] + c2[k] + t2 * d2[k]);
1244
+ if (sep > 0.f) add_contact(s, pair, 0, -sep, pc, fr);
1245
+ }
1246
+ #else
1247
+ for (int i = 0; i < n; i++) {
1248
+ if (!(depth[i] < 0.f)) continue;
1249
+ float pl[3] = {pts[i][0], pts[i][1], pts[i][2] + hz}, pc[3];
1250
+ mv3(rw, pl, pc);
1251
+ for (int k = 0; k < 3; k++) pc[k] += pw[k];
1252
+ add_contact(s, pair, i, depth[i], pc, fr);
1253
+ }
1254
+ #endif
1255
+ }
1256
+
1257
+ template <class S>
1258
+ __device__ DK_INL_COLLIDE void collide_pair(S& s, int pair) {
1259
+ int g1 = PG1(pair), g2 = PG2(pair), t1 = c_gtype[g1], t2 = c_gtype[g2];
1260
+ float p1[3], q1[4], p2[3], q2[4];
1261
+ for (int k = 0; k < 3; k++) { p1[k] = s.gx[g1][k]; p2[k] = s.gx[g2][k]; }
1262
+ for (int k = 0; k < 4; k++) { q1[k] = s.gq[g1][k]; q2[k] = s.gq[g2][k]; }
1263
+ const float* sz1 = c_gsize + 3 * g1;
1264
+ const float* sz2 = c_gsize + 3 * g2;
1265
+ if (t1 == 0) { // plane (the floor): normal = its z axis
1266
+ float n[3];
1267
+ zaxis_rn(q1, n);
1268
+ float dif[3] = {RSUB(p2[0], p1[0]), RSUB(p2[1], p1[1]), RSUB(p2[2], p1[2])};
1269
+ if (dot3_rn(dif, n) > c_grbound[g2]) return; // the other geom's bounding sphere is above the plane
1270
+ if (t2 == 1) {
1271
+ float pos[3], fr[9];
1272
+ float dist = plane_point(p1, n, p2, sz2[0], pos);
1273
+ make_frame(n, fr);
1274
+ if (dist < 0.f) add_contact(s, pair, 0, dist, pos, fr);
1275
+ } else if (t2 == 2) {
1276
+ float axis[3], fr[9];
1277
+ zaxis_rn(q2, axis);
1278
+ plane_capsule_frame(n, axis, fr);
1279
+ for (int e = 0; e < 2; e++) {
1280
+ float ce[3], pos[3];
1281
+ capsule_end(p2, axis, sz2[1], e, ce);
1282
+ float dist = plane_point(p1, n, ce, sz2[0], pos);
1283
+ if (dist < 0.f) add_contact(s, pair, e, dist, pos, fr);
1284
+ }
1285
+ }
1286
+ #if HAS_BOX
1287
+ else if (t2 == 3) {
1288
+ float fr[9], cd = dot3(p2, n) - dot3(p1, n);
1289
+ make_frame(n, fr);
1290
+ for (int i = 0; i < 8; i++) {
1291
+ float cl[3] = {(i & 1) ? sz2[0] : -sz2[0], (i & 2) ? sz2[1] : -sz2[1], (i & 4) ? sz2[2] : -sz2[2]}, cw[3];
1292
+ qrot(q2, cl, cw);
1293
+ float dist = cd + dot3(n, cw), pos[3];
1294
+ for (int k = 0; k < 3; k++) pos[k] = cw[k] + p2[k] - 0.5f * n[k] * dist;
1295
+ if (dist < 0.f) add_contact(s, pair, i, dist, pos, fr);
1296
+ }
1297
+ }
1298
+ #endif
1299
+ return;
1300
+ }
1301
+ { // bounding spheres (geom_rbound) do not overlap: no contact at zero margin
1302
+ float dif[3] = {RSUB(p2[0], p1[0]), RSUB(p2[1], p1[1]), RSUB(p2[2], p1[2])}, rb = RADD(c_grbound[g1], c_grbound[g2]);
1303
+ if (dot3_rn(dif, dif) > RMUL(rb, rb)) return;
1304
+ }
1305
+ if (t1 == 1 && t2 == 1) { // sphere-sphere
1306
+ float dist, pos[3], n[3];
1307
+ float nu = sphere_sphere(p1, sz1[0], p2, sz2[0], &dist, pos, n);
1308
+ if (dist < 0.f) add_sphere_contact(s, pair, 0, nu, dist, pos, n);
1309
+ return;
1310
+ }
1311
+ if (t1 == 1 && t2 == 2) { // sphere-capsule (MuJoCo Warp's sphere_capsule: closest point of the segment)
1312
+ float axis[3], a[3], ab[3], ap[3], gam, t, pt[3], dist, pos[3], n[3];
1313
+ zaxis_rn(q2, axis);
1314
+ segment_point(p1, p2, axis, sz2[1], a, ab, ap, &gam, &t, pt);
1315
+ float nu = sphere_sphere(p1, sz1[0], pt, sz2[0], &dist, pos, n);
1316
+ if (dist < 0.f) add_sphere_contact(s, pair, 0, nu, dist, pos, n);
1317
+ return;
1318
+ }
1319
+ if (t1 == 2 && t2 == 2) { // capsule-capsule
1320
+ CapCap cc;
1321
+ capcap_setup(p1, q1, sz1[1], p2, q2, sz2[1], cc);
1322
+ float dist, pos[3], n[3], x1, x2, raw;
1323
+ bool f1, f2;
1324
+ if (fabsf(cc.det) >= 1e-15f) {
1325
+ capcap_params(cc, &x1, &x2, &f1, &f2, &raw);
1326
+ float nu = capcap_core(p1, p2, cc, x1, x2, sz1[0], sz2[0], &dist, pos, n);
1327
+ if (dist < 0.f) add_sphere_contact(s, pair, 0, nu, dist, pos, n);
1328
+ } else {
1329
+ int cnt = 0;
1330
+ for (int e = 0; e < 4 && cnt < 2; e++) {
1331
+ capcap_candidate(cc, e, &x1, &x2, &f1, &f2, &raw);
1332
+ float nu = capcap_core(p1, p2, cc, x1, x2, sz1[0], sz2[0], &dist, pos, n);
1333
+ if (dist <= 0.f) {
1334
+ cnt++;
1335
+ if (dist < 0.f) add_sphere_contact(s, pair, e, nu, dist, pos, n);
1336
+ }
1337
+ }
1338
+ }
1339
+ return;
1340
+ }
1341
+ #if HAS_BOX
1342
+ if (t1 == 2 && t2 == 3) { // capsule-box
1343
+ float a1[3], R2[9];
1344
+ zaxis_rn(q1, a1);
1345
+ quat2mat(q2, R2);
1346
+ capsule_box(s, pair, p1, a1, sz1[0], sz1[1], p2, R2, sz2);
1347
+ return;
1348
+ }
1349
+ if (t1 == 3 && t2 == 3) { // box-box
1350
+ float R1[9], R2[9];
1351
+ quat2mat(q1, R1);
1352
+ quat2mat(q2, R2);
1353
+ box_box(s, pair, p1, R1, sz1, p2, R2, sz2);
1354
+ return;
1355
+ }
1356
+ #endif
1357
+ atomicOr(&s.unsupported, 1); // other type combinations do not occur in the G1 model
1358
+ }
1359
+
1360
+ // x^p for the solimp power: the integer powers 1 and 2 (both G1 models use 2) without powf (x * x is the correctly
1361
+ // rounded square, powf(x, 2) is within 1 ulp of it)
1362
+ __device__ __forceinline__ float pow_imp(float x, float p) { return p == 2.f ? RMUL(x, x) : (p == 1.f ? x : powf(x, p)); }
1363
+
1364
+ // the impedance curve's raw (unclamped) value for 0 < x < 1 and a power p != 1, on the branch lo = (x <= mid): the
1365
+ // forward's kbimp and the adjoint's kbimp_d (its clamp test) compute the same bits
1366
+ __device__ __forceinline__ float imp_raw(float x, float dmin, float dmax, float mid, float p, bool lo) {
1367
+ return lo ? RFMA(pow_imp(x, p) / pow_imp(mid, p - 1.f), RSUB(dmax, dmin), dmin)
1368
+ : RFMA(RSUB(1.f, pow_imp(RSUB(1.f, x), p) / pow_imp(RSUB(1.f, mid), p - 1.f)), RSUB(dmax, dmin), dmin);
1369
+ }
1370
+
1371
+ // impedance (k, b, imp) at pos_imp with refsafe (timeconst >= 2 h); explicit roundings: the adjoint's kbimp_d calls it
1372
+ __device__ __forceinline__ void kbimp(const float* solref, const float* solimp, float pos_imp, float h, float* k,
1373
+ float* b, float* imp) {
1374
+ float tc = fmaxf(solref[0], RMUL(2.f, h)), dr = solref[1];
1375
+ float dmin = fminf(fmaxf(solimp[0], 1e-4f), 0.9999f), dmax = fminf(fmaxf(solimp[1], 1e-4f), 0.9999f);
1376
+ float width = fmaxf(1e-15f, solimp[2]), mid = fminf(fmaxf(solimp[3], 1e-4f), 0.9999f);
1377
+ const float power = SOLIMP_POW2 ? 2.f : fmaxf(1.f, solimp[4]); // a constant: pow_imp folds to x * x and mid
1378
+ *k = 1.f / fmaxf(1e-15f, RMUL(RMUL(RMUL(RMUL(RMUL(dmax, dmax), tc), tc), dr), dr));
1379
+ *b = 2.f / fmaxf(1e-15f, RMUL(dmax, tc));
1380
+ float x = fabsf(pos_imp) / width;
1381
+ if (dmin == dmax || solimp[2] <= 1e-15f) *imp = RMUL(0.5f, RADD(dmin, dmax));
1382
+ else if (x <= 0.f) *imp = dmin;
1383
+ else if (x >= 1.f) *imp = dmax;
1384
+ else if (power == 1.f) *imp = RFMA(x, RSUB(dmax, dmin), dmin);
1385
+ else *imp = fminf(fmaxf(imp_raw(x, dmin, dmax, mid, power, x <= mid), dmin), dmax);
1386
+ }
1387
+
1388
+ // the distances of hinge dof i at angle q to its lower and upper limit (the limit rows' test and pos: one IEEE
1389
+ // subtraction each; the adjoint's adj_limits replays the test)
1390
+ __device__ __forceinline__ void limit_dists(int i, float q, float* dmin, float* dmax) {
1391
+ *dmin = RSUB(q, c_jrange[2 * i]);
1392
+ *dmax = RSUB(c_jrange[2 * i + 1], q);
1393
+ }
1394
+
1395
+ // the invweight of a contact of pair pr (friction mu): body 1's + body 2's, for condim 3 MuJoCo's pyramid scaling
1396
+ __device__ __forceinline__ float contact_invw(int pr, float mu) {
1397
+ float iw = RADD(c_binvw[c_gbody[PG1(pr)]], c_binvw[c_gbody[PG2(pr)]]);
1398
+ if (PDIM(pr) == 3) iw = RMUL(RMUL(RMUL(RFMA(RMUL(mu, mu), iw, iw), 2.f), mu), mu) / c_sopt[0];
1399
+ return iw;
1400
+ }
1401
+
1402
+ // a row's D = 1 / max(R, 1e-15), R = invw (1 - imp) / imp
1403
+ __device__ __forceinline__ float efc_D(float iw, float imp) { return 1.f / fmaxf(RMUL(iw, RSUB(1.f, imp)) / imp, 1e-15f); }
1404
+
1405
+ template <class T> struct dk_is_ptr { static constexpr bool value = false; };
1406
+ template <class T> struct dk_is_ptr<T*> { static constexpr bool value = true; };
1407
+
1408
+ // con_dot[c][d] = J_c,d v for every contact and frame direction (one lane per pair; v a shared NV vector). DK_JV_VEC's
1409
+ // 128-bit loads only where con_J is a pointer (to struct Hand: SimP, SimN): in k_substep (struct Sim) they made ptxas
1410
+ // contract other mul / add pairs of that kernel differently (its mass matrix), and k_substep must stay bitwise the
1411
+ // split forward
1412
+ template <class S>
1413
+ __device__ void con_jv(S& s, const float* v, int lane) {
1414
+ int ncon = min(s.ncon, MAXCON);
1415
+ for (int q = lane; q < 3 * ncon; q += 32) {
1416
+ int c = q / 3, nd = s.con_nd[c];
1417
+ const float* J = s.con_J[c][q % 3];
1418
+ const unsigned char* dof = s.con_dof[c];
1419
+ float a0 = 0.f, a1 = 0.f; // even / odd support entries (unrolled and predicated: the loads are independent)
1420
+ #if DK_JV_VEC && KDOF == 16
1421
+ if constexpr (dk_is_ptr<decltype(s.con_J)>::value) {
1422
+ const uint4 dw = *reinterpret_cast<const uint4*>(dof); // the KDOF support dofs, 4 per word
1423
+ const unsigned dws[4] = {dw.x, dw.y, dw.z, dw.w};
1424
+ #pragma unroll
1425
+ for (int k4 = 0; k4 < KDOF; k4 += 4) {
1426
+ float4 j4 = make_float4(0.f, 0.f, 0.f, 0.f);
1427
+ if (k4 < nd) j4 = *reinterpret_cast<const float4*>(J + k4);
1428
+ const float jk[4] = {j4.x, j4.y, j4.z, j4.w};
1429
+ #pragma unroll
1430
+ for (int t = 0; t < 4; t += 2) {
1431
+ const int k = k4 + t;
1432
+ if (k < nd) a0 += jk[t] * v[(dws[k4 >> 2] >> (8 * t)) & 255u];
1433
+ if (k + 1 < nd) a1 += jk[t + 1] * v[(dws[k4 >> 2] >> (8 * t + 8)) & 255u];
1434
+ }
1435
+ }
1436
+ } else
1437
+ #endif
1438
+ {
1439
+ #pragma unroll
1440
+ for (int k = 0; k < KDOF; k += 2) {
1441
+ if (k < nd) a0 += J[k] * v[dof[k]];
1442
+ if (k + 1 < nd) a1 += J[k + 1] * v[dof[k + 1]];
1443
+ }
1444
+ }
1445
+ s.con_dot[c][q % 3] = a0 + a1;
1446
+ }
1447
+ __syncwarp();
1448
+ }
1449
+
1450
+ // J v for every row (v a shared NV vector) into out[] (NEFC entries); contact rows from con_jv
1451
+ template <class S>
1452
+ __device__ DK_INL_ROWSJV void rows_jv(S& s, const float* v, float* out, int lane) {
1453
+ con_jv(s, v, lane);
1454
+ for (int r = lane; r < s.nefc; r += 32) {
1455
+ int kind = s.efc_kind[r], a = s.efc_a[r], b = s.efc_b[r];
1456
+ float val;
1457
+ if (kind == 0) val = v[a];
1458
+ else if (kind == 1) val = b * v[a];
1459
+ else if (kind == 2) {
1460
+ float mu = s.con_mu[a], sg = (b & 1) ? -1.f : 1.f;
1461
+ val = s.con_dot[a][0] + sg * mu * s.con_dot[a][1 + (b >> 1)];
1462
+ } else val = s.con_dot[a][0];
1463
+ out[r] = val;
1464
+ }
1465
+ __syncwarp();
1466
+ }
1467
+
1468
+ // The piece of row r's cost at x (0 inactive, 1 quadratic, 2 / 3 the linear frictionloss pieces), with the cost
1469
+ // derivative s'(x) and the curvature (D on the quadratic piece, else 0); D the row's, F its frictionloss bound. The
1470
+ // frictionloss rows are the first NFLOSS rows (kind 0), so without them (mjlab model) the test is compiled out
1471
+ __device__ __forceinline__ int row_piece(int r, float x, float D, float F, float* ds, float* dd) {
1472
+ if (NFLOSS > 0 && r < NFLOSS) {
1473
+ float R = 1.f / D;
1474
+ if (x <= -R * F) { *ds = -F; *dd = 0.f; return 2; }
1475
+ if (x >= R * F) { *ds = F; *dd = 0.f; return 3; }
1476
+ *ds = D * x; *dd = D; return 1;
1477
+ }
1478
+ if (x < 0.f) { *ds = D * x; *dd = D; return 1; }
1479
+ *ds = 0.f; *dd = 0.f; return 0;
1480
+ }
1481
+ __device__ __forceinline__ float row_cost(int z, float x, float D, float F) { // the row's cost s(x) on piece z
1482
+ if (NFLOSS > 0 && z >= 2) { float R = 1.f / D; return (z == 2 ? -F * x : F * x) - 0.5f * R * F * F; }
1483
+ return z == 1 ? 0.5f * D * x * x : 0.f;
1484
+ }
1485
+ template <class S>
1486
+ __device__ __forceinline__ float row_floss(const S& s, int r) { // frictionloss bound of row r (0 for the others)
1487
+ return NFLOSS > 0 && r < NFLOSS ? c_floss[s.efc_a[r]] : 0.f;
1488
+ }
1489
+
1490
+ // row cost derivative s'(x), curvature (D on the quadratic zone, else 0) and cost s(x)
1491
+ template <class S>
1492
+ __device__ __forceinline__ void row_eval(const S& s, int r, float x, float* ds, float* dd, float* cost) {
1493
+ float D = s.efc_D[r], F = row_floss(s, r);
1494
+ *cost = row_cost(row_piece(r, x, D, F, ds, dd), x, D, F);
1495
+ }
1496
+
1497
+ // J^T f into out (f per row): a contact's rows combined into one force per frame direction (pyramid rows
1498
+ // n +- mu t1, n +- mu t2), then per dof the dof rows plus the contacts
1499
+ template <class S>
1500
+ __device__ __forceinline__ void con_force(const S& s, const float* f, int c, float* g) { // contact c's, per direction
1501
+ const float* fr = f + s.con_row[c];
1502
+ int nr = s.con_nrow[c];
1503
+ float f0 = nr > 0 ? fr[0] : 0.f, f1 = nr > 1 ? fr[1] : 0.f, f2 = nr > 2 ? fr[2] : 0.f, f3 = nr > 3 ? fr[3] : 0.f;
1504
+ float mu = s.con_dim[c] == 3 ? s.con_mu[c] : 0.f;
1505
+ g[0] = f0 + f1 + f2 + f3; g[1] = mu * (f0 - f1); g[2] = mu * (f2 - f3);
1506
+ }
1507
+ template <class S>
1508
+ __device__ void rows_jtf(S& s, const float* f, float* out, int lane) {
1509
+ int ncon = uniform_int(min(s.ncon, MAXCON), 7);
1510
+ #if DK_JTF_GATHER
1511
+ // per dof in registers (lane l: dofs l and l + 32): the dof rows, then the contacts in contact order (the sums of the
1512
+ // scatter below, bitwise). Lane i of a block of 32 contacts holds contact c0 + i's forces and support mask
1513
+ // (con_mask), shuffled to all lanes per contact; dof d is in contact c's support when bit d of the mask is set, at
1514
+ // support position k = the set bits below d. No __syncwarp() between the contacts and no shared memory
1515
+ float acc[2];
1516
+ #pragma unroll
1517
+ for (int t = 0; t < 2; t++) {
1518
+ const int i = lane + 32 * t;
1519
+ acc[t] = 0.f;
1520
+ if (i < NV)
1521
+ for (int r = 0; r < s.nefc_dof; r++) {
1522
+ if (s.efc_a[r] != i) continue;
1523
+ acc[t] += r < NFLOSS ? f[r] : s.efc_b[r] * f[r]; // frictionloss rows (kind 0) first, then limits (kind 1)
1524
+ }
1525
+ }
1526
+ SUBPROF(21);
1527
+ SUBPROF(22);
1528
+ const unsigned below = (1u << lane) - 1u;
1529
+ const auto CJ = s.con_J; // (SimP / SimN: the pointer into Hand, loaded once)
1530
+ for (int c0 = 0; c0 < ncon; c0 += 32) {
1531
+ float g[3] = {0.f, 0.f, 0.f};
1532
+ unsigned glo = 0u, ghi = 0u;
1533
+ if (c0 + lane < ncon) {
1534
+ con_force(s, f, c0 + lane, g);
1535
+ const unsigned long long m = s.con_mask[c0 + lane];
1536
+ glo = (unsigned)m; ghi = (unsigned)(m >> 32);
1537
+ }
1538
+ const int n = min(32, ncon - c0);
1539
+ #pragma unroll 1
1540
+ for (int i = 0; i < n; i++) { // the dofs 0-31 (not unrolled: 2 / 4 times were 1.7% / 4.8% slower on V100)
1541
+ const unsigned lo = __shfl_sync(0xffffffffu, glo, i);
1542
+ const float f0 = __shfl_sync(0xffffffffu, g[0], i), f1 = __shfl_sync(0xffffffffu, g[1], i),
1543
+ f2 = __shfl_sync(0xffffffffu, g[2], i);
1544
+ const float* J = CJ[c0 + i][0];
1545
+ if ((lo >> lane) & 1u) {
1546
+ const int k = __popc(lo & below);
1547
+ acc[0] += f0 * J[k] + f1 * J[KDOF + k] + f2 * J[2 * KDOF + k];
1548
+ }
1549
+ }
1550
+ // the dofs 32.. (lanes 0 ..): only the contacts with support there (few: a right wrist), in contact order. In the
1551
+ // loop above they cost every contact 3 predicated loads and 7 more instructions (ptxas if-converts a uniform
1552
+ // branch around them), and the gather was then 1-2% slower than the scatter on the RTX 3090
1553
+ if (NV > 32)
1554
+ for (unsigned hm = __ballot_sync(0xffffffffu, ghi != 0u); hm; hm &= hm - 1u) {
1555
+ const int i = __ffs(hm) - 1;
1556
+ const unsigned lo = __shfl_sync(0xffffffffu, glo, i), hi = __shfl_sync(0xffffffffu, ghi, i);
1557
+ const float f0 = __shfl_sync(0xffffffffu, g[0], i), f1 = __shfl_sync(0xffffffffu, g[1], i),
1558
+ f2 = __shfl_sync(0xffffffffu, g[2], i);
1559
+ const float* J = CJ[c0 + i][0];
1560
+ if ((hi >> lane) & 1u) {
1561
+ const int k = __popc(lo) + __popc(hi & below);
1562
+ acc[1] += f0 * J[k] + f1 * J[KDOF + k] + f2 * J[2 * KDOF + k];
1563
+ }
1564
+ }
1565
+ }
1566
+ #pragma unroll
1567
+ for (int t = 0; t < 2; t++)
1568
+ if (lane + 32 * t < NV) out[lane + 32 * t] = acc[t];
1569
+ __syncwarp();
1570
+ #else
1571
+ for (int c = lane; c < ncon; c += 32) con_force(s, f, c, s.con_f[c]);
1572
+ __syncwarp();
1573
+ SUBPROF(21);
1574
+ for (int i = lane; i < NV; i += 32) {
1575
+ float acc = 0.f;
1576
+ for (int r = 0; r < s.nefc_dof; r++) {
1577
+ if (s.efc_a[r] != i) continue;
1578
+ acc += r < NFLOSS ? f[r] : s.efc_b[r] * f[r]; // frictionloss rows (kind 0) first, then limits (kind 1)
1579
+ }
1580
+ out[i] = acc;
1581
+ }
1582
+ __syncwarp();
1583
+ SUBPROF(22);
1584
+ for (int c = 0; c < ncon; c++) { // scatter each contact over its support (one dof per lane)
1585
+ if (lane < s.con_nd[c])
1586
+ out[s.con_dof[c][lane]] += s.con_f[c][0] * s.con_J[c][0][lane] + s.con_f[c][1] * s.con_J[c][1][lane]
1587
+ + s.con_f[c][2] * s.con_J[c][2][lane];
1588
+ __syncwarp();
1589
+ }
1590
+ #endif
1591
+ SUBPROF(23);
1592
+ }
1593
+
1594
+ // zone of row r at x (the piece of its cost): 0 inactive, 1 quadratic, 2 / 3 the linear frictionloss pieces
1595
+ template <class S>
1596
+ __device__ __forceinline__ int row_zone(const S& s, int r, float x) {
1597
+ float ds, dd;
1598
+ return row_piece(r, x, s.efc_D[r], row_floss(s, r), &ds, &dd);
1599
+ }
1600
+
1601
+ // The tape helpers are not inlined: the forward without a tape then keeps its compact code (V100, a 4096-state corpus,
1602
+ // 4096 worlds: tape off 20.49 ms against 20.60 ms with the helpers inlined, 20.41 ms without any tape code; tape on
1603
+ // 20.84 / 20.88 ms)
1604
+
1605
+ // tape: the rows on their quadratic zone at the current jar (row_zone 1, the rows that put D into the Newton Hessian),
1606
+ // as bits; lane j returns rows 32 j .. 32 j + 31 (0 past nefc and on lanes j >= ceil(nefc / 32))
1607
+ template <class S>
1608
+ __device__ __noinline__ unsigned zone_word(const S& s, int lane) {
1609
+ unsigned z = 0u;
1610
+ const int nefc = uniform_int(s.nefc, 8);
1611
+ for (int r0 = 0; r0 < nefc; r0 += 32) {
1612
+ int r = r0 + lane;
1613
+ unsigned b = __ballot_sync(0xffffffffu, r < nefc && row_zone(s, r, s.efc_jar[r]) == 1);
1614
+ if (lane == r0 >> 5) z = b;
1615
+ }
1616
+ return z;
1617
+ }
1618
+
1619
+ // tape: n words from shared memory into the record and zeros up to word end (the padding to the next field, so a record
1620
+ // does not depend on what the buffer held before), lane-strided (each warp store is one coalesced 128-byte line when
1621
+ // dst is aligned), streaming stores (__stcs: the adjoint reads the tape much later)
1622
+ __device__ __noinline__ void tape_put(float* dst, const float* src, int n, int end, int lane) {
1623
+ for (int i = lane; i < end; i += 32) __stcs(dst + i, i < n ? src[i] : 0.f);
1624
+ }
1625
+
1626
+ // constraint forces at the current jar, J^T f into tmp and grad = M qacc - qfrc_smooth - J^T f; returns |grad| (and
1627
+ // with DK_GRAD_COST in .y the warp sum of extra, reduced together with it)
1628
+ template <class S>
1629
+ // (forces: compute the row forces into efc_jv; false: the line search's update has stored them there)
1630
+ #if DK_GRAD_COST
1631
+ __device__ DK_INL_GRAD float2 newton_grad(S& s, int lane, bool forces = true, float extra = 0.f) {
1632
+ #else
1633
+ __device__ DK_INL_GRAD float newton_grad(S& s, int lane, bool forces = true) {
1634
+ #endif
1635
+ if (forces)
1636
+ for (int r = lane; r < s.nefc; r += 32) {
1637
+ float ds, dd, c;
1638
+ row_eval(s, r, s.efc_jar[r], &ds, &dd, &c);
1639
+ s.efc_jv[r] = -ds; // the line search's J p is not needed any more
1640
+ }
1641
+ __syncwarp();
1642
+ SUBPROF(20);
1643
+ rows_jtf(s, s.efc_jv, s.tmp, lane);
1644
+ float gn = 0.f;
1645
+ for (int i = lane; i < NV; i += 32) { float g = s.Ma[i] - s.qsm[i] - s.tmp[i]; s.grad[i] = g; gn += g * g; }
1646
+ __syncwarp();
1647
+ #if DK_GRAD_COST
1648
+ for (int o = 16; o > 0; o >>= 1) { // warp_sum of both (the same sums, interleaved)
1649
+ gn += __shfl_xor_sync(0xffffffffu, gn, o);
1650
+ extra += __shfl_xor_sync(0xffffffffu, extra, o);
1651
+ }
1652
+ return make_float2(sqrtf(gn), extra);
1653
+ #else
1654
+ return sqrtf(warp_sum(gn));
1655
+ #endif
1656
+ }
1657
+
1658
+ // out = A v for a symmetric shared NV x NV matrix stored as its packed lower triangle
1659
+ // (a split of rows 32.. over the warp with shuffle sums, instead of their second trip, was 0.4% / 2.4% slower on the
1660
+ // V100 / RTX 3090; the element as `j <= i ? A[ri + j] : A[TRI(j, 0) + i]`, meant as two predicated loads at immediate
1661
+ // offsets, compiles to the same address select; a padded full copy of M does not fit SimN at 11 worlds per SM)
1662
+ __device__ DK_INL_MATVEC void matvec(const float* A, const float* v, float* out, int lane) {
1663
+ for (int i = lane; i < NV; i += 32) { // one trip count for all lanes: element (i, j) from row max(i, j)
1664
+ const int ri = TRI(i, 0);
1665
+ float acc = 0.f, acc2 = 0.f; // even / odd columns
1666
+ #pragma unroll
1667
+ for (int j = 0; j < NV; j++) { // fully unrolled, no branches: TRI(j, 0) is a constant
1668
+ const float* e = A + (j <= i ? ri + j : TRI(j, 0) + i);
1669
+ if (j & 1) acc2 += *e * v[j]; else acc += *e * v[j];
1670
+ }
1671
+ out[i] = acc + acc2;
1672
+ }
1673
+ __syncwarp();
1674
+ }
1675
+
1676
+ __device__ __forceinline__ float vdot(const float* a, const float* b, int lane) {
1677
+ float acc = 0.f;
1678
+ for (int i = lane; i < NV; i += 32) acc += a[i] * b[i];
1679
+ return warp_sum(acc);
1680
+ }
1681
+
1682
+ // total cost at the current qacc (needs Ma and efc_jar)
1683
+ template <class S>
1684
+ __device__ DK_INL_COST float total_cost(S& s, int lane) {
1685
+ float g = 0.f;
1686
+ for (int i = lane; i < NV; i += 32) g += 0.5f * (s.Ma[i] - s.qsm[i]) * (s.qacc[i] - s.qacc0[i]);
1687
+ for (int r = lane; r < s.nefc; r += 32) {
1688
+ float ds, dd, c;
1689
+ row_eval(s, r, s.efc_jar[r], &ds, &dd, &c);
1690
+ g += c;
1691
+ }
1692
+ return warp_sum(g);
1693
+ }
1694
+
1695
+ template <class S>
1696
+ __device__ void refresh(S& s, int lane) { // Ma, jar at the current qacc
1697
+ matvec(s.M, s.qacc, s.Ma, lane);
1698
+ SUBPROF(18);
1699
+ rows_jv(s, s.qacc, s.efc_jar, lane);
1700
+ SUBPROF(19);
1701
+ for (int r = lane; r < s.nefc; r += 32) s.efc_jar[r] -= s.efc_aref[r];
1702
+ __syncwarp();
1703
+ }
1704
+
1705
+ // the free joint (lane 0): position, then the orientation rotated by h times the angular velocity. Not inlined: ptxas
1706
+ // fuses some of its mul / add pairs depending on the surrounding code, and k_substep and k_post must agree bitwise
1707
+ __device__ __noinline__ void integrate_root(float* qpos, const float* qvel, float h) {
1708
+ for (int k = 0; k < 3; k++) qpos[k] += h * qvel[k];
1709
+ float w[3] = {qvel[3], qvel[4], qvel[5]}, nw = sqrtf(dot3(w, w));
1710
+ if (nw > 0.f) {
1711
+ float ang = h * nw, sa, ca;
1712
+ sincosf(0.5f * ang, &sa, &ca);
1713
+ float dq[4] = {ca, sa * w[0] / nw, sa * w[1] / nw, sa * w[2] / nw};
1714
+ float q[4] = {qpos[3], qpos[4], qpos[5], qpos[6]}, o[4];
1715
+ qmul(q, dq, o);
1716
+ float on = rsqrtf(o[0] * o[0] + o[1] * o[1] + o[2] * o[2] + o[3] * o[3]);
1717
+ for (int k = 0; k < 4; k++) qpos[3 + k] = o[k] * on;
1718
+ }
1719
+ }
1720
+ """
1721
+
1722
+ STEP_KERNEL = r"""
1723
+ // a contact's support as dof bits (con_mask) from x = the body mask of its two chains' symmetric difference (bit b:
1724
+ // body b on exactly one of them): the dofs whose body is in x
1725
+ __device__ __forceinline__ unsigned long long support_mask(unsigned x) {
1726
+ #if DOF_BODY_ROOT6
1727
+ return (unsigned long long)(x >> 2) << 6 | ((x & 2u) ? 0x3full : 0ull);
1728
+ #else
1729
+ unsigned long long m = 0ull;
1730
+ for (int i = 0; i < NV; i++)
1731
+ if ((x >> c_dofbody[i]) & 1u) m |= 1ull << i;
1732
+ return m;
1733
+ #endif
1734
+ }
1735
+ // the Newton Hessian into s.L (see below); world, grp0, grp1: the contacts against the world and their groups by body
1736
+ // (substep_post)
1737
+ template <class S>
1738
+ __device__ __forceinline__ void hessian(S& s, int ncon, unsigned long long world, unsigned grp0, unsigned grp1,
1739
+ int lane) {
1740
+ // H = M + J' D J on the quadratic rows (lower triangle into L), curvatures D from the rows' zones at jar. The pyramid
1741
+ // rows of a contact, u_k = n +- mu t1, n +- mu t2, add C_nn n n' + C_n1 (n t1' + t1 n') + C_11 t1 t1' + (same for t2)
1742
+ // = J' C J with C = [C_nn C_n1 C_n2; C_n1 C_11 0; C_n2 0 C_22] (only C_nn for condim 1) and J the frame rows
1743
+ float mv[(NTRI + 31) / 32]; // L = M: all loads first (entry e by lane e mod 32)
1744
+ #pragma unroll
1745
+ for (int k = 0; k < (NTRI + 31) / 32; k++) if (lane + 32 * k < NTRI) mv[k] = s.M[lane + 32 * k];
1746
+ int ha[HSETS][3], hb[HSETS], hthr[HSETS][3]; // this lane's support pairs (ha, hb) of one column hb per set, the
1747
+ #pragma unroll // same for every contact, valid when nd > hthr (step.hess_columns)
1748
+ for (int k = 0; k < HSETS; k++)
1749
+ #pragma unroll
1750
+ for (int t = 0; t < 3; t++) {
1751
+ unsigned e = c_hcol[(3 * k + t) * 32 + lane];
1752
+ ha[k][t] = e & 255; hb[k] = (e >> 8) & 255; hthr[k][t] = e >> 16;
1753
+ }
1754
+ unsigned long long act = 0ull; // contacts with a quadratic row
1755
+ for (int c0 = 0; c0 < ncon; c0 += 32) {
1756
+ int c = c0 + lane;
1757
+ bool on = false;
1758
+ if (c < ncon) {
1759
+ int r0 = s.con_row[c], nr = s.con_nrow[c];
1760
+ float d[4];
1761
+ #pragma unroll
1762
+ for (int k = 0; k < 4; k++) { // curvatures; the loads read a valid row either way (con_row is set only when
1763
+ int r = nr > k ? r0 + k : 0; // nr > 0), so there are no branches
1764
+ float jar = s.efc_jar[r], D = s.efc_D[r];
1765
+ d[k] = nr > k && jar < 0.f ? D : 0.f;
1766
+ }
1767
+ float d0 = d[0], d1 = d[1], d2 = d[2], d3 = d[3], mu = s.con_dim[c] == 3 ? s.con_mu[c] : 0.f;
1768
+ s.con_C[c][0] = d0 + d1 + d2 + d3;
1769
+ s.con_C[c][1] = mu * (d0 - d1); s.con_C[c][2] = mu * mu * (d0 + d1);
1770
+ s.con_C[c][3] = mu * (d2 - d3); s.con_C[c][4] = mu * mu * (d2 + d3);
1771
+ on = d0 + d1 + d2 + d3 != 0.f; // C_nn is the sum of the curvatures
1772
+ }
1773
+ act |= (unsigned long long)__ballot_sync(0xffffffffu, on) << c0;
1774
+ }
1775
+ SUBPROF(27);
1776
+ #pragma unroll
1777
+ for (int k = 0; k < (NTRI + 31) / 32; k++) if (lane + 32 * k < NTRI) s.L[lane + 32 * k] = mv[k];
1778
+ const int ndof = uniform_int(s.nefc_dof, 8);
1779
+ #if DK_HESS_DOFPAR
1780
+ if (NFLOSS == 0) { // limit rows only: one per dof, distinct diagonal entries, each added by its row's lane
1781
+ __syncwarp(); // (after the copy)
1782
+ for (int r = lane; r < ndof; r += 32) {
1783
+ float ds, dd, c;
1784
+ row_eval(s, r, s.efc_jar[r], &ds, &dd, &c);
1785
+ s.L[TRI(s.efc_a[r], s.efc_a[r])] += dd;
1786
+ }
1787
+ } else
1788
+ #endif
1789
+ for (int r0 = 0; r0 < ndof; r0 += 32) { // dof rows on the diagonal: frictionloss (quadratic zone) and limits, each
1790
+ int r = r0 + lane, e = 0; // added in row order by the lane that copied its entry
1791
+ float dd = 0.f;
1792
+ if (r < ndof) {
1793
+ float ds, c;
1794
+ row_eval(s, r, s.efc_jar[r], &ds, &dd, &c);
1795
+ e = TRI(s.efc_a[r], s.efc_a[r]);
1796
+ }
1797
+ for (int k = 0; k < min(32, ndof - r0); k++) {
1798
+ int ek = __shfl_sync(0xffffffffu, e, k);
1799
+ float dk = __shfl_sync(0xffffffffu, dd, k);
1800
+ if ((ek & 31) == lane) s.L[ek] += dk;
1801
+ }
1802
+ }
1803
+ __syncwarp();
1804
+ SUBPROF(28);
1805
+ // the contacts on the lower triangles of their supports (dofs ascending: dof[a] >= dof[b]): first the world
1806
+ // contacts, a group (one body, one support) at a time, then each contact between two bodies. Per lane and set: the
1807
+ // pairs (a, b) of one column b, H_ab = J_a' G_b with G_b = C J_b once per contact, summed over the group before the
1808
+ // update of L
1809
+ for (unsigned long long todo = act & world, rest = act & ~world; todo | rest;) {
1810
+ bool w = todo != 0ull;
1811
+ unsigned long long m64 = w ? todo : rest;
1812
+ int c0 = (unsigned)m64 ? 0 : 32; // contacts c0 + i, i in gm (32-bit masks: a cheap __ffs)
1813
+ unsigned m = (unsigned)(m64 >> c0);
1814
+ int c = __ffs(m) - 1;
1815
+ unsigned gw = __ballot_sync(0xffffffffu, ((c0 ? grp1 : grp0) >> c) & 1u), gm = w ? m & gw : 1u << c; // c's group
1816
+ if (w) todo &= ~((unsigned long long)gm << c0);
1817
+ else {
1818
+ rest &= ~((unsigned long long)gm << c0);
1819
+ __syncwarp(); // between two bodies: fenced
1820
+ }
1821
+ int nd = s.con_nd[c0 + c];
1822
+ const unsigned char* dof = s.con_dof[c0 + c];
1823
+ constexpr int hlo[HSETS] = HSET_LO;
1824
+ #pragma unroll
1825
+ for (int k = 0; k < HSETS; k++) {
1826
+ if (nd <= hlo[k]) break; // no rows of this set in the support
1827
+ int db = dof[hb[k]], he[3];
1828
+ float hv[3], lv[3];
1829
+ #pragma unroll
1830
+ for (int t = 0; t < 3; t++) { // the entries of one support are distinct: loads first, stores after the sum
1831
+ int da = dof[ha[k][t]];
1832
+ he[t] = da * (da + 1) / 2 + db;
1833
+ hv[t] = 0.f;
1834
+ if (nd > hthr[k][t]) lv[t] = s.L[he[t]];
1835
+ }
1836
+ unsigned mm = gm;
1837
+ int in = __ffs(mm) - 1; // the next contact, found one iteration ahead
1838
+ mm &= mm - 1u;
1839
+ for (int i = in; i >= 0; i = in) {
1840
+ in = __ffs(mm) - 1;
1841
+ mm &= mm - 1u;
1842
+ int cc = c0 + i, b = hb[k];
1843
+ const float *C = s.con_C[cc], *Jn = s.con_J[cc][0], *Ja = s.con_J[cc][1], *Jb = s.con_J[cc][2];
1844
+ float j0 = Jn[b], j1 = Ja[b], j2 = Jb[b]; // G_b (condim 1: C_nn only, the rest adds exact zeros)
1845
+ float g0 = C[0] * j0 + C[1] * j1 + C[3] * j2, g1 = C[1] * j0 + C[2] * j1, g2 = C[3] * j0 + C[4] * j2;
1846
+ #pragma unroll
1847
+ for (int t = 0; t < 3; t++) {
1848
+ int a = ha[k][t];
1849
+ hv[t] = fmaf(Jb[a], g2, fmaf(Ja[a], g1, fmaf(Jn[a], g0, hv[t])));
1850
+ }
1851
+ }
1852
+ #pragma unroll
1853
+ for (int t = 0; t < 3; t++) if (nd > hthr[k][t]) s.L[he[t]] = lv[t] + hv[t];
1854
+ }
1855
+ }
1856
+ }
1857
+
1858
+ // one substep for the world in s (qpos, qvel, qacc warm start, com, fric set); ctrl: this world's NV-6 setpoints.
1859
+ // Two halves (substep_pre: smooth dynamics, collision, Jacobians, rows; substep_post: Newton, implicitfast) so that they can
1860
+ // also run as separate kernels with the state in global memory (engine_step_check.py --split).
1861
+ // rec: this world's tape record of the substep (tape.py), or null (no tape); the same
1862
+ // pointer goes to both halves. The record is written at five points: the input state (here), the actuator clamp mask,
1863
+ // the contact table (end of substep_pre), the final zones with their Hessian factor L_H, and after the implicitfast
1864
+ // solve L_Q, a*, a_adv and the header (substep_post). The forward results do not depend on rec.
1865
+ template <class S>
1866
+ __device__ void substep_pre(S& s, const float* ctrl, int lane, float* rec) {
1867
+ const float h = c_misc[0];
1868
+ int b = lane, d = (b < NB) ? c_depth[b] : -1, p = (b < NB) ? c_parent[b] : 0;
1869
+ if (rec) { // tape: the substep's input state
1870
+ tape_put(rec + OFF_QPOS, s.qpos, NQ, NQ, lane);
1871
+ tape_put(rec + OFF_QVEL, s.qvel, NV, NV, lane);
1872
+ }
1873
+ if (lane == 0) {
1874
+ s.Q[0][0] = 1.f; s.Q[0][1] = s.Q[0][2] = s.Q[0][3] = 0.f;
1875
+ for (int k = 0; k < 3; k++) s.X[0][k] = s.W[0][k] = s.V[0][k] = s.AL[0][k] = s.A[0][k] = 0.f;
1876
+ s.ncon = 0; s.nefc = 0; // s.unsupported accumulates over substeps; the caller clears it
1877
+ s.min_nu_bits = 0x7f800000; // +inf
1878
+ }
1879
+ for (int i = lane; i < NV; i += 32) s.zero[i] = 0.f;
1880
+ for (int i = lane; i < NTRI; i += 32) s.M[i] = 0.f;
1881
+ PROF_START();
1882
+ // The tree passes below read what they need from shared memory into registers before they store anything: the
1883
+ // compiler cannot tell a body's arrays from its parent's or children's (same arrays, variable indices), so a load
1884
+ // after a store would wait for it (one shared-memory latency per element). The arithmetic is unchanged
1885
+ for (int L = 1; L <= MAXD; L++) { // kinematics and velocities (zero acceleration: RNE gives the bias forces)
1886
+ if (d == L) {
1887
+ float Qp[4], Xp[3], Wp[3], Vp[3], ALp[3], Ap[3], Qb[4], Xb[3], Wb[3], Vb[3], ALb[3], Ab[3];
1888
+ for (int k = 0; k < 4; k++) Qp[k] = s.Q[p][k];
1889
+ for (int k = 0; k < 3; k++) {
1890
+ Xp[k] = s.X[p][k]; Wp[k] = s.W[p][k]; Vp[k] = s.V[p][k]; ALp[k] = s.AL[p][k]; Ap[k] = s.A[p][k];
1891
+ }
1892
+ fwd_body(b, Qp, Xp, Wp, Vp, ALp, Ap, s.qpos, s.qvel, s.zero, Qb, Xb, Wb, Vb, ALb, Ab);
1893
+ for (int k = 0; k < 4; k++) s.Q[b][k] = Qb[k];
1894
+ for (int k = 0; k < 3; k++) {
1895
+ s.X[b][k] = Xb[k]; s.W[b][k] = Wb[k]; s.V[b][k] = Vb[k]; s.AL[b][k] = ALb[k]; s.A[b][k] = Ab[k];
1896
+ }
1897
+ }
1898
+ __syncwarp();
1899
+ }
1900
+ SUBPROF(14);
1901
+ const float O[3] = {s.X[1][0], s.X[1][1], s.X[1][2]}; // the root's origin: the point of the mass matrix
1902
+ if (b >= 1 && b < NB) {
1903
+ float ip[3], Qb[4], Xb[3], Wb[3], ALb[3], Ab[3], Fb[3], Nb[3], Jb[10];
1904
+ for (int k = 0; k < 4; k++) Qb[k] = s.Q[b][k];
1905
+ for (int k = 0; k < 3; k++) { Xb[k] = s.X[b][k]; Wb[k] = s.W[b][k]; ALb[k] = s.AL[b][k]; Ab[k] = s.A[b][k]; }
1906
+ body_ipos(b, s.com, ip);
1907
+ body_force(b, Qb, Wb, ALb, Ab, ip, Fb, Nb);
1908
+ body_inertia(b, Qb, Xb, O, ip, Jb);
1909
+ for (int k = 0; k < 3; k++) { s.F[b][k] = Fb[k]; s.N[b][k] = Nb[k]; }
1910
+ for (int k = 0; k < 10; k++) s.J[b][k] = Jb[k];
1911
+ if (b >= 2) { // the hinge's motion subspace about O into W, V (no longer needed), for the mass matrix and the
1912
+ float w[3], v[3]; // contact Jacobians
1913
+ dof_motion(b, 0, Qb, Xb, O, w, v);
1914
+ for (int k = 0; k < 3; k++) { s.W[b][k] = w[k]; s.V[b][k] = v[k]; }
1915
+ }
1916
+ }
1917
+ __syncwarp();
1918
+ SUBPROF(15);
1919
+ for (int L = MAXD - 1; L >= 1; L--) {
1920
+ if (d == L && c_nchild[b] > 0) {
1921
+ int nch = c_nchild[b];
1922
+ float Xb[3], Fb[3], Nb[3], Jb[10];
1923
+ for (int k = 0; k < 3; k++) { Xb[k] = s.X[b][k]; Fb[k] = s.F[b][k]; Nb[k] = s.N[b][k]; }
1924
+ for (int k = 0; k < 10; k++) Jb[k] = s.J[b][k];
1925
+ for (int i = 0; i < nch; i++) {
1926
+ int c = c_child[3 * b + i];
1927
+ float Xc[3], Fc[3], Nc[3];
1928
+ for (int k = 0; k < 3; k++) { Xc[k] = s.X[c][k]; Fc[k] = s.F[c][k]; Nc[k] = s.N[c][k]; }
1929
+ accumulate(Xb, Xc, Fc, Nc, Fb, Nb);
1930
+ for (int k = 0; k < 10; k++) Jb[k] += s.J[c][k];
1931
+ }
1932
+ for (int k = 0; k < 3; k++) { s.F[b][k] = Fb[k]; s.N[b][k] = Nb[k]; }
1933
+ for (int k = 0; k < 10; k++) s.J[b][k] = Jb[k];
1934
+ }
1935
+ __syncwarp();
1936
+ }
1937
+ SUBPROF(16);
1938
+ if (b >= 1 && b < NB) torques(b, s.Q[b], s.F[b], s.N[b], s.qsm); // qsm holds the bias for now
1939
+ float sw[3], sv[3], kw[3], kv[3], n[3], f[3];
1940
+ const float q1[4] = {s.Q[1][0], s.Q[1][1], s.Q[1][2], s.Q[1][3]}; // the root's rotation (its dofs' subspace)
1941
+ if (b >= 2 && b < NB) {
1942
+ int j = c_dadr[b], na = c_nanc[b], ad[12];
1943
+ float Jb[10], aw[12][3], av[12][3];
1944
+ for (int k = 0; k < 10; k++) Jb[k] = s.J[b][k];
1945
+ for (int k = 0; k < 3; k++) { sw[k] = s.W[b][k]; sv[k] = s.V[b][k]; }
1946
+ #pragma unroll
1947
+ for (int a = 0; a < 12; a++) // the hinge ancestors' motion subspaces, all loaded before the first store
1948
+ if (a < na) {
1949
+ int k = c_anc[12 * b + a];
1950
+ ad[a] = c_dadr[k];
1951
+ for (int t = 0; t < 3; t++) { aw[a][t] = s.W[k][t]; av[a][t] = s.V[k][t]; }
1952
+ }
1953
+ apply_inertia(Jb, sw, sv, n, f);
1954
+ s.M[TRI(j, j)] = dot3(sw, n) + dot3(sv, f) + c_armature[j];
1955
+ #pragma unroll
1956
+ for (int a = 0; a < 12; a++)
1957
+ if (a < na) s.M[TRI(j, ad[a])] = dot3(aw[a], n) + dot3(av[a], f);
1958
+ for (int t = 0; t < 6; t++) {
1959
+ dof_motion(1, t, q1, O, O, kw, kv);
1960
+ s.M[TRI(j, t)] = dot3(kw, n) + dot3(kv, f);
1961
+ }
1962
+ }
1963
+ if (b == 1) {
1964
+ float J1[10];
1965
+ for (int k = 0; k < 10; k++) J1[k] = s.J[1][k];
1966
+ for (int j = 0; j < 6; j++) {
1967
+ dof_motion(1, j, q1, O, O, sw, sv);
1968
+ apply_inertia(J1, sw, sv, n, f);
1969
+ for (int i = 0; i <= j; i++) {
1970
+ dof_motion(1, i, q1, O, O, kw, kv);
1971
+ s.M[TRI(j, i)] = dot3(kw, n) + dot3(kv, f) + (i == j ? c_armature[j] : 0.f);
1972
+ }
1973
+ }
1974
+ }
1975
+ __syncwarp();
1976
+ SUBPROF(17);
1977
+ for (int i0 = 0; i0 < NV; i0 += 32) { // qfrc_smooth = clamped actuator force - bias
1978
+ int i = i0 + lane;
1979
+ bool clamp = false;
1980
+ if (i < NV) {
1981
+ float act = 0.f;
1982
+ #if DK_CLAMP_IMPLICIT
1983
+ float kvg = c_kv[i], wv = 1.f; // the dof's implicit actuator damping; DK_CLAMP_IMPLICIT=2's tape word
1984
+ #endif
1985
+ if (i >= 6) {
1986
+ act = c_kp[i] * (ctrl[i - 6] - s.qpos[i + 1]) - c_kv[i] * s.qvel[i];
1987
+ #if DK_CLAMP_IMPLICIT == 2
1988
+ const float ov = fmaxf((fabsf(act) - c_frclim[i]) / c_frclim[i], 0.f); // the relative overshoot o
1989
+ #endif
1990
+ act = fminf(fmaxf(act, -c_frclim[i]), c_frclim[i]);
1991
+ clamp = act <= -c_frclim[i] || act >= c_frclim[i]; // at the limit: MuJoCo Warp's actuator_lam test
1992
+ #if DK_CLAMP_IMPLICIT == 1
1993
+ if (clamp) kvg = 0.f; // MuJoCo 4.0: a clamped force has no implicit damping
1994
+ #elif DK_CLAMP_IMPLICIT == 2
1995
+ if (clamp) { // w = exp(-o / delta), recorded with the force's sign (adjoint: w = |wv|, dw/df = -wv / (delta tau))
1996
+ wv = copysignf(expf(-ov / DK_CLAMP_IMPLICIT_DELTA), act);
1997
+ kvg *= fabsf(wv);
1998
+ }
1999
+ #endif
2000
+ }
2001
+ #if DK_CLAMP_IMPLICIT
2002
+ s.kvi[i] = kvg;
2003
+ #if DK_CLAMP_IMPLICIT == 2
2004
+ if (rec) __stcs(rec + OFF_KVW + i, wv);
2005
+ #endif
2006
+ #endif
2007
+ s.qsm[i] = act - s.qsm[i];
2008
+ }
2009
+ if (rec) { // tape: the clamp mask (dof bits), stored rather than recomputed: the adjoint's FMA contraction of the
2010
+ unsigned bal = __ballot_sync(0xffffffffu, clamp); // force could differ and flip a dof at the limit
2011
+ if (lane == 0) __stcs(rec + OFF_CLAMP + (i0 >> 5), __uint_as_float(bal));
2012
+ }
2013
+ }
2014
+ PROF(0);
2015
+ for (int i = lane; i < NV; i += 32) s.qacc0[i] = s.qsm[i];
2016
+ __syncwarp();
2017
+ CHOL_SOLVE(s.M, s.L, s.qacc0, lane, s.cbuf);
2018
+ PROF(1);
2019
+
2020
+ // collision
2021
+ geom_poses(s, lane);
2022
+ __syncwarp();
2023
+ SUBPROF(26);
2024
+ { // broad phase: the pairs whose bounding test passes (collide_pair's first test, here with a relative slack of 1e-5
2025
+ // so that it keeps every pair collide_pair keeps), in pair order into s.cand; then collide_pair on them, one per
2026
+ // lane (rather than 16 pairs per lane, most of them rejected and the narrow phases of the others diverging)
2027
+ static_assert(NPAIR < 65536, "candidate pairs as 16-bit indices");
2028
+ const unsigned lanes_below = (1u << lane) - 1u;
2029
+ #if FLOOR_G >= 0
2030
+ float fn[3]; // the only plane's normal
2031
+ zaxis_rn(s.gq[FLOOR_G], fn);
2032
+ #endif
2033
+ int ncand = 0;
2034
+ #pragma unroll 4
2035
+ for (int k = 0; k < (NPAIR + 31) / 32; k++) {
2036
+ int pr = lane + 32 * k;
2037
+ bool keep = false;
2038
+ if (pr < NPAIR) {
2039
+ int g1 = PG1(pr), g2 = PG2(pr);
2040
+ float dif[3] = {RSUB(s.gx[g2][0], s.gx[g1][0]), RSUB(s.gx[g2][1], s.gx[g1][1]), RSUB(s.gx[g2][2], s.gx[g1][2])};
2041
+ if (PPLANE(pr)) {
2042
+ #if FLOOR_G >= 0
2043
+ const float* n = fn;
2044
+ #else
2045
+ float n[3];
2046
+ zaxis_rn(s.gq[g1], n);
2047
+ #endif
2048
+ keep = dot3(dif, n) <= RFMA(c_grbound[g2], 1.f + 1e-5f, 1e-6f);
2049
+ } else {
2050
+ float rb = RADD(c_grbound[g1], c_grbound[g2]);
2051
+ keep = dot3(dif, dif) <= RFMA(RMUL(rb, rb), 1.f + 1e-5f, 1e-12f);
2052
+ }
2053
+ }
2054
+ unsigned bal = __ballot_sync(0xffffffffu, keep);
2055
+ if (keep) s.cand[ncand + __popc(bal & lanes_below)] = (unsigned short)pr;
2056
+ ncand += __popc(bal);
2057
+ }
2058
+ __syncwarp();
2059
+ SUBPROF(29);
2060
+ for (int i = lane; i < ncand; i += 32) collide_pair(s, s.cand[i]);
2061
+ }
2062
+ PROF(2);
2063
+ if (lane == 0 && s.ncon > MAXCON) s.unsupported |= 4;
2064
+ int ncon = uniform_int(min(s.ncon, MAXCON), 7);
2065
+ { // contact Jacobians: frame rows of J(body2, pos) - J(body1, pos) on the dofs on exactly one chain, packed in
2066
+ // ascending order. Lane l keeps the motion subspaces (w, v about O) of dofs l and l + 32, and the two bodies'
2067
+ // ancestor masks of contacts l and l + 32 (shuffled to all lanes per contact)
2068
+ static_assert(NV <= 64 && MAXCON <= 64, "two dofs and two contacts per lane");
2069
+ float dw[2][3], dv[2][3];
2070
+ int dbody[2];
2071
+ unsigned am1[2], am2[2];
2072
+ #pragma unroll
2073
+ for (int h = 0; h < 2; h++) {
2074
+ int i = lane + 32 * h, c = lane + 32 * h;
2075
+ dbody[h] = i < NV ? c_dofbody[i] : 0;
2076
+ if (dbody[h] == 1) dof_motion(1, i, q1, O, O, dw[h], dv[h]);
2077
+ else if (dbody[h] >= 2)
2078
+ for (int t = 0; t < 3; t++) { dw[h][t] = s.W[dbody[h]][t]; dv[h][t] = s.V[dbody[h]][t]; }
2079
+ int pr = c < ncon ? s.con_pair[c] : 0;
2080
+ am1[h] = c_ancmask[c_gbody[PG1(pr)]];
2081
+ am2[h] = c_ancmask[c_gbody[PG2(pr)]];
2082
+ }
2083
+ for (int c = 0; c < ncon; c++) {
2084
+ unsigned m1 = __shfl_sync(0xffffffffu, c < 32 ? am1[0] : am1[1], c & 31);
2085
+ unsigned m2 = __shfl_sync(0xffffffffu, c < 32 ? am2[0] : am2[1], c & 31);
2086
+ float pos[3], fr[9];
2087
+ for (int t = 0; t < 3; t++) pos[t] = s.con_pos[c][t];
2088
+ for (int t = 0; t < 9; t++) fr[t] = s.con_frame[c][t];
2089
+ int base = 0;
2090
+ #pragma unroll
2091
+ for (int h = 0; h < 2; h++) {
2092
+ int i = lane + 32 * h, bi = dbody[h];
2093
+ int in2 = (m2 >> bi) & 1, in1 = (m1 >> bi) & 1;
2094
+ bool on = i < NV && in1 != in2;
2095
+ unsigned bal = __ballot_sync(0xffffffffu, on);
2096
+ if (on) {
2097
+ int k = base + __popc(bal & ((1u << lane) - 1u));
2098
+ float r[3], u[3], jp[3];
2099
+ for (int t = 0; t < 3; t++) r[t] = pos[t] - O[t];
2100
+ cross(dw[h], r, u);
2101
+ float sg = in2 ? 1.f : -1.f;
2102
+ for (int t = 0; t < 3; t++) jp[t] = sg * (dv[h][t] + u[t]);
2103
+ for (int dd = 0; dd < 3; dd++) s.con_J[c][dd][k] = dot3(fr + 3 * dd, jp);
2104
+ s.con_dof[c][k] = (unsigned char)i;
2105
+ }
2106
+ base += __popc(bal);
2107
+ }
2108
+ if (lane == 0) s.con_nd[c] = base;
2109
+ }
2110
+ #pragma unroll
2111
+ for (int h = 0; h < 2; h++)
2112
+ if (lane + 32 * h < ncon) s.con_mask[lane + 32 * h] = support_mask(am1[h] ^ am2[h]); // (the ballots' bits)
2113
+ }
2114
+ PROF(3);
2115
+
2116
+ // constraint rows: dof frictionloss rows (dof order), active hinge limits (dof order), then per contact (contact order)
2117
+ // 4 pyramid rows (condim 3) or 1 normal row (condim 1); row indices from ballot prefix counts. First the dof rows'
2118
+ // (kind, dof, sign), one lane per dof
2119
+ const unsigned below = (1u << lane) - 1u;
2120
+ int ndof = 0;
2121
+ for (int i0 = 0; i0 < NV; i0 += 32) {
2122
+ int i = i0 + lane;
2123
+ bool on = i < NV && c_floss[i] > 0.f;
2124
+ unsigned bal = __ballot_sync(0xffffffffu, on);
2125
+ if (on) { int r = ndof + __popc(bal & below); s.efc_kind[r] = 0; s.efc_a[r] = i; s.efc_b[r] = 1; }
2126
+ ndof += __popc(bal);
2127
+ }
2128
+ for (int i0 = 0; i0 < NV; i0 += 32) {
2129
+ int i = min(i0 + lane, NV - 1); // clamped so that the loads need no branch
2130
+ float dmin, dmax;
2131
+ limit_dists(i, s.qpos[i + 1], &dmin, &dmax);
2132
+ bool on = i0 + lane < NV && i >= 6 && c_jlim[i] != 0.f && fminf(dmin, dmax) < 0.f;
2133
+ unsigned bal = __ballot_sync(0xffffffffu, on);
2134
+ if (on) {
2135
+ int r = ndof + __popc(bal & below);
2136
+ s.efc_kind[r] = 1; s.efc_a[r] = i; s.efc_b[r] = dmin < dmax ? 1 : -1;
2137
+ }
2138
+ ndof += __popc(bal);
2139
+ }
2140
+ con_jv(s, s.qvel, lane); // contact J qvel for the contact rows' velocities (its __syncwarp also publishes the above)
2141
+ // then one lane per job, a dof row (job j < ndof) or a contact (c = j - ndof): impedance, D and aref of its rows;
2142
+ // contact c's first row is ndof + c + 3 * (the number of condim-3 contacts before c)
2143
+ int ntri = 0;
2144
+ for (int j0 = 0; j0 < ndof + ncon; j0 += 32) {
2145
+ int j = j0 + lane, c = j - ndof;
2146
+ bool con = c >= 0 && c < ncon, tri = con && s.con_dim[c] == 3;
2147
+ unsigned b3 = __ballot_sync(0xffffffffu, tri);
2148
+ int r0 = ndof + c + 3 * (ntri + __popc(b3 & below));
2149
+ ntri += __popc(b3);
2150
+ if (j < ndof + ncon) {
2151
+ const float *sref, *simp;
2152
+ float iw, pos = 0.f, mu = 0.f;
2153
+ int i = 0;
2154
+ if (!con) { // dof row j: frictionloss (at 0) or limit
2155
+ i = s.efc_a[j];
2156
+ bool fl = s.efc_kind[j] == 0;
2157
+ float dmin, dmax;
2158
+ limit_dists(i, s.qpos[i + 1], &dmin, &dmax);
2159
+ iw = c_dinvw[i];
2160
+ pos = fl ? 0.f : fminf(dmin, dmax);
2161
+ sref = fl ? c_dsolref : c_jsolref; simp = fl ? c_dsolimp : c_jsolimp;
2162
+ } else {
2163
+ int pr = s.con_pair[c];
2164
+ mu = s.con_mu[c];
2165
+ iw = contact_invw(pr, mu);
2166
+ pos = s.con_dist[c]; sref = PSOLREF(pr); simp = PSOLIMP(pr);
2167
+ }
2168
+ float k, bb, imp;
2169
+ kbimp(sref, simp, pos, h, &k, &bb, &imp);
2170
+ float D = efc_D(iw, imp);
2171
+ if (!con) {
2172
+ s.efc_D[j] = D; s.efc_aref[j] = -k * imp * pos - bb * (s.efc_b[j] * s.qvel[i]);
2173
+ } else {
2174
+ int nr = max(0, min(tri ? 4 : 1, NEFC - r0)); // rows beyond NEFC are dropped
2175
+ s.con_row[c] = r0; s.con_nrow[c] = nr;
2176
+ #pragma unroll
2177
+ for (int t = 0; t < 4; t++) {
2178
+ if (t >= nr) break;
2179
+ float sg = (t & 1) ? -1.f : 1.f;
2180
+ float vel = tri ? s.con_dot[c][0] + sg * mu * s.con_dot[c][1 + (t >> 1)] : s.con_dot[c][0];
2181
+ s.efc_kind[r0 + t] = tri ? 2 : 3; s.efc_a[r0 + t] = c; s.efc_b[r0 + t] = t;
2182
+ s.efc_D[r0 + t] = D; s.efc_aref[r0 + t] = -k * imp * pos - bb * vel;
2183
+ }
2184
+ }
2185
+ }
2186
+ }
2187
+ if (lane == 0) {
2188
+ int need = ndof + ncon + 3 * ntri;
2189
+ if (need > NEFC) s.unsupported |= 16; // constraint rows beyond capacity are dropped
2190
+ s.nefc = min(need, NEFC);
2191
+ s.nefc_dof = ndof; // dof rows (frictionloss, limits) come first; contact rows follow
2192
+ }
2193
+ PROF(4);
2194
+ if (rec) // tape: the contact table in contact (= row) order, two 16-bit entries pair | slot << 9 per word
2195
+ for (int i = lane; i < (MAXCON + 1) / 2; i += 32) {
2196
+ unsigned e0 = 2 * i < ncon ? (unsigned)s.con_pair[2 * i] | (unsigned)s.con_slot[2 * i] << 9 : TAPE_CON_NONE;
2197
+ unsigned e1 = 2 * i + 1 < ncon ? (unsigned)s.con_pair[2 * i + 1] | (unsigned)s.con_slot[2 * i + 1] << 9
2198
+ : TAPE_CON_NONE;
2199
+ __stcs(rec + OFF_CON + i, __uint_as_float(e0 | e1 << 16));
2200
+ }
2201
+ }
2202
+
2203
+ template <class S>
2204
+ __device__ void substep_post(S& s, int iterations, int lane, int* niter_out, float* rec) {
2205
+ const float h = c_misc[0];
2206
+ int ncon = uniform_int(min(s.ncon, MAXCON), 7);
2207
+ PROF_START();
2208
+ // Newton solver from the warm start (or qacc_smooth when that is cheaper)
2209
+ const float scale = 1.f / (c_sopt[1] * NV), tol = c_sopt[2];
2210
+ refresh(s, lane);
2211
+ float cost = total_cost(s, lane);
2212
+ // the warm start's qacc, Ma and jar kept in tmp, p and efc_jv (all free here; SimN's Mp shares tmp's storage) in
2213
+ // case it stays the start
2214
+ for (int i = lane; i < NV; i += 32) { s.tmp[i] = s.qacc[i]; s.qacc[i] = s.qacc0[i]; s.p[i] = s.Ma[i]; }
2215
+ for (int r = lane; r < s.nefc; r += 32) s.efc_jv[r] = s.efc_jar[r];
2216
+ __syncwarp();
2217
+ refresh(s, lane);
2218
+ float cost0 = total_cost(s, lane);
2219
+ if (UNIFORM(cost0 > cost)) {
2220
+ for (int i = lane; i < NV; i += 32) { s.qacc[i] = s.tmp[i]; s.Ma[i] = s.p[i]; }
2221
+ for (int r = lane; r < s.nefc; r += 32) s.efc_jar[r] = s.efc_jv[r];
2222
+ __syncwarp();
2223
+ } else cost = cost0;
2224
+ PROF(5);
2225
+ newton_grad(s, lane);
2226
+ PROF(6);
2227
+ // contacts against the world, for the Hessian assembly: the support of such a contact is the whole chain of the
2228
+ // other body, so the dofs two of them share are their common ancestors' dofs, at the same positions in both supports,
2229
+ // and an entry of L they share comes from the same support pair (a, b), which is always on the same lane: no
2230
+ // __syncwarp() between them. The world contacts on one body have the same support and are summed in registers before
2231
+ // one update of L (grp0 / grp1: lane masks of the contacts 0-31 / 32-63 on the same body). A contact between two
2232
+ // bodies (support: the dofs on exactly one chain) is fenced on both sides.
2233
+ static_assert(MAXCON <= 64 && KDOF <= 32, "contact bit masks; hess_columns fits 32 lanes");
2234
+ unsigned long long world = 0ull;
2235
+ unsigned grp0 = 0u, grp1 = 0u;
2236
+ for (int c0 = 0; c0 < ncon; c0 += 32) {
2237
+ int c = c0 + lane, pr = c < ncon ? s.con_pair[c] : 0, b1 = c_gbody[PG1(pr)], b2 = c_gbody[PG2(pr)];
2238
+ bool w = c < ncon && (b1 == 0 || b2 == 0);
2239
+ world |= (unsigned long long)__ballot_sync(0xffffffffu, w) << c0;
2240
+ unsigned g = __match_any_sync(0xffffffffu, w ? b1 + b2 : -1 - lane);
2241
+ if (c0 == 0) grp0 = g; else grp1 = g;
2242
+ }
2243
+ // tape (rec): L_H must be the Hessian factor at the final zones. The last factorization was assembled at the jar
2244
+ // before the last step; when that step moved a row to another zone (chg, tested where jar is updated), or no step was
2245
+ // made, the loop runs once more without a step (refact): assembly and factorization at the final jar, so the tape
2246
+ // needs no second copy of the assembly code. Only the scratch s.L, s.p and s.con_C change, so the forward results are
2247
+ // the same with and without the tape
2248
+ int it = 0;
2249
+ bool conv = false, zchanged = rec && iterations <= 0, refact = zchanged, zsame = false;
2250
+ while (it < iterations || refact) {
2251
+ #if NEWTON_REUSE
2252
+ if (zsame && !refact) { // no row changed its zone in the last step: H and its factor in s.L are the same
2253
+ for (int i = lane; i < NV; i += 32) s.p[i] = -s.grad[i];
2254
+ __syncwarp();
2255
+ chol_resolve(s.L, s.p, lane, s.cbuf);
2256
+ } else
2257
+ #endif
2258
+ {
2259
+ hessian(s, ncon, world, grp0, grp1, lane);
2260
+ PROF(7);
2261
+ for (int i = lane; i < NV; i += 32) s.p[i] = -s.grad[i];
2262
+ __syncwarp();
2263
+ CHOL_SOLVE(s.L, s.L, s.p, lane, s.cbuf);
2264
+ }
2265
+ PROF(8);
2266
+ if (refact) break; // the tape's re-factorization: no step
2267
+ // exact line search along p on the piecewise-quadratic cost: 1-D Newton, stopping when the step stays on its piece
2268
+ rows_jv(s, s.p, s.efc_jv, lane);
2269
+ SUBPROF(24);
2270
+ matvec(s.M, s.p, s.Mp, lane);
2271
+ SUBPROF(25);
2272
+ #ifdef DK_PROFILE
2273
+ __syncwarp(); if (lane == 0) s.prof[12] += clock64() - s.prof_t;
2274
+ #endif
2275
+ float a1 = 0.f, a2 = 0.f;
2276
+ for (int i = lane; i < NV; i += 32) { a1 += (s.Ma[i] - s.qsm[i]) * s.p[i]; a2 += s.p[i] * s.Mp[i]; }
2277
+ a1 = warp_sum(a1); a2 = warp_sum(a2);
2278
+ // the lane's rows r = lane + 32 t stay in registers for all steps (jar, J p, D, frictionloss bound; zeros past
2279
+ // nefc: inactive, no contribution), their pieces as 2-bit codes; a Newton step's test whether it kept every row on
2280
+ // its piece (then it landed on the exact minimizer) is done by the next pass over the rows
2281
+ constexpr int RT = (NEFC + 31) / 32;
2282
+ const int nefc = s.nefc;
2283
+ float rx[RT], rj[RT], rD[RT], rF[RT];
2284
+ #pragma unroll
2285
+ for (int t = 0; t < RT; t++) {
2286
+ int r = lane + 32 * t;
2287
+ bool v = r < nefc;
2288
+ rx[t] = v ? s.efc_jar[r] : 0.f; rj[t] = v ? s.efc_jv[r] : 0.f; rD[t] = v ? s.efc_D[r] : 0.f;
2289
+ rF[t] = row_floss(s, r);
2290
+ }
2291
+ float alpha = 0.f, lo = 0.f, hi = 1e30f, d0 = 0.f;
2292
+ unsigned zprev = 0u;
2293
+ bool newton = false;
2294
+ for (int k = 0; k <= 40; k++) {
2295
+ float fd = 0.f, fdd = 0.f;
2296
+ unsigned z = 0u;
2297
+ #pragma unroll
2298
+ for (int t = 0; t < RT; t++) {
2299
+ if (32 * t >= nefc) break;
2300
+ float ds, dd, jv = rj[t];
2301
+ z |= (unsigned)row_piece(lane + 32 * t, rx[t] + alpha * jv, rD[t], rF[t], &ds, &dd) << (2 * t);
2302
+ fd += ds * jv; fdd += dd * jv * jv;
2303
+ }
2304
+ if (__all_sync(0xffffffffu, newton && z == zprev)) break; // the last Newton step kept every row on its piece
2305
+ if (k == 40) break;
2306
+ #ifdef DK_PROFILE
2307
+ if (lane == 0) s.prof[13]++;
2308
+ #endif
2309
+ fd = warp_sum(fd) + a1 + alpha * a2;
2310
+ fdd = warp_sum(fdd) + a2;
2311
+ if (k == 0) { d0 = fd; if (UNIFORM(d0 >= 0.f)) break; }
2312
+ if (UNIFORM(fabsf(fd) <= 1e-7f * fabsf(d0))) break;
2313
+ if (fd < 0.f) lo = alpha; else hi = alpha;
2314
+ float nx = alpha - fd / fdd;
2315
+ newton = nx > lo && nx < hi;
2316
+ if (!newton) nx = hi < 1e29f ? 0.5f * (lo + hi) : 2.f * fmaxf(alpha, 1e-6f);
2317
+ zprev = z;
2318
+ alpha = nx;
2319
+ }
2320
+ // move along p: qacc, M qacc and J qacc - aref are linear in alpha; with the new cost (as total_cost) and the rows'
2321
+ // forces for newton_grad
2322
+ float g = 0.f;
2323
+ for (int i = lane; i < NV; i += 32) {
2324
+ float qa = s.qacc[i] + alpha * s.p[i], ma = s.Ma[i] + alpha * s.Mp[i];
2325
+ s.qacc[i] = qa; s.Ma[i] = ma;
2326
+ g += 0.5f * (ma - s.qsm[i]) * (qa - s.qacc0[i]);
2327
+ }
2328
+ bool chg = false; // a row of this lane changes its zone (tape: the Hessian factored above is then out of date)
2329
+ #pragma unroll
2330
+ for (int t = 0; t < RT; t++) {
2331
+ int r = lane + 32 * t;
2332
+ if (32 * t >= nefc) break;
2333
+ if (r < nefc) {
2334
+ float xn = rx[t] + alpha * rj[t], ds, dd;
2335
+ int z0 = row_piece(r, rx[t], rD[t], rF[t], &ds, &dd), z1 = row_piece(r, xn, rD[t], rF[t], &ds, &dd);
2336
+ chg |= z0 != z1;
2337
+ g += row_cost(z1, xn, rD[t], rF[t]);
2338
+ s.efc_jar[r] = xn;
2339
+ s.efc_jv[r] = -ds; // the line search's J p is not needed any more
2340
+ }
2341
+ }
2342
+ zsame = !__any_sync(0xffffffffu, chg); // then the next H is this one
2343
+ PROF(9);
2344
+ #if DK_GRAD_COST
2345
+ PROF(10);
2346
+ const float2 gc = newton_grad(s, lane, false, g); // gradient at the new point (the stopping test and the next
2347
+ const float gn = gc.x, newcost = gc.y; // step), the new cost
2348
+ float improvement = scale * (cost - newcost);
2349
+ cost = newcost;
2350
+ #else
2351
+ float newcost = warp_sum(g);
2352
+ PROF(10);
2353
+ float improvement = scale * (cost - newcost);
2354
+ cost = newcost;
2355
+ float gn = newton_grad(s, lane, false); // gradient at the new point: the stopping test and the next step
2356
+ #endif
2357
+ PROF(6);
2358
+ it++;
2359
+ conv = UNIFORM(improvement < tol || scale * gn < tol);
2360
+ if (conv || it == iterations) {
2361
+ if (rec) { // tape: did the last step change a zone?
2362
+ zchanged = __any_sync(0xffffffffu, chg);
2363
+ #ifdef DK_TAPE_VERIFY
2364
+ for (int e = lane; e < NTRI; e += 32) s.Lv[e] = s.L[e]; // debug: always re-assemble, compare below
2365
+ refact = true;
2366
+ #else
2367
+ refact = zchanged;
2368
+ #endif
2369
+ }
2370
+ if (!refact) break;
2371
+ }
2372
+ }
2373
+ if (niter_out && lane == 0) *niter_out = it;
2374
+ if (rec) { // tape: the final zones and their Hessian factor, before the implicitfast solve overwrites L
2375
+ unsigned z = zone_word(s, lane);
2376
+ if (lane < (NEFC + 31) / 32) __stcs(rec + OFF_ZONE + lane, __uint_as_float(z));
2377
+ tape_put(rec + OFF_LH, s.L, NTRI, OFF_LQ - OFF_LH, lane);
2378
+ }
2379
+ #ifdef DK_TAPE_VERIFY
2380
+ bool vdiff = false; // the factor of the last Newton assembly differs from the one at the final zones
2381
+ if (rec && it > 0) {
2382
+ bool d = false;
2383
+ for (int e = lane; e < NTRI; e += 32) d |= __float_as_uint(s.L[e]) != __float_as_uint(s.Lv[e]);
2384
+ vdiff = __any_sync(0xffffffffu, d);
2385
+ }
2386
+ #endif
2387
+
2388
+ // implicitfast: (M + h kv) qacc' = M qacc; then qvel, qpos
2389
+ for (int e = lane; e < NTRI; e += 32) s.L[e] = s.M[e];
2390
+ __syncwarp();
2391
+ for (int i = lane; i < NV; i += 32) { s.L[TRI(i, i)] += h * KVI(i); s.tmp[i] = s.Ma[i]; }
2392
+ __syncwarp();
2393
+ CHOL_SOLVE(s.L, s.L, s.tmp, lane, s.cbuf);
2394
+ if (rec) { // tape: L_Q = chol(M + h kv), a* and a_adv (qvel' = qvel + h a_adv), header
2395
+ tape_put(rec + OFF_LQ, s.L, NTRI, REC_WORDS - OFF_LQ, lane);
2396
+ tape_put(rec + OFF_QACC, s.qacc, NV, NV, lane);
2397
+ #if DK_CLAMP_IMPLICIT == 2 // (the weights after qacc_adv, written by substep_pre: pad only behind them)
2398
+ tape_put(rec + OFF_QADV, s.tmp, NV, NV, lane);
2399
+ for (int i = OFF_KVW + NV + lane; i < OFF_LH; i += 32) __stcs(rec + i, 0.f);
2400
+ #else
2401
+ tape_put(rec + OFF_QADV, s.tmp, NV, OFF_LH - OFF_QADV, lane);
2402
+ #endif
2403
+ if (lane == 0) {
2404
+ float nu = __int_as_float(s.min_nu_bits);
2405
+ unsigned fl = (unsigned)(s.unsupported & 31) | (zchanged ? TAPE_REFACT : 0u) | (conv ? 0u : TAPE_NONCONV)
2406
+ | (nu < TAPE_SINGULAR_NU ? TAPE_SINGULAR : 0u);
2407
+ #ifdef DK_TAPE_VERIFY
2408
+ if (vdiff) fl |= TAPE_VERIFY_DIFF;
2409
+ #endif
2410
+ unsigned hd = (unsigned)ncon | (unsigned)s.nefc << 8 | (unsigned)(s.nefc_dof - NFLOSS) << 16
2411
+ | (unsigned)min(it, 255) << 24;
2412
+ __stcs(rec + OFF_HDR, __uint_as_float(hd));
2413
+ __stcs(rec + OFF_FLAGS, __uint_as_float(fl));
2414
+ __stcs(rec + OFF_MIN_NU, nu);
2415
+ __stcs(rec + OFF_RESERVED, 0.f);
2416
+ }
2417
+ }
2418
+ for (int i = lane; i < NV; i += 32) s.qvel[i] += h * s.tmp[i];
2419
+ __syncwarp();
2420
+ if (lane == 0) integrate_root(s.qpos, s.qvel, h);
2421
+ for (int i = 6 + lane; i < NV; i += 32) s.qpos[i + 1] += h * s.qvel[i];
2422
+ __syncwarp();
2423
+ PROF(11);
2424
+ }
2425
+
2426
+ template <class S>
2427
+ __device__ __forceinline__ void substep(S& s, const float* ctrl, int iterations, int lane, int* niter_out,
2428
+ float* rec) {
2429
+ substep_pre(s, ctrl, lane, rec);
2430
+ substep_post(s, iterations, lane, niter_out, rec);
2431
+ }
2432
+
2433
+ // The split forward (host.py: k_pre, k_post, dk_forward_split): substep_pre and substep_post as two kernels, each
2434
+ // with its own state (SimP, SimN: only what that half uses, so more worlds fit an SM, and each kernel's code is about
2435
+ // half of k_substep's). Their members have struct Sim's names, so the device code above runs unchanged on all three;
2436
+ // arrays that live in global memory are pointers there (struct Hand, one per world: what substep_pre hands to
2437
+ // substep_post).
2438
+ // substep_post runs on SimNT<SPLIT_NCON, SPLIT_NEFC> in shared memory when the world's contacts and rows fit (corpora:
2439
+ // at most 31 contacts and 122 rows), else on a full-capacity SimN in Hand (global memory, the same code).
2440
+ #ifndef SPLIT_NCON
2441
+ #define SPLIT_NCON (MAXCON < 32 ? MAXCON : 32) // k_post's shared-memory capacity: contacts
2442
+ #endif
2443
+ #ifndef SPLIT_NEFC
2444
+ #define SPLIT_NEFC (NEFC < 128 ? NEFC : 128) // and constraint rows
2445
+ #endif
2446
+ template <int NC, int NR>
2447
+ struct SimNT { // substep_post: Newton, implicitfast; capacity NC contacts, NR rows. Members whose lifetimes do not
2448
+ float M[NTRI], L[NTRI]; // overlap share storage (unions), the read-only ones the loop seldom reads stay in Hand
2449
+ float qacc[NV], Ma[NV];
2450
+ union { float grad[NV], p[NV]; }; // grad is last read by p = -grad (in place)
2451
+ union { float Mp[NV], tmp[NV]; }; // Mp: line search to update; tmp: J'f (newton_grad), start's qacc, implicitfast
2452
+ float efc_D[NR], efc_jar[NR];
2453
+ unsigned char efc_kind[NR], efc_a[NR];
2454
+ signed char efc_b[NR];
2455
+ int ncon, nefc, unsupported, min_nu_bits, nefc_dof;
2456
+ union {
2457
+ float con_C[NC][5]; // the Hessian assembly only (J p, the forces and their per-contact sums are dead there)
2458
+ alignas(16) float cbuf[72]; // CHOL_SOLVE's scratch: the factorizations (con_C is dead from there on)
2459
+ struct {
2460
+ union { float con_dot[NC][3], con_f[NC][3]; };
2461
+ float efc_jv[NR];
2462
+ };
2463
+ };
2464
+ unsigned short con_row[NC];
2465
+ unsigned char con_dim[NC], con_nrow[NC], con_nd[NC];
2466
+ float *qpos, *qvel; // the kernel's outputs (implicitfast only)
2467
+ const float *qsm, *qacc0, *con_mu, *efc_aref; // in Hand
2468
+ #if DK_CLAMP_IMPLICIT
2469
+ const float* kvi; // in Hand
2470
+ #endif
2471
+ const int* con_pair;
2472
+ const float (*con_J)[3][KDOF];
2473
+ const unsigned char (*con_dof)[KDOF];
2474
+ const unsigned long long* con_mask;
2475
+ #ifdef DK_PROFILE
2476
+ long long prof[NPROF], prof_t, prof_u;
2477
+ #endif
2478
+ #ifdef DK_TAPE_VERIFY
2479
+ float Lv[NTRI];
2480
+ #endif
2481
+ };
2482
+ typedef SimNT<SPLIT_NCON, SPLIT_NEFC> SimN; // k_post's shared memory
2483
+ typedef SimNT<MAXCON, NEFC> SimNfull; // the worlds beyond it (Hand::big)
2484
+
2485
+ struct Hand {
2486
+ float M[NTRI], qsm[NV], qacc0[NV];
2487
+ #if DK_CLAMP_IMPLICIT
2488
+ float kvi[NV]; // substep_pre's implicit actuator damping (DK_CLAMP_IMPLICIT)
2489
+ #endif
2490
+ float efc_D[NEFC], efc_aref[NEFC];
2491
+ alignas(16) float con_J[MAXCON][3][KDOF]; // (16-byte aligned: con_jv's 128-bit loads)
2492
+ float con_mu[MAXCON];
2493
+ int con_pair[MAXCON], con_dim[MAXCON], con_row[MAXCON], con_nrow[MAXCON], con_nd[MAXCON];
2494
+ int ncon, nefc, nefc_dof, unsupported, min_nu_bits;
2495
+ unsigned char efc_kind[NEFC], efc_a[NEFC];
2496
+ signed char efc_b[NEFC];
2497
+ alignas(16) unsigned char con_dof[MAXCON][KDOF];
2498
+ unsigned long long con_mask[MAXCON];
2499
+ float con_dist[MAXCON], con_pos[MAXCON][3], con_frame[MAXCON][9]; // substep_pre's (collision, Jacobians, rows)
2500
+ SimNfull big; // k_post's state of a world whose contacts or rows exceed SimN's capacity
2501
+ };
2502
+
2503
+ struct SimP { // substep_pre: smooth dynamics, qacc_smooth, collision, contact Jacobians (into Hand), rows (into Hand)
2504
+ float Q[NB][4], X[NB][3];
2505
+ float W[NB][3], V[NB][3]; // body velocities, then (body forces to contact Jacobians) the hinge motion subspaces
2506
+ union { // the smooth phase's body quantities, then qacc_smooth's factor, then the collision's geoms and candidates
2507
+ struct { float AL[NB][3], A[NB][3], F[NB][3], N[NB][3], J[NB][10]; };
2508
+ struct { float L[NTRI]; alignas(16) float cbuf[72]; }; // CHOL_SOLVE's scratch
2509
+ struct { float gx[NGEOMC][3], gq[NGEOMC][4], con_dot[MAXCON][3]; unsigned short cand[NPAIR]; };
2510
+ };
2511
+ float* M; // in Hand (the stores of the CRB, the loads of qacc_smooth's factorization)
2512
+ float qpos[NQ], qvel[NV], zero[NV], qsm[NV], qacc0[NV];
2513
+ #if DK_CLAMP_IMPLICIT
2514
+ float kvi[NV]; // implicitfast's actuator damping per dof (DK_CLAMP_IMPLICIT), handed to k_post in Hand
2515
+ #endif
2516
+ float com[3], fric;
2517
+ int ncon, nefc, unsupported, min_nu_bits, nefc_dof;
2518
+ int con_pair[MAXCON], con_dim[MAXCON], con_row[MAXCON], con_nrow[MAXCON], con_nd[MAXCON];
2519
+ float con_mu[MAXCON];
2520
+ unsigned char con_slot[MAXCON];
2521
+ float *con_dist, (*con_pos)[3], (*con_frame)[9]; // in Hand
2522
+ float (*con_J)[3][KDOF];
2523
+ unsigned char (*con_dof)[KDOF];
2524
+ unsigned long long* con_mask;
2525
+ unsigned char *efc_kind, *efc_a;
2526
+ signed char* efc_b;
2527
+ float *efc_D, *efc_aref;
2528
+ #ifdef DK_PROFILE
2529
+ long long prof[NPROF], prof_t, prof_u;
2530
+ #endif
2531
+ };
2532
+ """
2533
+
2534
+
2535
+
2536
+ TERRAIN_DEVICE = r"""
2537
+ // ---- terrain (nablaengine.terrain): static boxes and heightfields in global memory, shared by every world ----
2538
+ // set by <unit>_set_terrain (terrain.pack's arrays on the device); grid == nullptr: no terrain uploaded
2539
+ struct TerrainPtrs {
2540
+ const float* box; // (nbox, 15): pos, rot (row major), half sizes
2541
+ const float* hfh; // (nhf, 16): pos, rot, MuJoCo hfield_size (x, y radius, z scale, z bottom)
2542
+ const int* hfi; // (nhf, 4): nrow, ncol, data address, 0
2543
+ const float* hfd; // heights, MuJoCo's normalised data (times hfield_size z)
2544
+ const float* grid; // x0, y0, 1 / cell, nx, ny, nbox
2545
+ const int* cstart; // (nx ny + 1) cell offsets into citems
2546
+ const int* citems; // element indices: box i, or nbox + heightfield j
2547
+ const int* ecell; // (n, 2) each element's first cell
2548
+ };
2549
+ __device__ TerrainPtrs g_ter;
2550
+ // the block's world's object slots (TERRAIN_NOBJ x 15 floats in com after the COM offset; one world per block), set
2551
+ // by the kernels as they read com
2552
+ __shared__ const float* dk_obj;
2553
+ // a box of the terrain (e < OBJ_E0) or the world's object slot e - OBJ_E0
2554
+ __device__ __forceinline__ const float* ter_box(int e) { return e >= OBJ_E0 ? dk_obj + 15 * (e - OBJ_E0) : g_ter.box + 15 * e; }
2555
+
2556
+ // height and upward unit normal of the heightfield triangle below local (x, y) (cells split along MuJoCo's
2557
+ // (c, r+1)-(c+1, r) diagonal); false outside the grid
2558
+ __device__ __forceinline__ bool hfield_surface(const float* hs, const float* hd, int nrow, int ncol, float x, float y,
2559
+ float* h, float* n) {
2560
+ float dx = 2.f * hs[0] / float(ncol - 1), dy = 2.f * hs[1] / float(nrow - 1);
2561
+ float fc = (x + hs[0]) / dx, fr = (y + hs[1]) / dy;
2562
+ if (fc < 0.f || fr < 0.f || fc > float(ncol - 1) || fr > float(nrow - 1)) return false;
2563
+ int c0 = min(int(floorf(fc)), ncol - 2), r0 = min(int(floorf(fr)), nrow - 2);
2564
+ float u = fc - float(c0), v = fr - float(r0);
2565
+ float h00 = hd[r0 * ncol + c0] * hs[2], h10 = hd[r0 * ncol + c0 + 1] * hs[2];
2566
+ float h01 = hd[(r0 + 1) * ncol + c0] * hs[2], h11 = hd[(r0 + 1) * ncol + c0 + 1] * hs[2];
2567
+ float t[3];
2568
+ if (u + v <= 1.f) {
2569
+ *h = h00 + u * (h10 - h00) + v * (h01 - h00);
2570
+ t[0] = -dy * (h10 - h00); t[1] = -dx * (h01 - h00); t[2] = dx * dy;
2571
+ } else {
2572
+ *h = h11 + (1.f - u) * (h01 - h11) + (1.f - v) * (h10 - h11);
2573
+ t[0] = dy * (h01 - h11); t[1] = dx * (h10 - h11); t[2] = dx * dy;
2574
+ }
2575
+ float il = rsqrtf(t[0] * t[0] + t[1] * t[1] + t[2] * t[2]);
2576
+ for (int k = 0; k < 3; k++) n[k] = t[k] * il;
2577
+ return true;
2578
+ }
2579
+
2580
+ // The terrain contacts' geometry, shared by the forward and the adjoint's replay (adjoint_contact.TERRAIN_DEVICE):
2581
+ // one __noinline__ copy of each, so the replay computes the forward's bits (the native heightfield contacts instead are
2582
+ // explicitly rounded and inlined into both: TERRAIN_HF_NATIVE below). A contact's tape slot is k | element << 8
2583
+ // (k: capsule_box's candidate, or the heightfield sample point; element: box i, or nbox + heightfield j)
2584
+
2585
+ // sphere (centre sp, radius r) against terrain box b (15 words): sphere_box with the normal from the box towards the
2586
+ // sphere
2587
+ __device__ __noinline__ void terrain_sphere_box(const float* sp, float r, const float* b, float* dist, float* pos,
2588
+ float* n) {
2589
+ sphere_box(sp, r, b, b + 3, b + 12, dist, pos, n);
2590
+ for (int k = 0; k < 3; k++) n[k] = -n[k];
2591
+ }
2592
+
2593
+ // centre of capsule_box's candidate sphere at segment parameter seg (capbox_segs), as capsule_box computes it
2594
+ __device__ __noinline__ void capbox_point(const float* cp, const float* axisw, float hl, const float* b, float seg,
2595
+ float* ce) {
2596
+ const float *bp = b, *R = b + 3;
2597
+ float d[3] = {cp[0] - bp[0], cp[1] - bp[1], cp[2] - bp[2]}, pos[3], axis[3], lc[3], t[3];
2598
+ mtv3(R, d, pos);
2599
+ mtv3(R, axisw, axis);
2600
+ for (int k = 0; k < 3; k++) lc[k] = pos[k] + axis[k] * hl * seg;
2601
+ mv3(R, lc, t);
2602
+ for (int k = 0; k < 3; k++) ce[k] = bp[k] + t[k];
2603
+ }
2604
+
2605
+ // capsule_box's candidate spheres for a terrain box b (capbox_segs) with a fast path for the common case, a capsule
2606
+ // resting on a box's top: both ends above the box's local +z face and inside its footprint by more than 1 mm. There
2607
+ // capsule_box's search ends with the lower end (the -1 end on a tie) against that face (no edge is nearer: they are
2608
+ // at least 1 mm away horizontally), and the second candidate is the other end (its exits from the face's footprint
2609
+ // lie beyond the segment): segs = (lower, other), the same values as capbox_segs without its edge search
2610
+ __device__ __noinline__ int terrain_capbox_segs(const float* cp, const float* axisw, float hl, const float* b,
2611
+ float* segs) {
2612
+ const float *bp = b, *R = b + 3, *bs = b + 12;
2613
+ float d[3] = {cp[0] - bp[0], cp[1] - bp[1], cp[2] - bp[2]}, pos[3], axis[3], dz[2];
2614
+ mtv3(R, d, pos);
2615
+ mtv3(R, axisw, axis);
2616
+ bool fast = true;
2617
+ for (int e = 0; e < 2 && fast; e++) {
2618
+ float tip[3];
2619
+ for (int j = 0; j < 3; j++) tip[j] = pos[j] + float(2 * e - 1) * (axis[j] * hl);
2620
+ fast = fabsf(tip[0]) <= bs[0] - 1e-3f && fabsf(tip[1]) <= bs[1] - 1e-3f && tip[2] > bs[2];
2621
+ dz[e] = (bs[2] - tip[2]) * (bs[2] - tip[2]);
2622
+ }
2623
+ if (!fast) return capbox_segs(cp, axisw, hl, bp, R, bs, segs);
2624
+ segs[0] = dz[1] < dz[0] ? 1.f : -1.f;
2625
+ segs[1] = -segs[0];
2626
+ return 2;
2627
+ }
2628
+
2629
+ // robot geom g (sphere or capsule, pose gx / gq) against terrain box e. Broad phase: the geom's bounding sphere
2630
+ // against the oriented box (the squared distance from the geom's centre to the box, in the box's frame, against the
2631
+ // bounding radius squared, with a relative margin of 2e-4 and 1e-6 m^2: conservative, a contact needs the geom to
2632
+ // touch the box); large boxes (stair treads, platforms) no longer send every geom within their bounding sphere through
2633
+ // the narrow phase
2634
+ template <class S>
2635
+ __device__ void terrain_box(S& s, int pair, int g, int e) {
2636
+ const float* b = ter_box(e);
2637
+ if (!(b[12] > 0.f)) return; // an absent object slot
2638
+ const float* p = s.gx[g];
2639
+ float d[3] = {p[0] - b[0], p[1] - b[1], p[2] - b[2]};
2640
+ {
2641
+ const float rg = c_grbound[g];
2642
+ float q2 = 0.f;
2643
+ #pragma unroll
2644
+ for (int i = 0; i < 3; i++) {
2645
+ const float l = b[3 + i] * d[0] + b[6 + i] * d[1] + b[9 + i] * d[2]; // (R' d)_i
2646
+ const float o = fmaxf(fabsf(l) - b[12 + i], 0.f);
2647
+ q2 += o * o;
2648
+ }
2649
+ if (q2 > rg * rg * 1.0002f + 1e-6f) return;
2650
+ }
2651
+ const float* sz = c_gsize + 3 * g;
2652
+ float dist, pos[3], n[3], fr[9];
2653
+ if (c_gtype[g] == 1) {
2654
+ terrain_sphere_box(p, sz[0], b, &dist, pos, n);
2655
+ if (dist < 0.f) { make_frame(n, fr); add_contact(s, pair, e << 8, dist, pos, fr); }
2656
+ } else if (c_gtype[g] == 2) {
2657
+ float axis[3], segs[2], ce[3];
2658
+ zaxis_rn(s.gq[g], axis);
2659
+ const int ns = terrain_capbox_segs(p, axis, sz[1], b, segs);
2660
+ for (int k = 0; k < ns; k++) {
2661
+ capbox_point(p, axis, sz[1], b, segs[k], ce);
2662
+ terrain_sphere_box(ce, sz[0], b, &dist, pos, n);
2663
+ if (dist < 0.f) { make_frame(n, fr); add_contact(s, pair, k | e << 8, dist, pos, fr); }
2664
+ }
2665
+ }
2666
+ }
2667
+
2668
+ // sample point k of robot geom g (type gt, size sz, pose gp / gq) against terrain heightfield j: (sphere: the centre;
2669
+ // capsule: TERRAIN_CAP_PTS points w = -1 .. 1 along the axis) against the plane of the heightfield triangle below it
2670
+ // (the analytic mode): dist = n_z (q_z - h) - r, pos = q - (r + dist / 2) n, normal nw (world,
2671
+ // from the terrain towards the geom); false outside the grid
2672
+ __device__ __noinline__ bool terrain_hfield_point(int j, int gt, const float* sz, const float* gp, const float* gq,
2673
+ int k, float* dist, float* pos, float* nw) {
2674
+ const float* hh = g_ter.hfh + 16 * j;
2675
+ const int* hi = g_ter.hfi + 4 * j;
2676
+ const float* R = hh + 3;
2677
+ float d[3] = {gp[0] - hh[0], gp[1] - hh[1], gp[2] - hh[2]}, q[3], al[3] = {0.f, 0.f, 0.f}, w = 0.f;
2678
+ mtv3(R, d, q); // the geom centre in the heightfield's frame
2679
+ if (gt == 2) {
2680
+ float axis[3];
2681
+ zaxis_rn(gq, axis);
2682
+ mtv3(R, axis, al);
2683
+ w = TERRAIN_CAP_PTS > 1 ? -1.f + float(k) * 2.f / float(TERRAIN_CAP_PTS - 1) : 0.f;
2684
+ }
2685
+ for (int i = 0; i < 3; i++) q[i] += w * sz[1] * al[i];
2686
+ float h, n[3];
2687
+ if (!hfield_surface(hh + 12, g_ter.hfd + hi[2], hi[0], hi[1], q[0], q[1], &h, n)) return false;
2688
+ *dist = (q[2] - h) * n[2] - sz[0];
2689
+ float posl[3];
2690
+ for (int i = 0; i < 3; i++) posl[i] = q[i] - (sz[0] + 0.5f * (*dist)) * n[i];
2691
+ mv3(R, posl, pos);
2692
+ for (int i = 0; i < 3; i++) pos[i] += hh[i];
2693
+ mv3(R, n, nw);
2694
+ return true;
2695
+ }
2696
+
2697
+ #if TERRAIN_HF_NATIVE
2698
+ // ---- native heightfield contacts (TerrainConfig.mode = "native"): MuJoCo's prisms (mjc_ConvexHField / MuJoCo Warp's
2699
+ // ccd_hfield_kernel: the cells under the geom's bounding box, two triangular prisms per cell from the triangle down to
2700
+ // the heightfield's bottom), each measured exactly in closed form instead of GJK / EPA, and MuJoCo's choice of at most 4
2701
+ // contacts per geom and heightfield (the deepest, the farthest from it, the farthest from their line, the fourth)
2702
+ // among the penetrating candidates. Per prism, the geom's core (sphere: its centre; capsule: its axis segment):
2703
+ // - disjoint from the prism: for every prism face whose face region the core's points project into, the two ends of
2704
+ // that part of the core (each one's exact distance to the prism is its height above the face); and the closest
2705
+ // pair when it lies on a prism edge or vertex (point-to-point normal);
2706
+ // - intersecting the prism: the minimum translation by the separating axes (face normals, axis x edge directions),
2707
+ // at the core's deepest point along it (the middle of the core where the core is parallel to the face).
2708
+ // On a flat heightfield this gives the plane's contacts (a capsule: its two ends). Contact types for the adjoint:
2709
+ // HF_FACE (constant normal), HF_POINT (normal from a fixed prism point q to the core point), HF_DEEP (constant normal).
2710
+ // The geom's core, the prisms' vertices, the prism routine (hf_prism) and a chosen contact's geometry are written with
2711
+ // the explicit roundings (RMUL, RADD, RFMA: source.py) and inlined into the forward (hfield_native) and the adjoint's
2712
+ // replay (hfield_native_one): each copy computes the same bits in any kernel, compilation unit or -fmad setting. Inlined,
2713
+ // the prism's arrays (indexed by constants once unrolled) stay in registers; the forward keeps only its candidates in
2714
+ // local memory
2715
+ #define HF_MAXCAND 24
2716
+ #define HF_FACE 0
2717
+ #define HF_POINT 1
2718
+ #define HF_DEEP 2
2719
+ #define HF_MIN_NEXT 1e-3f // MuJoCo Warp's MIN_DIST_TO_NEXT_CONTACT (here a candidate below it is never taken)
2720
+
2721
+ struct HfCand { // a candidate (hfield frame): the core point x = a + t d, its prism point x - (dist + r) n
2722
+ float dist, n[3], t; // t: the core parameter (0 .. 1 from axis end -1 to +1)
2723
+ int type;
2724
+ unsigned pid; // ((cell r ncol + c) << 1 | triangle) << 4 | the candidate's index in its prism (hf_prism's sub)
2725
+ };
2726
+ struct HfCon { // a chosen contact (hfield frame): pos midway between the prism point q and the geom's surface
2727
+ float dist, pos[3], n[3], q[3], t;
2728
+ int type;
2729
+ unsigned pid;
2730
+ };
2731
+
2732
+ __device__ __forceinline__ void hf_mtv3(const float* R, const float* v, float* o) { // R^T v (R row major)
2733
+ #pragma unroll
2734
+ for (int k = 0; k < 3; k++) o[k] = RFMA(R[6 + k], v[2], RFMA(R[k], v[0], RMUL(R[3 + k], v[1])));
2735
+ }
2736
+ __device__ __forceinline__ void hf_mv3(const float* R, const float* v, float* o) { // R v
2737
+ #pragma unroll
2738
+ for (int k = 0; k < 3; k++) o[k] = dot3_rn(R + 3 * k, v);
2739
+ }
2740
+
2741
+ // segment p1 + s d1 against segment p2 + t d2 (s, t in [0, 1]; Ericson, Real-Time Collision Detection 5.1.9)
2742
+ __device__ __forceinline__ void hf_segseg(const float* p1, const float* d1, const float* p2, const float* d2, float* s,
2743
+ float* t) {
2744
+ const float r[3] = {RSUB(p1[0], p2[0]), RSUB(p1[1], p2[1]), RSUB(p1[2], p2[2])};
2745
+ const float a = dot3_rn(d1, d1), e = dot3_rn(d2, d2), f = dot3_rn(d2, r);
2746
+ if (a <= 1e-20f) { *s = 0.f; *t = e > 1e-20f ? fminf(fmaxf(f / e, 0.f), 1.f) : 0.f; return; }
2747
+ const float c = dot3_rn(d1, r);
2748
+ if (e <= 1e-20f) { *t = 0.f; *s = fminf(fmaxf(-c / a, 0.f), 1.f); return; }
2749
+ const float b = dot3_rn(d1, d2), den = RFMS(b, b, RMUL(a, e)); // a e - b b
2750
+ *s = den > 0.f ? fminf(fmaxf(RFMS(c, e, RMUL(b, f)) / den, 0.f), 1.f) : 0.f; // (b f - c e) / den
2751
+ *t = RFMA(b, *s, f) / e;
2752
+ if (*t < 0.f) { *t = 0.f; *s = fminf(fmaxf(-c / a, 0.f), 1.f); }
2753
+ else if (*t > 1.f) { *t = 1.f; *s = fminf(fmaxf(RSUB(b, c) / a, 0.f), 1.f); }
2754
+ }
2755
+
2756
+ // the candidates of the core a + t d (t in [0, 1]; d = 0: a sphere) with radius r against the prism of top vertices
2757
+ // v[0..2] (counterclockwise from above) and bottom zb, hfield frame: emit(type, dist, n, t, sub) for each, sub its index
2758
+ // in the prism (2 face + end, 10 the edge / vertex pair, 11 the intersection)
2759
+ template <class E>
2760
+ __device__ __forceinline__ void hf_prism(const float (*v)[3], float zb, const float* a, const float* d, float r,
2761
+ E& emit) {
2762
+ float P[6][3]; // 0..2 top, 3..5 bottom
2763
+ #pragma unroll
2764
+ for (int i = 0; i < 3; i++)
2765
+ #pragma unroll
2766
+ for (int k = 0; k < 3; k++) { P[i][k] = v[i][k]; P[3 + i][k] = k == 2 ? zb : v[i][k]; }
2767
+ // faces: 0 top (P0 P1 P2), 1 bottom (P3 P5 P4), 2..4 sides (Pi Pj P3+j P3+i), outward normals
2768
+ const int fv[5][4] = {{0, 1, 2, -1}, {3, 5, 4, -1}, {0, 3, 4, 1}, {1, 4, 5, 2}, {2, 5, 3, 0}};
2769
+ const int ev[9][2] = {{0, 1}, {1, 2}, {2, 0}, {3, 4}, {4, 5}, {5, 3}, {0, 3}, {1, 4}, {2, 5}};
2770
+ float fn[5][3], hA[5], hd[5]; // normal; h(t) = hA + t hd
2771
+ #pragma unroll
2772
+ for (int f = 0; f < 5; f++) {
2773
+ const float *p0 = P[fv[f][0]], *p1 = P[fv[f][1]], *p2 = P[fv[f][2]];
2774
+ float e1[3], e2[3], w[3];
2775
+ #pragma unroll
2776
+ for (int k = 0; k < 3; k++) { e1[k] = RSUB(p1[k], p0[k]); e2[k] = RSUB(p2[k], p0[k]); w[k] = RSUB(a[k], p0[k]); }
2777
+ cross_rn(e1, e2, fn[f]);
2778
+ const float il = rsqrtf(dot3_rn(fn[f], fn[f]));
2779
+ #pragma unroll
2780
+ for (int k = 0; k < 3; k++) fn[f][k] = RMUL(fn[f][k], il);
2781
+ hA[f] = dot3_rn(fn[f], w); hd[f] = dot3_rn(fn[f], d);
2782
+ }
2783
+ // the core at least r outside a face plane at both ends: the prism (on the inner side of all its face planes) is at
2784
+ // least r away, no candidate (most prisms under a geom's bounding box end here)
2785
+ #pragma unroll
2786
+ for (int f = 0; f < 5; f++)
2787
+ if (fminf(hA[f], RADD(hA[f], hd[f])) >= r) return;
2788
+ // inside test of the core's ends and pierced faces: intersection -> separating axes
2789
+ bool inA = true, inB = true;
2790
+ #pragma unroll
2791
+ for (int f = 0; f < 5; f++) { inA = inA && hA[f] < 0.f; inB = inB && RADD(hA[f], hd[f]) < 0.f; }
2792
+ bool hit = inA || inB;
2793
+ float ti0[5], ti1[5]; // each face's region interval of the core
2794
+ #pragma unroll
2795
+ for (int f = 0; f < 5; f++) {
2796
+ float t0 = 0.f, t1 = 1.f; // (an empty interval stays empty: t0 only grows, t1 only shrinks)
2797
+ const int nv = fv[f][3] < 0 ? 3 : 4;
2798
+ #pragma unroll
2799
+ for (int k = 0; k < 4; k++) {
2800
+ if (k >= nv) break;
2801
+ const float *q0 = P[fv[f][k]], *q1 = P[fv[f][(k + 1) % nv]];
2802
+ float e[3], m[3], w[3];
2803
+ #pragma unroll
2804
+ for (int q = 0; q < 3; q++) { e[q] = RSUB(q1[q], q0[q]); w[q] = RSUB(a[q], q0[q]); }
2805
+ cross_rn(e, fn[f], m); // outward in the face plane
2806
+ const float g0 = dot3_rn(m, w), g1 = dot3_rn(m, d); // inside: g0 + t g1 <= 0
2807
+ if (fabsf(g1) <= 1e-20f) { if (g0 > 0.f) t1 = -1.f; }
2808
+ else if (g1 > 0.f) t1 = fminf(t1, -g0 / g1);
2809
+ else t0 = fmaxf(t0, -g0 / g1);
2810
+ }
2811
+ ti0[f] = t0; ti1[f] = t1;
2812
+ if (t0 <= t1 && RMUL(RFMA(t0, hd[f], hA[f]), RFMA(t1, hd[f], hA[f])) < 0.f) hit = true; // the core pierces f
2813
+ }
2814
+ if (hit) { // minimum translation: axes fn (faces) and normalize(d x edge); push the core out along +u
2815
+ const float dd = dot3_rn(d, d);
2816
+ float best = 3.4e38f, bu[3] = {0.f, 0.f, 1.f};
2817
+ #pragma unroll
2818
+ for (int ax = 0; ax < 14; ax++) {
2819
+ float u[3];
2820
+ if (ax < 5) {
2821
+ #pragma unroll
2822
+ for (int k = 0; k < 3; k++) u[k] = fn[ax][k];
2823
+ } else {
2824
+ const float *q0 = P[ev[ax - 5][0]], *q1 = P[ev[ax - 5][1]];
2825
+ const float e[3] = {RSUB(q1[0], q0[0]), RSUB(q1[1], q0[1]), RSUB(q1[2], q0[2])};
2826
+ cross_rn(d, e, u);
2827
+ const float l2 = dot3_rn(u, u);
2828
+ if (l2 <= RMUL(RMUL(1e-12f, dd), dot3_rn(e, e)) || l2 <= 1e-30f) continue;
2829
+ const float il = rsqrtf(l2);
2830
+ #pragma unroll
2831
+ for (int k = 0; k < 3; k++) u[k] = RMUL(u[k], il);
2832
+ }
2833
+ float pmax = -3.4e38f, pmin = 3.4e38f;
2834
+ #pragma unroll
2835
+ for (int i = 0; i < 6; i++) { const float x = dot3_rn(u, P[i]); pmax = fmaxf(pmax, x); pmin = fminf(pmin, x); }
2836
+ const float sa = dot3_rn(u, a), sb = RADD(sa, dot3_rn(u, d)), smin = fminf(sa, sb), smax = fmaxf(sa, sb);
2837
+ const float pp = RSUB(pmax, smin), pm = RSUB(smax, pmin); // translation along +u, along -u
2838
+ if (pp < best) { best = pp; for (int k = 0; k < 3; k++) bu[k] = u[k]; }
2839
+ if (ax >= 5 && pm < best) { best = pm; for (int k = 0; k < 3; k++) bu[k] = -u[k]; }
2840
+ }
2841
+ const float ud = dot3_rn(bu, d), tol = RMUL(1e-7f, sqrtf(dd));
2842
+ emit(HF_DEEP, RSUB(-best, r), bu, ud > tol ? 0.f : (ud < -tol ? 1.f : 0.5f), 11);
2843
+ return;
2844
+ }
2845
+ // disjoint: the face-region ends in front of their face (exact distances), then the closest edge pair if it is closer
2846
+ float dmin = 3.4e38f;
2847
+ #pragma unroll
2848
+ for (int f = 0; f < 5; f++) {
2849
+ if (ti0[f] > ti1[f]) continue;
2850
+ const float h0 = RFMA(ti0[f], hd[f], hA[f]), h1 = RFMA(ti1[f], hd[f], hA[f]);
2851
+ if (h0 < 0.f) continue; // behind the face (then the whole region part is: no pierce)
2852
+ #pragma unroll
2853
+ for (int e = 0; e < 2; e++) {
2854
+ if (e == 1 && !(ti1[f] > ti0[f])) break;
2855
+ const float t = e ? ti1[f] : ti0[f], h = e ? h1 : h0;
2856
+ dmin = fminf(dmin, h);
2857
+ if (RSUB(h, r) >= 0.f) continue;
2858
+ emit(HF_FACE, RSUB(h, r), fn[f], t, 2 * f + e);
2859
+ }
2860
+ }
2861
+ float bd = 3.4e38f, bx[3] = {0.f, 0.f, 0.f}, bq[3] = {0.f, 0.f, 0.f}, bt = 0.f;
2862
+ #pragma unroll
2863
+ for (int i = 0; i < 9; i++) {
2864
+ const float *q0 = P[ev[i][0]], *q1 = P[ev[i][1]];
2865
+ const float e[3] = {RSUB(q1[0], q0[0]), RSUB(q1[1], q0[1]), RSUB(q1[2], q0[2])};
2866
+ float s, t, x[3], q[3], w[3];
2867
+ hf_segseg(a, d, q0, e, &s, &t);
2868
+ #pragma unroll
2869
+ for (int k = 0; k < 3; k++) { x[k] = RFMA(s, d[k], a[k]); q[k] = RFMA(t, e[k], q0[k]); w[k] = RSUB(x[k], q[k]); }
2870
+ const float dd = dot3_rn(w, w);
2871
+ if (dd < bd) { bd = dd; bt = s; for (int k = 0; k < 3; k++) { bx[k] = x[k]; bq[k] = q[k]; } }
2872
+ }
2873
+ bd = sqrtf(bd);
2874
+ if (bd < dmin && RSUB(bd, r) < 0.f && bd > 0.f) {
2875
+ const float n[3] = {RSUB(bx[0], bq[0]) / bd, RSUB(bx[1], bq[1]) / bd, RSUB(bx[2], bq[2]) / bd};
2876
+ emit(HF_POINT, RSUB(bd, r), n, bt, 10);
2877
+ }
2878
+ }
2879
+
2880
+ // the forward's candidate list (local memory): every candidate, tagged with its prism
2881
+ struct HfEmitAll {
2882
+ HfCand* cand;
2883
+ int nc, over;
2884
+ unsigned tag;
2885
+ __device__ __forceinline__ void operator()(int type, float dist, const float* n, float t, int sub) {
2886
+ if (nc >= HF_MAXCAND) { over = 1; return; }
2887
+ HfCand& c = cand[nc++];
2888
+ c.dist = dist; c.t = t; c.type = type; c.pid = tag | (unsigned)sub;
2889
+ for (int k = 0; k < 3; k++) c.n[k] = n[k];
2890
+ }
2891
+ };
2892
+ // the replay's: the candidate with index want in its prism
2893
+ struct HfEmitOne {
2894
+ int want;
2895
+ bool found;
2896
+ HfCand c;
2897
+ __device__ __forceinline__ void operator()(int type, float dist, const float* n, float t, int sub) {
2898
+ if (sub != want) return;
2899
+ found = true;
2900
+ c.dist = dist; c.t = t; c.type = type;
2901
+ for (int k = 0; k < 3; k++) c.n[k] = n[k];
2902
+ }
2903
+ };
2904
+
2905
+ // grid coordinate (x of column c, y of row c) of a heightfield: d c - hs
2906
+ __device__ __forceinline__ float hf_grid(float d, int c, float hs) { return RFMA(d, float(c), -hs); }
2907
+
2908
+ // the four corners of cell (rr, cc) (columns cc - 1 .. cc, rows rr .. rr + 1): k[0] (cc-1, rr), k[1] (cc, rr),
2909
+ // k[2] (cc-1, rr+1), k[3] (cc, rr+1), hfield frame
2910
+ __device__ __forceinline__ void hf_cell(const float* hs, const float* hd, int ncol, float dx, float dy, int rr, int cc,
2911
+ float (*k)[3]) {
2912
+ const float x0 = hf_grid(dx, cc - 1, hs[0]), x1 = hf_grid(dx, cc, hs[0]);
2913
+ const float y0 = hf_grid(dy, rr, hs[1]), y1 = hf_grid(dy, rr + 1, hs[1]);
2914
+ k[0][0] = x0; k[0][1] = y0; k[0][2] = RMUL(hd[rr * ncol + cc - 1], hs[2]);
2915
+ k[1][0] = x1; k[1][1] = y0; k[1][2] = RMUL(hd[rr * ncol + cc], hs[2]);
2916
+ k[2][0] = x0; k[2][1] = y1; k[2][2] = RMUL(hd[(rr + 1) * ncol + cc - 1], hs[2]);
2917
+ k[3][0] = x1; k[3][1] = y1; k[3][2] = RMUL(hd[(rr + 1) * ncol + cc], hs[2]);
2918
+ }
2919
+
2920
+ // top vertices of the cell's triangle i, counterclockwise from above (MuJoCo Warp's strip triangles (cc-1, rr)
2921
+ // (cc-1, rr+1) (cc, rr) and (cc-1, rr+1) (cc, rr) (cc, rr+1)): 0: k0 k1 k2, 1: k2 k1 k3; false where the prism is below
2922
+ // zmin (MuJoCo's prism height test)
2923
+ __device__ __forceinline__ bool hf_tri(const float (*k)[3], int i, float zmin, float (*v)[3]) {
2924
+ #pragma unroll
2925
+ for (int q = 0; q < 3; q++) { v[0][q] = i ? k[2][q] : k[0][q]; v[1][q] = k[1][q]; v[2][q] = i ? k[3][q] : k[2][q]; }
2926
+ return !(v[0][2] < zmin && v[1][2] < zmin && v[2][2] < zmin);
2927
+ }
2928
+
2929
+ // distance from p to triangle (a, b, c) (Ericson, Real-Time Collision Detection 5.1.5)
2930
+ __device__ float hf_pt_tri(const float* p, const float* a, const float* b, const float* c);
2931
+
2932
+ // distance from p to the heightfield surface where it is below reach: the top triangles of cells rmin .. rmax - 1,
2933
+ // cmin .. cmax - 1 (cell (r, c) between columns c, c + 1) within reach of p horizontally (a triangle nearer than reach
2934
+ // is in one of them; the others are not visited), hfield frame; >= reach if none is nearer
2935
+ __device__ float hf_surf_dist(const float* p, float reach, int rmin, int rmax, int cmin, int cmax, float dx, float dy,
2936
+ const float* hs, const float* hd, int ncol) {
2937
+ float best = 3.4e38f;
2938
+ const float pad = reach + 1e-4f;
2939
+ const int c0 = max(cmin, int(floorf((p[0] - pad + hs[0]) / dx))), c1 = min(cmax - 1, int(floorf((p[0] + pad + hs[0]) / dx)));
2940
+ const int r0 = max(rmin, int(floorf((p[1] - pad + hs[1]) / dy))), r1 = min(rmax - 1, int(floorf((p[1] + pad + hs[1]) / dy)));
2941
+ for (int rr = r0; rr <= r1; rr++)
2942
+ for (int cc = c0; cc <= c1; cc++) {
2943
+ float k[4][3];
2944
+ hf_cell(hs, hd, ncol, dx, dy, rr, cc + 1, k); // (the prisms' own vertices)
2945
+ best = fminf(best, fminf(hf_pt_tri(p, k[0], k[1], k[2]), hf_pt_tri(p, k[2], k[1], k[3])));
2946
+ }
2947
+ return best;
2948
+ }
2949
+
2950
+ __device__ float hf_pt_tri(const float* p, const float* a, const float* b, const float* c) {
2951
+ float ab[3], ac[3], ap[3], q[3];
2952
+ for (int k = 0; k < 3; k++) { ab[k] = b[k] - a[k]; ac[k] = c[k] - a[k]; ap[k] = p[k] - a[k]; }
2953
+ float d1 = dot3(ab, ap), d2 = dot3(ac, ap);
2954
+ if (d1 <= 0.f && d2 <= 0.f) { for (int k = 0; k < 3; k++) q[k] = a[k]; }
2955
+ else {
2956
+ float bp[3] = {p[0] - b[0], p[1] - b[1], p[2] - b[2]}, d3 = dot3(ab, bp), d4 = dot3(ac, bp);
2957
+ float cp[3] = {p[0] - c[0], p[1] - c[1], p[2] - c[2]}, d5 = dot3(ab, cp), d6 = dot3(ac, cp);
2958
+ float vc = d1 * d4 - d3 * d2, vb = d5 * d2 - d1 * d6, va = d3 * d6 - d5 * d4;
2959
+ if (d3 >= 0.f && d4 <= d3) { for (int k = 0; k < 3; k++) q[k] = b[k]; }
2960
+ else if (d6 >= 0.f && d5 <= d6) { for (int k = 0; k < 3; k++) q[k] = c[k]; }
2961
+ else if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f) { float v = d1 / (d1 - d3); for (int k = 0; k < 3; k++) q[k] = a[k] + v * ab[k]; }
2962
+ else if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f) { float w = d2 / (d2 - d6); for (int k = 0; k < 3; k++) q[k] = a[k] + w * ac[k]; }
2963
+ else if (va <= 0.f && (d4 - d3) >= 0.f && (d5 - d6) >= 0.f) {
2964
+ float w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
2965
+ for (int k = 0; k < 3; k++) q[k] = b[k] + w * (c[k] - b[k]);
2966
+ } else {
2967
+ float den = 1.f / (va + vb + vc), v = vb * den, w = vc * den;
2968
+ for (int k = 0; k < 3; k++) q[k] = a[k] + v * ab[k] + w * ac[k];
2969
+ }
2970
+ }
2971
+ float w[3] = {p[0] - q[0], p[1] - q[1], p[2] - q[2]};
2972
+ return sqrtf(dot3(w, w));
2973
+ }
2974
+
2975
+ // add_contact (step.py) returning the contact's index (-1 beyond MAXCON): the native contacts tape their candidate
2976
+ template <class S>
2977
+ __device__ __forceinline__ int add_contact_aux(S& s, int pair, int slot, float dist, const float* pos,
2978
+ const float* frame) {
2979
+ int c = atomicAdd(&s.ncon, 1);
2980
+ if (c >= MAXCON) return -1;
2981
+ s.con_pair[c] = pair;
2982
+ s.con_slot[c] = (unsigned char)(slot & 255);
2983
+ s.con_elem[c] = (unsigned short)(slot >> 8);
2984
+ s.con_dim[c] = PDIM(pair);
2985
+ s.con_dist[c] = dist;
2986
+ for (int k = 0; k < 3; k++) s.con_pos[c][k] = pos[k];
2987
+ for (int k = 0; k < 9; k++) s.con_frame[c][k] = frame[k];
2988
+ s.con_mu[c] = PFOOT(pair) ? s.fric : PMU(pair);
2989
+ return c;
2990
+ }
2991
+
2992
+ // the geom's core in the frame of heightfield hh (g_ter.hfh + 16 j): a + t d (t in [0, 1]), and its bounding box
2993
+ // lo .. hi (with the radius)
2994
+ __device__ __forceinline__ void hf_core(const float* hh, int gt, const float* sz, const float* gp, const float* gq,
2995
+ float* a, float* d, float* lo, float* hi) {
2996
+ const float dw[3] = {RSUB(gp[0], hh[0]), RSUB(gp[1], hh[1]), RSUB(gp[2], hh[2])};
2997
+ float c[3], ax[3] = {0.f, 0.f, 0.f};
2998
+ hf_mtv3(hh + 3, dw, c);
2999
+ const float r = sz[0], hl = gt == 2 ? sz[1] : 0.f;
3000
+ if (gt == 2) { float aw[3]; zaxis_rn(gq, aw); hf_mtv3(hh + 3, aw, ax); }
3001
+ #pragma unroll
3002
+ for (int k = 0; k < 3; k++) {
3003
+ const float e = RFMA(fabsf(ax[k]), hl, r);
3004
+ lo[k] = RSUB(c[k], e); hi[k] = RADD(c[k], e);
3005
+ a[k] = RFMS(hl, ax[k], c[k]); d[k] = RMUL(2.f * hl, ax[k]);
3006
+ }
3007
+ }
3008
+
3009
+ // a chosen candidate as a contact (hfield frame)
3010
+ __device__ __forceinline__ void hf_con_of(const HfCand& c, const float* a, const float* d, float r, HfCon* o) {
3011
+ o->dist = c.dist; o->t = c.t; o->type = c.type; o->pid = c.pid;
3012
+ const float s = RFMA(0.5f, c.dist, r), h = RADD(c.dist, r);
3013
+ #pragma unroll
3014
+ for (int q = 0; q < 3; q++) {
3015
+ const float x = RFMA(c.t, d[q], a[q]);
3016
+ o->pos[q] = RFMS(s, c.n[q], x); o->n[q] = c.n[q]; o->q[q] = RFMS(h, c.n[q], x);
3017
+ }
3018
+ }
3019
+ // a candidate's contact position (hfield frame): midway between its prism point and the geom's surface (hf_con_of's)
3020
+ __device__ __forceinline__ void hf_pos(const HfCand& c, const float* a, const float* d, float r, float* pos) {
3021
+ const float s = RFMA(0.5f, c.dist, r);
3022
+ #pragma unroll
3023
+ for (int q = 0; q < 3; q++) pos[q] = RFMS(s, c.n[q], RFMA(c.t, d[q], a[q]));
3024
+ }
3025
+ // a contact's point (hfield frame) in the world: R p + pos of heightfield hh
3026
+ __device__ __forceinline__ void hf_world_point(const float* hh, const float* p, float* o) {
3027
+ hf_mv3(hh + 3, p, o);
3028
+ #pragma unroll
3029
+ for (int k = 0; k < 3; k++) o[k] = RADD(o[k], hh[k]);
3030
+ }
3031
+
3032
+ // the native contacts of robot geom (type gt, size sz, pose gp / gq) and heightfield j: out[0..n-1] in MuJoCo's order
3033
+ // (deepest, farthest, ...; hfield frame), returns n (0..4); *over: candidates beyond HF_MAXCAND were dropped
3034
+ __device__ __noinline__ int hfield_native(int j, int gt, const float* sz, const float* gp, const float* gq,
3035
+ HfCon* out, int* over) {
3036
+ const float* hh = g_ter.hfh + 16 * j;
3037
+ const int* hi = g_ter.hfi + 4 * j;
3038
+ const float *hs = hh + 12, *hd = g_ter.hfd + hi[2];
3039
+ const int nrow = hi[0], ncol = hi[1];
3040
+ const float r = sz[0];
3041
+ float a[3], d[3], lo[3], hi3[3];
3042
+ hf_core(hh, gt, sz, gp, gq, a, d, lo, hi3);
3043
+ *over = 0;
3044
+ if (lo[0] > hs[0] || hi3[0] < -hs[0] || lo[1] > hs[1] || hi3[1] < -hs[1] || lo[2] > hs[2] || hi3[2] < -hs[3])
3045
+ return 0;
3046
+ const float xs = 0.5f * float(ncol - 1) / hs[0], ys = 0.5f * float(nrow - 1) / hs[1];
3047
+ const int cmin = max(0, int(floorf((lo[0] + hs[0]) * xs))), cmax = min(ncol - 1, int(ceilf((hi3[0] + hs[0]) * xs)));
3048
+ const int rmin = max(0, int(floorf((lo[1] + hs[1]) * ys))), rmax = min(nrow - 1, int(ceilf((hi3[1] + hs[1]) * ys)));
3049
+ const float dx = 2.f * hs[0] / float(ncol - 1), dy = 2.f * hs[1] / float(nrow - 1);
3050
+ HfCand cand[HF_MAXCAND];
3051
+ HfEmitAll em{cand, 0, 0, 0u};
3052
+ for (int rr = rmin; rr < rmax; rr++)
3053
+ for (int cc = cmin + 1; cc <= cmax; cc++) {
3054
+ float k[4][3];
3055
+ hf_cell(hs, hd, ncol, dx, dy, rr, cc, k);
3056
+ #pragma unroll 1
3057
+ for (int i = 0; i < 2; i++) {
3058
+ float v[3][3];
3059
+ if (!hf_tri(k, i, lo[2], v)) continue;
3060
+ em.tag = (unsigned)((rr * ncol + cc) << 1 | i) << 4;
3061
+ hf_prism(v, -hs[3], a, d, r, em);
3062
+ }
3063
+ }
3064
+ *over = em.over;
3065
+ int nc = em.nc;
3066
+ // keep the candidates whose prism point is a closest point of the heightfield surface (the prisms' top triangles):
3067
+ // a prism's own edge next to a neighbouring triangle (an edge inside a flat or concave part of the surface) gives a
3068
+ // farther point than that triangle and is dropped; convex ridges and peaks stay. A candidate inside the core
3069
+ // (0 < t < 1: a face-region end at a triangle boundary, an edge point) stays only where the core's distance to the
3070
+ // surface has a local minimum: the surface 0.5 mm along the core on either side is not closer (a ridge under the
3071
+ // core; on a plane only the core's ends stay, as the plane's contacts). Penetrating cores (HF_DEEP) stay
3072
+ const float dl = sqrtf(dot3(d, d));
3073
+ int nk = 0;
3074
+ for (int i = 0; i < nc; i++) {
3075
+ const HfCand& ci = cand[i];
3076
+ bool keep = true;
3077
+ if (ci.type != HF_DEEP) {
3078
+ float x[3], h = ci.dist + r; // the core point and its distance to the candidate's prism
3079
+ for (int k = 0; k < 3; k++) x[k] = a[k] + ci.t * d[k];
3080
+ keep = hf_surf_dist(x, h, rmin, rmax, cmin, cmax, dx, dy, hs, hd, ncol) >= h - 1e-6f;
3081
+ if (keep && ci.t > 0.f && ci.t < 1.f) // inside the core: a local minimum of the distance along it
3082
+ for (int sg = -1; sg <= 1 && keep; sg += 2) {
3083
+ float tb = fminf(fmaxf(ci.t + float(sg) * 5e-4f / fmaxf(dl, 1e-6f), 0.f), 1.f), xb[3];
3084
+ for (int k = 0; k < 3; k++) xb[k] = a[k] + tb * d[k];
3085
+ keep = hf_surf_dist(xb, h, rmin, rmax, cmin, cmax, dx, dy, hs, hd, ncol) >= h - 1e-8f;
3086
+ }
3087
+ }
3088
+ if (keep) cand[nk++] = cand[i];
3089
+ }
3090
+ nc = nk;
3091
+ if (nc == 0) return 0;
3092
+ // MuJoCo's choice (ccd_hfield_kernel): the deepest, the farthest from it, the farthest from their line, the fourth
3093
+ int id0 = 0;
3094
+ for (int i = 1; i < nc; i++) if (cand[i].dist < cand[id0].dist) id0 = i;
3095
+ float p0[3], p1[3], p2[3], pi[3];
3096
+ hf_pos(cand[id0], a, d, r, p0);
3097
+ int ids[4] = {id0, -1, -1, -1}, n = 1;
3098
+ float best = -1.f;
3099
+ for (int i = 0; i < nc; i++) {
3100
+ if (i == id0) continue;
3101
+ hf_pos(cand[i], a, d, r, pi);
3102
+ float w[3] = {pi[0] - p0[0], pi[1] - p0[1], pi[2] - p0[2]}, l = sqrtf(dot3(w, w));
3103
+ if (l > best) { best = l; ids[1] = i; }
3104
+ }
3105
+ if (ids[1] >= 0 && best >= HF_MIN_NEXT) {
3106
+ n = 2;
3107
+ hf_pos(cand[ids[1]], a, d, r, p1);
3108
+ const float* n0 = cand[id0].n;
3109
+ float l01[3], w01[3] = {p0[0] - p1[0], p0[1] - p1[1], p0[2] - p1[2]};
3110
+ cross(n0, w01, l01);
3111
+ best = -1.f;
3112
+ for (int i = 0; i < nc; i++) {
3113
+ if (i == id0 || i == ids[1]) continue;
3114
+ hf_pos(cand[i], a, d, r, pi);
3115
+ float w[3] = {pi[0] - p0[0], pi[1] - p0[1], pi[2] - p0[2]}, l = fabsf(dot3(w, l01));
3116
+ if (l > best) { best = l; ids[2] = i; }
3117
+ }
3118
+ if (ids[2] >= 0 && best >= HF_MIN_NEXT) {
3119
+ n = 3;
3120
+ hf_pos(cand[ids[2]], a, d, r, p2);
3121
+ float m2[3], m12[3], w02[3] = {p0[0] - p2[0], p0[1] - p2[1], p0[2] - p2[2]},
3122
+ w12[3] = {p1[0] - p2[0], p1[1] - p2[1], p1[2] - p2[2]};
3123
+ cross(n0, w02, m2);
3124
+ cross(n0, w12, m12);
3125
+ best = -1.f;
3126
+ for (int i = 0; i < nc; i++) {
3127
+ if (i == id0 || i == ids[1] || i == ids[2]) continue;
3128
+ hf_pos(cand[i], a, d, r, pi);
3129
+ float w[3] = {pi[0] - p0[0], pi[1] - p0[1], pi[2] - p0[2]};
3130
+ float u[3] = {p1[0] - pi[0], p1[1] - pi[1], p1[2] - pi[2]};
3131
+ float l = fabsf(dot3(w, m2)) + fabsf(dot3(u, m12));
3132
+ if (l > best) { best = l; ids[3] = i; }
3133
+ }
3134
+ if (ids[3] >= 0 && best >= HF_MIN_NEXT) n = 4;
3135
+ }
3136
+ }
3137
+ for (int k = 0; k < n; k++) hf_con_of(cand[ids[k]], a, d, r, out + k);
3138
+ return n;
3139
+ }
3140
+
3141
+ // the adjoint's replay of a native contact: the candidate pid of geom (gt, sz, gp, gq) and heightfield j, recomputed
3142
+ // from its prism alone (the forward's bits: the same explicitly rounded functions)
3143
+ __device__ __noinline__ bool hfield_native_one(int j, int gt, const float* sz, const float* gp, const float* gq,
3144
+ unsigned pid, HfCon* o) {
3145
+ const float* hh = g_ter.hfh + 16 * j;
3146
+ const int* hi = g_ter.hfi + 4 * j;
3147
+ const float *hs = hh + 12, *hd = g_ter.hfd + hi[2];
3148
+ const int nrow = hi[0], ncol = hi[1];
3149
+ const float dx = 2.f * hs[0] / float(ncol - 1), dy = 2.f * hs[1] / float(nrow - 1);
3150
+ float a[3], d[3], lo[3], hi3[3], k[4][3], v[3][3];
3151
+ hf_core(hh, gt, sz, gp, gq, a, d, lo, hi3);
3152
+ const int cell = (int)(pid >> 5), rr = cell / ncol, cc = cell - rr * ncol, i = (int)((pid >> 4) & 1u);
3153
+ hf_cell(hs, hd, ncol, dx, dy, rr, cc, k);
3154
+ if (!hf_tri(k, i, lo[2], v)) return false;
3155
+ HfEmitOne em;
3156
+ em.want = (int)(pid & 15u);
3157
+ em.found = false;
3158
+ hf_prism(v, -hs[3], a, d, sz[0], em);
3159
+ if (!em.found) return false;
3160
+ em.c.pid = pid;
3161
+ hf_con_of(em.c, a, d, sz[0], o);
3162
+ return true;
3163
+ }
3164
+ #endif // TERRAIN_HF_NATIVE
3165
+
3166
+ // ---- height scan (torch_ffi.raycast): rays against the terrain, MuJoCo Warp's ray_box / ray_hfield (ray.py) ----
3167
+ #define TR_MINVAL 1e-15f // mjMINVAL
3168
+ __device__ __forceinline__ float tr_div(float x, float y) { return x / (y != 0.f ? y : TR_MINVAL); }
3169
+
3170
+ // _ray_quad: the first non-negative solution of a x^2 + 2 b x + c = 0, else -1
3171
+ __device__ __forceinline__ float tr_quad(float a, float b, float c) {
3172
+ float det = b * b - a * c;
3173
+ if (det < TR_MINVAL) return -1.f;
3174
+ det = sqrtf(det);
3175
+ const float den = tr_div(1.f, a), x0 = (-b - det) * den, x1 = (-b + det) * den;
3176
+ return x0 >= 0.f ? x0 : (x1 >= 0.f ? x1 : -1.f);
3177
+ }
3178
+
3179
+ // ray_box: box at pos with rotation R (row major) and half sizes sz; all[6]: per side solutions (or -1), nrm: world
3180
+ __device__ float tr_box(const float* pos, const float* R, const float* sz, const float* pnt, const float* vec, float* all,
3181
+ float* nrm) {
3182
+ for (int i = 0; i < 6; i++) all[i] = -1.f;
3183
+ for (int k = 0; k < 3; k++) nrm[k] = 0.f;
3184
+ float dif[3] = {pnt[0] - pos[0], pnt[1] - pos[1], pnt[2] - pos[2]};
3185
+ if (tr_quad(dot3(vec, vec), dot3(vec, dif), dot3(dif, dif) - dot3(sz, sz)) < 0.f) return -1.f; // bounding sphere
3186
+ float lp[3], lv[3];
3187
+ mtv3(R, dif, lp);
3188
+ mtv3(R, vec, lv);
3189
+ float x = -1.f;
3190
+ int fa = -1, fs = -1;
3191
+ for (int i = 0; i < 3; i++) {
3192
+ if (!(fabsf(lv[i]) > TR_MINVAL)) continue;
3193
+ for (int side = -1; side < 2; side += 2) {
3194
+ const float sol = (float(side) * sz[i] - lp[i]) / lv[i];
3195
+ if (sol >= 0.f) {
3196
+ const int i0 = i == 0 ? 1 : 0, i1 = i == 2 ? 1 : 2;
3197
+ const float p0 = lp[i0] + sol * lv[i0], p1 = lp[i1] + sol * lv[i1];
3198
+ if (fabsf(p0) <= sz[i0] && fabsf(p1) <= sz[i1]) {
3199
+ if (x < 0.f || sol < x) { x = sol; fa = i; fs = side; }
3200
+ all[2 * i + (side + 1) / 2] = sol;
3201
+ }
3202
+ }
3203
+ }
3204
+ }
3205
+ if (x >= 0.f) {
3206
+ float nl[3] = {0.f, 0.f, 0.f};
3207
+ nl[fa] = float(fs);
3208
+ mv3(R, nl, nrm);
3209
+ }
3210
+ return x;
3211
+ }
3212
+
3213
+ // _ray_triangle (local frame; b0, b1: _orthogonal_basis of the ray direction)
3214
+ __device__ float tr_tri(const float* v0, const float* v1, const float* v2, const float* pnt, const float* vec,
3215
+ const float* b0, const float* b1, float* nrm) {
3216
+ float d0[3], d1[3], d2[3];
3217
+ for (int k = 0; k < 3; k++) { d0[k] = v0[k] - pnt[k]; d1[k] = v1[k] - pnt[k]; d2[k] = v2[k] - pnt[k]; }
3218
+ const float p00 = dot3(d0, b0), p01 = dot3(d0, b1), p10 = dot3(d1, b0), p11 = dot3(d1, b1), p20 = dot3(d2, b0),
3219
+ p21 = dot3(d2, b1);
3220
+ if ((p00 > 0.f && p10 > 0.f && p20 > 0.f) || (p00 < 0.f && p10 < 0.f && p20 < 0.f) ||
3221
+ (p01 > 0.f && p11 > 0.f && p21 > 0.f) || (p01 < 0.f && p11 < 0.f && p21 < 0.f))
3222
+ return -1.f;
3223
+ const float A00 = p00 - p20, A10 = p10 - p20, A01 = p01 - p21, A11 = p11 - p21, bb0 = -p20, bb1 = -p21;
3224
+ const float det = A00 * A11 - A10 * A01;
3225
+ if (fabsf(det) < TR_MINVAL) return -1.f;
3226
+ const float t0 = (A11 * bb0 - A10 * bb1) / det, t1 = (-A01 * bb0 + A00 * bb1) / det;
3227
+ if (t0 < 0.f || t1 < 0.f || t0 + t1 > 1.f) return -1.f;
3228
+ float e0[3], e1[3], e2[3], n[3];
3229
+ for (int k = 0; k < 3; k++) { e0[k] = v0[k] - v2[k]; e1[k] = v1[k] - v2[k]; e2[k] = pnt[k] - v2[k]; }
3230
+ cross(e0, e1, n);
3231
+ const float den = dot3(vec, n);
3232
+ if (fabsf(den) < TR_MINVAL) return -1.f;
3233
+ const float dist = -dot3(e2, n) / den, il = rsqrtf(dot3(n, n));
3234
+ for (int k = 0; k < 3; k++) nrm[k] = n[k] * il;
3235
+ return dist >= 0.f ? dist : -1.f;
3236
+ }
3237
+
3238
+ // ray_hfield: terrain heightfield j (the base box, the top box, the triangles under the ray's part in the top box,
3239
+ // split along the (c, r)-(c+1, r+1) diagonal as MuJoCo Warp's rays, and the top box's sides under the boundary heights)
3240
+ __device__ float tr_hfield(int j, const float* pnt, const float* vec, float* nrm) {
3241
+ const float* hh = g_ter.hfh + 16 * j;
3242
+ const int* hi = g_ter.hfi + 4 * j;
3243
+ const float *pos = hh, *R = hh + 3, *size = hh + 12, *hd = g_ter.hfd + hi[2];
3244
+ const int nrow = hi[0], ncol = hi[1];
3245
+ const float col[3] = {R[2], R[5], R[8]};
3246
+ const float bs = size[3] * 0.5f, ts = size[2] * 0.5f;
3247
+ float bsz[3] = {size[0], size[1], bs}, tsz[3] = {size[0], size[1], ts}, bpos[3], tpos[3], allb[6], all[6], nb[3],
3248
+ nt[3];
3249
+ for (int k = 0; k < 3; k++) { bpos[k] = pos[k] - col[k] * bs; tpos[k] = pos[k] + col[k] * ts; }
3250
+ float x = tr_box(bpos, R, bsz, pnt, vec, allb, nb);
3251
+ const float top = tr_box(tpos, R, tsz, pnt, vec, all, nt);
3252
+ if (top < 0.f) { for (int k = 0; k < 3; k++) nrm[k] = nb[k]; return x; }
3253
+ float dif[3] = {pnt[0] - pos[0], pnt[1] - pos[1], pnt[2] - pos[2]}, lp[3], lv[3];
3254
+ mtv3(R, dif, lp);
3255
+ mtv3(R, vec, lv);
3256
+ const float sg = lv[2] >= 0.f ? 1.f : -1.f, a = -1.f / (sg + lv[2]), b = lv[0] * lv[1] * a;
3257
+ const float b0[3] = {1.f + sg * lv[0] * lv[0] * a, sg * b, -sg * lv[0]}, b1[3] = {b, sg + lv[1] * lv[1] * a, -lv[1]};
3258
+ float s0 = 0.f, s1 = top;
3259
+ for (int i = 0; i < 6; i++)
3260
+ if (all[i] > s1) { s0 = top; s1 = all[i]; }
3261
+ const float dx = tr_div(2.f * size[0], float(ncol - 1)), dy = tr_div(2.f * size[1], float(nrow - 1));
3262
+ const float SX0 = tr_div(lp[0] + s0 * lv[0] + size[0], dx), SX1 = tr_div(lp[0] + s1 * lv[0] + size[0], dx);
3263
+ const float SY0 = tr_div(lp[1] + s0 * lv[1] + size[1], dy), SY1 = tr_div(lp[1] + s1 * lv[1] + size[1], dy);
3264
+ const int cmin = max(0, int(floorf(fminf(SX0, SX1)) - 1.f)), cmax = min(ncol - 1, int(ceilf(fmaxf(SX0, SX1)) + 1.f));
3265
+ const int rmin = max(0, int(floorf(fminf(SY0, SY1)) - 1.f)), rmax = min(nrow - 1, int(ceilf(fmaxf(SY0, SY1)) + 1.f));
3266
+ float nl[3] = {0.f, 0.f, 0.f};
3267
+ if (x >= 0.f) mtv3(R, nb, nl);
3268
+ for (int r = rmin; r < rmax; r++)
3269
+ for (int c = cmin; c < cmax; c++) {
3270
+ const float x0 = dx * float(c) - size[0], x1 = dx * float(c + 1) - size[0];
3271
+ const float y0 = dy * float(r) - size[1], y1 = dy * float(r + 1) - size[1];
3272
+ const float h00 = hd[r * ncol + c] * size[2], h10 = hd[r * ncol + c + 1] * size[2];
3273
+ const float h11 = hd[(r + 1) * ncol + c + 1] * size[2], h01 = hd[(r + 1) * ncol + c] * size[2];
3274
+ const float va[3] = {x0, y0, h00}, vb[3] = {x1, y0, h10}, vc[3] = {x1, y1, h11}, vd[3] = {x0, y1, h01};
3275
+ float nt2[3];
3276
+ float sol = tr_tri(va, vb, vc, lp, lv, b0, b1, nt2);
3277
+ if (sol >= 0.f && (x < 0.f || sol < x)) { x = sol; for (int k = 0; k < 3; k++) nl[k] = nt2[k]; }
3278
+ sol = tr_tri(va, vc, vd, lp, lv, b0, b1, nt2);
3279
+ if (sol >= 0.f && (x < 0.f || sol < x)) { x = sol; for (int k = 0; k < 3; k++) nl[k] = nt2[k]; }
3280
+ }
3281
+ for (int i = 0; i < 4; i++) {
3282
+ if (!(all[i] >= 0.f && (all[i] < x || x < 0.f))) continue;
3283
+ const float z = tr_div(lp[2] + all[i] * lv[2], size[2]);
3284
+ float y, y0, z0, z1;
3285
+ if (i < 2) {
3286
+ y = tr_div(lp[1] + all[i] * lv[1] + size[1], dy);
3287
+ y0 = fmaxf(0.f, fminf(float(nrow - 2), floorf(y)));
3288
+ const int k0 = int(rintf(y0)), k1 = int(rintf(y0 + 1.f));
3289
+ z0 = i == 1 ? hd[k0 * ncol + ncol - 1] : hd[k0 * ncol];
3290
+ z1 = i == 1 ? hd[k1 * ncol + ncol - 1] : hd[k1 * ncol];
3291
+ } else {
3292
+ y = tr_div(lp[0] + all[i] * lv[0] + size[0], dx);
3293
+ y0 = fmaxf(0.f, fminf(float(ncol - 2), floorf(y)));
3294
+ const int k0 = int(rintf(y0)), k1 = int(rintf(y0 + 1.f));
3295
+ z0 = i == 3 ? hd[k0 + (nrow - 1) * ncol] : hd[k0];
3296
+ z1 = i == 3 ? hd[k1 + (nrow - 1) * ncol] : hd[k1];
3297
+ }
3298
+ if (z < z0 * (y0 + 1.f - y) + z1 * (y - y0)) {
3299
+ x = all[i];
3300
+ nl[0] = float(i == 1) - float(i == 0); nl[1] = float(i == 3) - float(i == 2); nl[2] = 0.f;
3301
+ }
3302
+ }
3303
+ if (x >= 0.f) mv3(R, nl, nrm);
3304
+ else for (int k = 0; k < 3; k++) nrm[k] = 0.f;
3305
+ return x;
3306
+ }
3307
+
3308
+ // n rays (origins pnt, unit directions vec, world, 3 floats each) against the terrain: dist (the nearest hit; -1 for
3309
+ // none or beyond maxd) and nrm (its world normal, 0 for none); the elements in the grid cells along the segment
3310
+ // pnt .. pnt + maxd vec, row by row from the origin's: in each grid row, the columns the segment crosses in that row's
3311
+ // band (padded by TR_PAD on every side, so a hit on a cell boundary finds its element), and no further row once the
3312
+ // nearest hit is nearer than the row's entry (a long slanted ray visits about its length in cells, not its bounding
3313
+ // box's area); a heightfield is measured once per ray (tr_hfield walks the whole ray over it, whatever the cell)
3314
+ #define TR_PAD 1e-3f
3315
+ __global__ void k_terrain_rays(int n, const float* pnt, const float* vec, float maxd, float* dist, float* nrm) {
3316
+ const int i = blockIdx.x * blockDim.x + threadIdx.x;
3317
+ if (i >= n) return;
3318
+ const float *p = pnt + 3 * i, *v = vec + 3 * i;
3319
+ float best = -1.f, bn[3] = {0.f, 0.f, 0.f};
3320
+ if (g_ter.grid != nullptr) {
3321
+ const float x0 = g_ter.grid[0], y0 = g_ter.grid[1], ic = g_ter.grid[2], cell = 1.f / ic;
3322
+ const int nx = int(g_ter.grid[3]), ny = int(g_ter.grid[4]), nbox = int(g_ter.grid[5]);
3323
+ const float ey = p[1] + maxd * v[1];
3324
+ const int ra = int(floorf((p[1] - TR_PAD - y0) * ic)), rb = int(floorf((p[1] + TR_PAD - y0) * ic));
3325
+ const int ea = int(floorf((ey - TR_PAD - y0) * ic)), eb = int(floorf((ey + TR_PAD - y0) * ic));
3326
+ unsigned long long hf_seen[2] = {0ull, 0ull};
3327
+ const bool up = v[1] >= 0.f; // rows in the order the ray passes them
3328
+ const int rlo = max(0, min(ra, ea)), rhi = min(ny - 1, max(rb, eb));
3329
+ for (int j = 0; j <= rhi - rlo; j++) {
3330
+ const int r = up ? rlo + j : rhi - j;
3331
+ // the segment's parameters in the padded band of row r, then its x extent there
3332
+ const float yb0 = y0 + float(r) * cell - TR_PAD, yb1 = y0 + float(r + 1) * cell + TR_PAD;
3333
+ float t0 = 0.f, t1 = maxd;
3334
+ if (fabsf(v[1]) > 1e-12f) {
3335
+ float ta = (yb0 - p[1]) / v[1], tb = (yb1 - p[1]) / v[1];
3336
+ t0 = fmaxf(t0, fminf(ta, tb)); t1 = fminf(t1, fmaxf(ta, tb));
3337
+ } else if (p[1] < yb0 || p[1] > yb1) continue;
3338
+ if (t0 > t1) continue;
3339
+ if (best >= 0.f && best < t0) break; // every later row is entered beyond the nearest hit
3340
+ const float xa = p[0] + t0 * v[0], xb = p[0] + t1 * v[0];
3341
+ const int c0 = max(0, int(floorf((fminf(xa, xb) - TR_PAD - x0) * ic)));
3342
+ const int c1 = min(nx - 1, int(floorf((fmaxf(xa, xb) + TR_PAD - x0) * ic)));
3343
+ for (int c = c0; c <= c1; c++)
3344
+ for (int k = g_ter.cstart[r * nx + c]; k < g_ter.cstart[r * nx + c + 1]; k++) {
3345
+ const int e = g_ter.citems[k];
3346
+ float all[6], nn[3], d;
3347
+ if (e < nbox) { const float* b = g_ter.box + 15 * e; d = tr_box(b, b + 3, b + 12, p, v, all, nn); }
3348
+ else { // a heightfield spans many cells: each one is measured once per ray (the first 128 heightfields)
3349
+ const int j = e - nbox;
3350
+ if (j < 128) {
3351
+ const unsigned long long bit = 1ull << (j & 63);
3352
+ if (hf_seen[j >> 6] & bit) continue;
3353
+ hf_seen[j >> 6] |= bit;
3354
+ }
3355
+ d = tr_hfield(j, p, v, nn);
3356
+ }
3357
+ if (d >= 0.f && (best < 0.f || d < best)) { best = d; for (int q = 0; q < 3; q++) bn[q] = nn[q]; }
3358
+ }
3359
+ }
3360
+ }
3361
+ if (best > maxd) best = -1.f;
3362
+ dist[i] = best;
3363
+ for (int q = 0; q < 3; q++) nrm[3 * i + q] = best >= 0.f ? bn[q] : 0.f;
3364
+ }
3365
+
3366
+ // robot geom g against terrain heightfield j (element nbox + j)
3367
+ template <class S>
3368
+ __device__ void terrain_hfield(S& s, int pair, int g, int j, int nbox) {
3369
+ const float* hh = g_ter.hfh + 16 * j;
3370
+ float d[3] = {s.gx[g][0] - hh[0], s.gx[g][1] - hh[1], s.gx[g][2] - hh[2]}, pl[3];
3371
+ mtv3(hh + 3, d, pl);
3372
+ if (pl[2] - c_grbound[g] > hh[14]) return; // above the heightfield's top
3373
+ #if TERRAIN_HF_NATIVE
3374
+ HfCon con[4];
3375
+ int over;
3376
+ const int nn = hfield_native(j, c_gtype[g], c_gsize + 3 * g, s.gx[g], s.gq[g], con, &over);
3377
+ if (over) atomicOr(&s.unsupported, 4); // candidates dropped (counted as a contact overflow)
3378
+ for (int k = 0; k < nn; k++) {
3379
+ float pos[3], nw[3], fr[9];
3380
+ hf_world_point(hh, con[k].pos, pos);
3381
+ hf_mv3(hh + 3, con[k].n, nw);
3382
+ make_frame(nw, fr);
3383
+ const int c = add_contact_aux(s, pair, k | (nbox + j) << 8, con[k].dist, pos, fr);
3384
+ if (c >= 0) s.con_aux[c] = con[k].pid; // the tape's taux: the adjoint replays this prism candidate only
3385
+ }
3386
+ return;
3387
+ #endif
3388
+ const int gt = c_gtype[g], npts = gt == 2 ? TERRAIN_CAP_PTS : 1;
3389
+ for (int k = 0; k < npts; k++) {
3390
+ float dist, pos[3], nw[3], fr[9];
3391
+ if (!terrain_hfield_point(j, gt, c_gsize + 3 * g, s.gx[g], s.gq[g], k, &dist, pos, nw) || dist >= 0.f) continue;
3392
+ make_frame(nw, fr);
3393
+ add_contact(s, pair, k | (nbox + j) << 8, dist, pos, fr);
3394
+ }
3395
+ }
3396
+
3397
+ // permutation of a per-contact array: contact c (lanes c, c - 32) moves to rk[c / 32] (terrain_sort_contacts)
3398
+ template <class T>
3399
+ __device__ __forceinline__ void con_permute(T* a, int ncon, int lane, const int* rk) {
3400
+ const T v0 = a[min(lane, MAXCON - 1)], v1 = a[min(lane + 32, MAXCON - 1)];
3401
+ __syncwarp();
3402
+ if (lane < ncon) a[rk[0]] = v0;
3403
+ if (lane + 32 < ncon) a[rk[1]] = v1;
3404
+ __syncwarp();
3405
+ }
3406
+ template <int K, class T>
3407
+ __device__ __forceinline__ void con_permute_k(T (*a)[K], int ncon, int lane, const int* rk) {
3408
+ for (int k = 0; k < K; k++) {
3409
+ const T v0 = a[min(lane, MAXCON - 1)][k], v1 = a[min(lane + 32, MAXCON - 1)][k];
3410
+ __syncwarp();
3411
+ if (lane < ncon) a[rk[0]][k] = v0;
3412
+ if (lane + 32 < ncon) a[rk[1]][k] = v1;
3413
+ __syncwarp();
3414
+ }
3415
+ }
3416
+
3417
+ // A terrain build's contact order: sorted by (pair, element, slot), ties (one lane's contacts of one pair and element)
3418
+ // in their order of arrival. add_contact takes its slots with atomicAdd from divergent lanes, so the arrival order
3419
+ // depends on the work of the other lanes (e.g. a broad phase that skips more elements): sorted, the order, and hence
3420
+ // the constraint rows and the solver's bits, depend only on the contact set. A stable rank per contact (lanes c and
3421
+ // c + 32), then each per-contact array permuted; nothing moves when the contacts arrived sorted
3422
+ template <class S>
3423
+ __device__ void terrain_sort_contacts(S& s, int ncon, int lane) {
3424
+ #if TERRAIN_SORT
3425
+ __syncwarp();
3426
+ unsigned long long key[2];
3427
+ int rk[2] = {0, 0};
3428
+ #pragma unroll
3429
+ for (int h = 0; h < 2; h++) {
3430
+ const int c = lane + 32 * h;
3431
+ key[h] = c < ncon ? (unsigned long long)s.con_pair[c] << 32 | (unsigned long long)s.con_elem[c] << 8 |
3432
+ (unsigned long long)s.con_slot[c]
3433
+ : ~0ull;
3434
+ }
3435
+ for (int j = 0; j < ncon; j++) {
3436
+ const unsigned long long kj = __shfl_sync(0xffffffffu, j < 32 ? key[0] : key[1], j & 31);
3437
+ #pragma unroll
3438
+ for (int h = 0; h < 2; h++) rk[h] += kj < key[h] || (kj == key[h] && j < lane + 32 * h);
3439
+ }
3440
+ if (!__any_sync(0xffffffffu, (lane < ncon && rk[0] != lane) || (lane + 32 < ncon && rk[1] != lane + 32))) return;
3441
+ if (ncon <= 32) { // (warp-uniform) one contact per lane: every word read, then written at its rank
3442
+ int pr = 0, dm = 0;
3443
+ unsigned char sl = 0;
3444
+ unsigned short el = 0;
3445
+ float di = 0.f, mu = 0.f, ps[3] = {0.f, 0.f, 0.f}, fr[9];
3446
+ #ifdef PW_TORS
3447
+ float mus = 0.f;
3448
+ #endif
3449
+ #if TERRAIN_HF_NATIVE
3450
+ unsigned aux = 0u;
3451
+ #endif
3452
+ if (lane < ncon) {
3453
+ pr = s.con_pair[lane]; sl = s.con_slot[lane]; el = s.con_elem[lane]; dm = s.con_dim[lane];
3454
+ di = s.con_dist[lane]; mu = s.con_mu[lane];
3455
+ for (int k = 0; k < 3; k++) ps[k] = s.con_pos[lane][k];
3456
+ for (int k = 0; k < 9; k++) fr[k] = s.con_frame[lane][k];
3457
+ #ifdef PW_TORS
3458
+ mus = s.con_mus[lane];
3459
+ #endif
3460
+ #if TERRAIN_HF_NATIVE
3461
+ aux = s.con_aux[lane];
3462
+ #endif
3463
+ }
3464
+ __syncwarp();
3465
+ if (lane < ncon) {
3466
+ const int c = rk[0];
3467
+ s.con_pair[c] = pr; s.con_slot[c] = sl; s.con_elem[c] = el; s.con_dim[c] = dm;
3468
+ s.con_dist[c] = di; s.con_mu[c] = mu;
3469
+ for (int k = 0; k < 3; k++) s.con_pos[c][k] = ps[k];
3470
+ for (int k = 0; k < 9; k++) s.con_frame[c][k] = fr[k];
3471
+ #ifdef PW_TORS
3472
+ s.con_mus[c] = mus;
3473
+ #endif
3474
+ #if TERRAIN_HF_NATIVE
3475
+ s.con_aux[c] = aux;
3476
+ #endif
3477
+ }
3478
+ __syncwarp();
3479
+ return;
3480
+ }
3481
+ con_permute(s.con_pair, ncon, lane, rk);
3482
+ con_permute(s.con_slot, ncon, lane, rk);
3483
+ con_permute(s.con_elem, ncon, lane, rk);
3484
+ con_permute(s.con_dim, ncon, lane, rk);
3485
+ con_permute(s.con_dist, ncon, lane, rk);
3486
+ con_permute(s.con_mu, ncon, lane, rk);
3487
+ #ifdef PW_TORS
3488
+ con_permute(s.con_mus, ncon, lane, rk); // (world_params: foot_torsional)
3489
+ #endif
3490
+ #if TERRAIN_HF_NATIVE
3491
+ con_permute(s.con_aux, ncon, lane, rk);
3492
+ #endif
3493
+ con_permute_k(s.con_pos, ncon, lane, rk);
3494
+ con_permute_k(s.con_frame, ncon, lane, rk);
3495
+ #endif
3496
+ }
3497
+
3498
+ // the terrain's contacts of the robot geoms (virtual pairs NPAIR .. NPAIR + NTG - 1), one geom per lane
3499
+ template <class S>
3500
+ __device__ void collide_terrain(S& s, int lane) {
3501
+ #if TERRAIN_NOBJ > 0
3502
+ for (int t = lane; t < NTG * TERRAIN_NOBJ; t += 32) // the world's objects (one geom-object pair per lane)
3503
+ terrain_box(s, NPAIR + t / TERRAIN_NOBJ, PG2(NPAIR + t / TERRAIN_NOBJ), OBJ_E0 + t % TERRAIN_NOBJ);
3504
+ #endif
3505
+ if (g_ter.grid == nullptr) return;
3506
+ const float x0 = g_ter.grid[0], y0 = g_ter.grid[1], ic = g_ter.grid[2];
3507
+ const int nx = int(g_ter.grid[3]), ny = int(g_ter.grid[4]), nbox = int(g_ter.grid[5]);
3508
+ for (int t = lane; t < NTG; t += 32) {
3509
+ int pair = NPAIR + t, g = PG2(pair);
3510
+ const float* p = s.gx[g];
3511
+ float rb = c_grbound[g];
3512
+ int c0 = int(floorf((p[0] - rb - x0) * ic)), c1 = int(floorf((p[0] + rb - x0) * ic));
3513
+ int r0 = int(floorf((p[1] - rb - y0) * ic)), r1 = int(floorf((p[1] + rb - y0) * ic));
3514
+ if (c1 < 0 || r1 < 0 || c0 >= nx || r0 >= ny) continue;
3515
+ c0 = max(c0, 0); r0 = max(r0, 0); c1 = min(c1, nx - 1); r1 = min(r1, ny - 1);
3516
+ for (int r = r0; r <= r1; r++)
3517
+ for (int c = c0; c <= c1; c++)
3518
+ for (int k = g_ter.cstart[r * nx + c]; k < g_ter.cstart[r * nx + c + 1]; k++) {
3519
+ int e = g_ter.citems[k];
3520
+ if (c != max(c0, g_ter.ecell[2 * e]) || r != max(r0, g_ter.ecell[2 * e + 1])) continue; // once per element
3521
+ if (e < nbox) terrain_box(s, pair, g, e);
3522
+ else terrain_hfield(s, pair, g, e - nbox, nbox);
3523
+ }
3524
+ }
3525
+ }
3526
+ """
3527
+
3528
+ TERRAIN_HOOKS = (
3529
+ ("""template <class S>
3530
+ __device__ DK_INL_COLLIDE void collide_pair(S& s, int pair) {""",
3531
+ None),
3532
+ (""" unsigned char con_slot[MAXCON]; // which contact of its pair (tape): plane-capsule end, parallel capsule-capsule candidate
3533
+ """,
3534
+ """ unsigned char con_slot[MAXCON]; // which contact of its pair (tape): plane-capsule end, parallel capsule-capsule candidate
3535
+ unsigned short con_elem[MAXCON]; // terrain builds: the contact's terrain element (add_contact's slot >> 8)
3536
+ """),
3537
+ (""" float con_mu[MAXCON];
3538
+ unsigned char con_slot[MAXCON];
3539
+ float *con_dist""",
3540
+ """ float con_mu[MAXCON];
3541
+ unsigned char con_slot[MAXCON];
3542
+ unsigned short con_elem[MAXCON];
3543
+ float *con_dist"""),
3544
+ (""" s.con_slot[c] = (unsigned char)slot;
3545
+ """,
3546
+ """ s.con_slot[c] = (unsigned char)slot;
3547
+ s.con_elem[c] = (unsigned short)(slot >> 8);
3548
+ """),
3549
+ (""" unsigned e0 = 2 * i < ncon ? (unsigned)s.con_pair[2 * i] | (unsigned)s.con_slot[2 * i] << 9 : TAPE_CON_NONE;
3550
+ unsigned e1 = 2 * i + 1 < ncon ? (unsigned)s.con_pair[2 * i + 1] | (unsigned)s.con_slot[2 * i + 1] << 9
3551
+ : TAPE_CON_NONE;
3552
+ __stcs(rec + OFF_CON + i, __uint_as_float(e0 | e1 << 16));""",
3553
+ """ unsigned e0 = 2 * i < ncon ? (unsigned)s.con_pair[2 * i] | (unsigned)s.con_slot[2 * i] << 10 : TAPE_CON_NONE;
3554
+ unsigned e1 = 2 * i + 1 < ncon ? (unsigned)s.con_pair[2 * i + 1] | (unsigned)s.con_slot[2 * i + 1] << 10
3555
+ : TAPE_CON_NONE;
3556
+ __stcs(rec + OFF_CON + i, __uint_as_float(e0 | e1 << 16));
3557
+ unsigned x0 = 2 * i < ncon ? (unsigned)s.con_elem[2 * i] : 0u;
3558
+ unsigned x1 = 2 * i + 1 < ncon ? (unsigned)s.con_elem[2 * i + 1] : 0u;
3559
+ __stcs(rec + OFF_TELEM + i, __uint_as_float(x0 | x1 << 16));"""),
3560
+ (""" if (PPLANE(pr)) {
3561
+ #if FLOOR_G >= 0""",
3562
+ """ if (PPLANE(pr)) {
3563
+ #if !TERRAIN_FLOOR
3564
+ keep = false;
3565
+ #else
3566
+ #if FLOOR_G >= 0"""),
3567
+ (""" keep = dot3(dif, n) <= RFMA(c_grbound[g2], 1.f + 1e-5f, 1e-6f);
3568
+ } else {""",
3569
+ """ keep = dot3(dif, n) <= RFMA(c_grbound[g2], 1.f + 1e-5f, 1e-6f);
3570
+ #endif
3571
+ } else {"""),
3572
+ (""" for (int i = lane; i < ncand; i += 32) collide_pair(s, s.cand[i]);
3573
+ """,
3574
+ """ for (int i = lane; i < ncand; i += 32) collide_pair(s, s.cand[i]);
3575
+ collide_terrain(s, lane);
3576
+ """),
3577
+ (""" int ncon = uniform_int(min(s.ncon, MAXCON), 7);
3578
+ { // contact Jacobians:""",
3579
+ """ int ncon = uniform_int(min(s.ncon, MAXCON), 7);
3580
+ terrain_sort_contacts(s, ncon, lane);
3581
+ { // contact Jacobians:"""),
3582
+ )
3583
+
3584
+
3585
+ TERRAIN_NATIVE_HOOKS = (
3586
+ (""" unsigned short con_elem[MAXCON]; // terrain builds: the contact's terrain element (add_contact's slot >> 8)
3587
+ """,
3588
+ """ unsigned short con_elem[MAXCON]; // terrain builds: the contact's terrain element (add_contact's slot >> 8)
3589
+ unsigned con_aux[MAXCON]; // native heightfield contacts: the candidate id (HfCand.pid), else 0
3590
+ """),
3591
+ (""" unsigned short con_elem[MAXCON];
3592
+ float *con_dist""",
3593
+ """ unsigned short con_elem[MAXCON];
3594
+ unsigned con_aux[MAXCON];
3595
+ float *con_dist"""),
3596
+ (""" s.con_elem[c] = (unsigned short)(slot >> 8);
3597
+ s.con_dim[c] = PDIM(pair);
3598
+ s.con_dist[c] = dist;
3599
+ for (int k = 0; k < 3; k++) s.con_pos[c][k] = pos[k];
3600
+ for (int k = 0; k < 9; k++) s.con_frame[c][k] = frame[k];
3601
+ s.con_mu[c] = PFOOT(pair) ? s.fric : PMU(pair);
3602
+ return true;""",
3603
+ """ s.con_elem[c] = (unsigned short)(slot >> 8);
3604
+ s.con_aux[c] = 0u;
3605
+ s.con_dim[c] = PDIM(pair);
3606
+ s.con_dist[c] = dist;
3607
+ for (int k = 0; k < 3; k++) s.con_pos[c][k] = pos[k];
3608
+ for (int k = 0; k < 9; k++) s.con_frame[c][k] = frame[k];
3609
+ s.con_mu[c] = PFOOT(pair) ? s.fric : PMU(pair);
3610
+ return true;"""),
3611
+ (""" __stcs(rec + OFF_TELEM + i, __uint_as_float(x0 | x1 << 16));""",
3612
+ """ __stcs(rec + OFF_TELEM + i, __uint_as_float(x0 | x1 << 16));
3613
+ __stcs(rec + OFF_TAUX + 2 * i, __uint_as_float(2 * i < ncon ? s.con_aux[2 * i] : 0u));
3614
+ if (2 * i + 1 < MAXCON) __stcs(rec + OFF_TAUX + 2 * i + 1, __uint_as_float(2 * i + 1 < ncon ? s.con_aux[2 * i + 1] : 0u));"""),
3615
+ )
3616
+
3617
+
3618
+ def capbox_segs_source(text=None):
3619
+ """capsule_box's witness search (STEP_DEVICE, or text holding the same capsule_box: the forest engine's) as a
3620
+ function of its own: capbox_segs(...) -> the number of candidate spheres (0..2) and their segment parameters segs[]
3621
+ (MuJoCo Warp's capsule_box_witness), for the terrain."""
3622
+ text = STEP_DEVICE if text is None else text
3623
+ i = text.index("// capsule-box (MuJoCo Warp's capsule_box_witness")
3624
+ j = text.index(" for (int e = 0; e < 2; e++) {\n if (e == 1 && !(second > -3.f)) break;", i)
3625
+ src = text[i:j]
3626
+ reps = (("// capsule-box (MuJoCo Warp's capsule_box_witness + capsule_box): up to two sphere-box contacts along the "
3627
+ "segment\ntemplate <class S>\n__device__ void capsule_box(S& s, int pair, const float* cp, const float* "
3628
+ "axisw, float cr, float hl, const float* bp,\n const float* R, const float* bs) {",
3629
+ "// capsule_box's candidate spheres (generated from it by step.capbox_segs_source)\n"
3630
+ "__device__ __noinline__ int capbox_segs(const float* cp, const float* axisw, float hl, const float* bp,\n"
3631
+ " const float* R, const float* bs, float* segs) {"),
3632
+ (" if (cltype == -4) return;\n", " if (cltype == -4) return 0;\n"))
3633
+ for a, b in reps:
3634
+ if src.count(a) != 1:
3635
+ raise RuntimeError(f"capbox_segs_source: {a[:60]!r}")
3636
+ src = src.replace(a, b)
3637
+ if "return;" in src:
3638
+ raise RuntimeError("capbox_segs_source: a bare return left")
3639
+ return src + " segs[0] = bestseg;\n if (!(second > -3.f)) return 1;\n segs[1] = bestseg + second;\n return 2;\n}\n"
3640
+
3641
+
3642
+ def apply_hooks(src, hooks):
3643
+ """src with each (anchor, replacement) of hooks applied; every anchor must occur exactly once."""
3644
+ for a, b in hooks:
3645
+ if src.count(a) != 1:
3646
+ raise RuntimeError(f"terrain hook anchor found {src.count(a)} times: {a[:60]!r}")
3647
+ src = src.replace(a, b)
3648
+ return src
3649
+
3650
+
3651
+ def terrain_source(src, terrain=None):
3652
+ """src (STEP_DEVICE + STEP_KERNEL, or text containing them) with the terrain hooks for a terrain build; unchanged
3653
+ when terrain is None."""
3654
+ if terrain is None:
3655
+ return src
3656
+ dev = capbox_segs_source() + "\n" + TERRAIN_DEVICE.lstrip("\n") + "\n"
3657
+ src = apply_hooks(src, [(a, dev + a if b is None else b) for a, b in TERRAIN_HOOKS])
3658
+ if terrain[0].mode == "native":
3659
+ src = apply_hooks(src, TERRAIN_NATIVE_HOOKS)
3660
+ return src
3661
+
3662
+
3663
+ def extra_constants(m):
3664
+ """dof -> body map and per-body ancestor bitmasks (bit k: body k is the body or one of its ancestors)."""
3665
+ dofbody = np.asarray(m.dof_bodyid, np.float64)
3666
+ mask = np.zeros(m.nbody, np.int64)
3667
+ for b in range(m.nbody):
3668
+ k = b
3669
+ while k > 0:
3670
+ mask[b] |= 1 << k
3671
+ k = int(m.body_parentid[k])
3672
+ return dofbody, mask
3673
+
3674
+
3675
+ EXTRA_HEADER = "DKC int c_dofbody[NV];\nDKC unsigned int c_ancmask[NB];\n"
3676
+
3677
+
3678
+ def ancmask_packed(m, mask):
3679
+ """(c_ancmask packed for host.loader's "u" kind as float32, its layout entry): one 32-bit word per body, two (low,
3680
+ high: the device's unsigned long long, model_hooks.ENGINE_NB64) for more than 32 bodies."""
3681
+ mask = np.asarray(mask, np.int64)
3682
+ width = 2 if m.nbody > 32 else 1
3683
+ words = np.stack([mask & 0xFFFFFFFF, mask >> 32], 1).ravel() if width == 2 else mask
3684
+ return np.stack([words & 0xFFFF, words >> 16], 1).ravel().astype(np.float32), ("c_ancmask", "u", "nb", width)
3685
+
3686
+
3687
+ def _terrain_mod():
3688
+ from nablaengine import terrain
3689
+ return terrain
3690
+
3691
+
3692
+ OBJECT_HOST_HOOKS = (
3693
+ (" if (lane < 3) s.com[lane] = com[w * 3 + lane];\n",
3694
+ " if (lane < 3) s.com[lane] = com[(size_t)w * COM_WORDS + lane];\n"
3695
+ " dk_obj = com + (size_t)w * COM_WORDS + 3; // the world's object slots (terrain objects)\n", 2),
3696
+ )
3697
+ OBJECT_ADJ_HOOKS = (
3698
+ (" if (lane < 3) s.com[lane] = com[w * 3 + lane];\n",
3699
+ " if (lane < 3) s.com[lane] = com[(size_t)w * COM_WORDS + lane];\n"
3700
+ " dk_obj = com + (size_t)w * COM_WORDS + 3; // the world's object slots (terrain objects)\n", 1),
3701
+ )
3702
+ OBJECT_KIN_HOOKS = (
3703
+ (" if (lane < 3) s.com[lane] = com[(size_t)w * 3 + lane];\n",
3704
+ " if (lane < 3) s.com[lane] = com[(size_t)w * COM_WORDS + lane]; // (terrain objects: com's stride)\n", 1),
3705
+ )
3706
+
3707
+
3708
+ def object_hooks(src, hooks, terrain):
3709
+ """src with hooks ((anchor, replacement, count)) for a terrain build with objects, else unchanged."""
3710
+ if terrain is None or not terrain[0].objects:
3711
+ return src
3712
+ for a, b, n in hooks:
3713
+ if src.count(a) != n:
3714
+ raise RuntimeError(f"object hook anchor found {src.count(a)} times, expected {n}: {a[:70]!r}")
3715
+ src = src.replace(a, b)
3716
+ return src