peclet-dem 1.1.0
Performance-portable XPBD Discrete Element Method (Kokkos + ArborX)
Loading...
Searching...
No Matches
solver_velocity.hpp
Go to the documentation of this file.
1
9#ifndef DEM_SOLVER_VELOCITY_HPP
10#define DEM_SOLVER_VELOCITY_HPP
11
12#include <climits>
13#include <Kokkos_Core.hpp>
14#include <tuple>
15#include <utility>
16#include <vector>
17
18#include "contact_preprocessing.hpp" // ManifoldC, CpExec/CpMem
19#include "dem_portable.hpp"
20#include "solver_fused.hpp"
21
22namespace peclet::dem {
23
24namespace detail {
25KOKKOS_INLINE_FUNCTION F3 ld3(Kokkos::View<const float* [3], CpMem> v, int i) {
26 return F3{v(i, 0), v(i, 1), v(i, 2)};
27}
28// v^T I_world^-1 v with I_world^-1 = R I_local^-1 R^T -> (R^T v) diag(invI_local) (R^T v).
29KOKKOS_INLINE_FUNCTION float genInvMass(F3 tau, F3 invIlocal, F4 q) {
30 // Isotropic inertia (spheres): the principal frame is irrelevant -- skip both rotations.
31 if (invIlocal.x == invIlocal.y && invIlocal.y == invIlocal.z)
32 return dot3(tau, tau) * invIlocal.x;
33 const F3 t = invRotateVector(q, tau);
34 return t.x * t.x * invIlocal.x + t.y * t.y * invIlocal.y + t.z * t.z * invIlocal.z;
35}
36} // namespace detail
37
46inline void countVelocityJacobi(Kokkos::View<const ManifoldC*, CpMem> manifolds, int numManifolds,
47 Kokkos::View<const int*, CpMem> realIdx,
48 Kokkos::View<int*, CpMem> counts, bool dedupTwins = true) {
49 CpExec space;
50 Kokkos::parallel_for(
51 "peclet::dem::count_velocity_jacobi", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
52 KOKKOS_LAMBDA(int idx) {
53 const ManifoldC m = manifolds(idx);
54 if (m.num_points <= 0)
55 return;
56 const int realA = realIdx(m.bodyA);
57 if (m.bodyB >= 0) {
58 const int realB = realIdx(m.bodyB);
59 if (dedupTwins && realA > realB)
60 return; // periodic dedup, as in solveVelocity
61 Kokkos::atomic_add(&counts(realB), 1);
62 }
63 Kokkos::atomic_add(&counts(realA), 1);
64 });
65 space.fence();
66}
67
71 Kokkos::View<const unsigned char*, CpMem> persistent;
72 Kokkos::View<const float* [3], CpMem> posPred;
73 F3 gHat = {};
74 Kokkos::View<const unsigned char*, CpMem> grounded;
75};
76
87struct ShockGate {
88 float up; // > 0: A above B
89 float thr; // the near-horizontal band
90 float riseThr; // rise = -v.gHat (gHat points down-gravity)
91 KOKKOS_INLINE_FUNCTION ShockGate(F3 dx, F3 gHat, float restVelThreshold)
92 : up(-(dx.x * gHat.x + dx.y * gHat.y + dx.z * gHat.z))
93 , thr(0.3f * Kokkos::sqrt(dot3(dx, dx)))
94 , riseThr(4.0f * restVelThreshold) {}
95
96 KOKKOS_INLINE_FUNCTION bool lowerB(F3 vB, F3 gHat) const {
97 return up > thr && -dot3(vB, gHat) <= riseThr;
98 }
99
100 KOKKOS_INLINE_FUNCTION bool lowerA(F3 vA, F3 gHat) const {
101 return up < -thr && -dot3(vA, gHat) <= riseThr;
102 }
103};
104
114inline void solveVelocity(
115 Kokkos::View<const ManifoldC*, CpMem> manifolds, int numManifolds, const BodyState& bodies,
116 const BodyPred& pred, Kokkos::View<const int*, CpMem> realIdx, float growthRate,
117 float restitutionNormal, float restVelThreshold, Kokkos::View<float* [3], CpMem> deltaVel,
118 Kokkos::View<float* [3], CpMem> deltaAngVel, Kokkos::View<int*, CpMem> velCounts,
119 Kokkos::View<const int*, CpMem> onlyColor = {}, int colorFilter = 0,
120 const ShockPropagation& shock = {}, bool massSplit = false, bool dedupTwins = true) {
121 const Kokkos::View<const float*, CpMem> invMass = bodies.invMass;
122 const Kokkos::View<const float* [3], CpMem> invInertia = bodies.invInertia;
123 const Kokkos::View<const float* [4], CpMem> quat = bodies.quat;
124 const Kokkos::View<const float* [3], CpMem> velPred = pred.velPred, angVelPred = pred.angVelPred;
125 const Kokkos::View<const unsigned char*, CpMem> persistent = shock.persistent,
126 grounded = shock.grounded;
127 const Kokkos::View<const float* [3], CpMem> posPred = shock.posPred;
128 const F3 gHat = shock.gHat;
129 using detail::genInvMass;
130 using detail::ld3;
131 CpExec space;
132 const bool filt = onlyColor.extent(0) > 0;
133 const bool usePersist = persistent.extent(0) > 0;
134 Kokkos::parallel_for(
135 "peclet::dem::solve_velocity", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
136 KOKKOS_LAMBDA(int idx) {
137 if (filt && onlyColor(idx) != colorFilter)
138 return; // colour filter (kernel unit test only; no production caller)
139 const ManifoldC m = manifolds(idx);
140 if (m.num_points <= 0)
141 return;
142
143 const int idA = m.bodyA, idB = m.bodyB;
144 const int realA = realIdx(idA);
145 int realB = idB;
146 if (idB >= 0) {
147 realB = realIdx(idB);
148 if (dedupTwins && realA > realB)
149 return; // periodic dedup
150 }
151
152 const float invMassA = invMass(realA);
153 const float invMassB = (idB >= 0) ? invMass(realB) : 0.0f;
154 const F3 invIA = ld3(invInertia, realA);
155 const F3 invIB = (idB >= 0) ? ld3(invInertia, realB) : F3{0, 0, 0};
156 const F4 qA = F4{quat(realA, 0), quat(realA, 1), quat(realA, 2), quat(realA, 3)};
157 const F4 qB = (idB >= 0)
158 ? F4{quat(realB, 0), quat(realB, 1), quat(realB, 2), quat(realB, 3)}
159 : F4{0, 0, 0, 1};
160
161 const F3 vA = ld3(velPred, realA), wA = ld3(angVelPred, realA);
162 F3 vB{0, 0, 0}, wB{0, 0, 0};
163 if (idB >= 0) {
164 vB = ld3(velPred, realB);
165 wB = ld3(angVelPred, realB);
166 }
167
168 const F3 Nsum{m.normal_sum.x, m.normal_sum.y, m.normal_sum.z};
169 const F3 TauA{m.torque_armA_sum.x, m.torque_armA_sum.y, m.torque_armA_sum.z};
170 const F3 TauB{m.torque_armB_sum.x, m.torque_armB_sum.y, m.torque_armB_sum.z};
171
172 const float invN = 1.0f / static_cast<float>(m.num_points);
173
174 // Moving-wall boundary (idB<0): the static "body B" carries the wall's surface velocity
175 // (count-averaged over the contact patch) so restitution is against the wall's motion, and
176 // its own restitution (a < 0 average keeps the global material — planes, body-body).
177 float restitution = restitutionNormal;
178 if (idB < 0)
179 vB = scale3(F3{m.wallVel_sum.x, m.wallVel_sum.y, m.wallVel_sum.z}, invN);
180 { // per-wall AND per-pair material override (a < 0 average keeps the global material)
181 const float ra = m.restitution_sum * invN;
182 if (ra >= 0.0f)
183 restitution = ra;
184 }
185 const F3 rAavg = scale3(F3{m.rA_sum.x, m.rA_sum.y, m.rA_sum.z}, invN);
186 const F3 rBavg = scale3(F3{m.rB_sum.x, m.rB_sum.y, m.rB_sum.z}, invN);
187
188 const float lenN = Kokkos::sqrt(dot3(Nsum, Nsum));
189 if (lenN < 1e-9f)
190 return;
191
192 // Separation vector for the approaching-sign gate + growth velocity. For a BOUNDARY
193 // (idB<0), rBavg is the ABSOLUTE wall contact point (kept absolute for the position solve's
194 // plane linearisation), NOT a body-relative lever — so rAavg - rBavg would depend on where
195 // the contact sits in world space, flipping `alignment` (and thus the approaching test)
196 // around a curved wall / a wall far from the origin and injecting energy (grains "jump" on
197 // the way down a rotating drum). The grain's own contact lever rAavg is the meaningful
198 // relative vector (dot(Nsum, rAavg) = radius > 0, a consistent convention). Body-body keeps
199 // rAavg-rBavg.
200 const F3 diffCenters = (idB < 0) ? rAavg : sub3(rAavg, rBavg);
201 const F3 vGrowth = scale3(diffCenters, growthRate);
202
203 float vn = dot3(vA, Nsum) + dot3(wA, TauA) + dot3(vB, F3{-Nsum.x, -Nsum.y, -Nsum.z}) +
204 dot3(wB, TauB);
205 vn += dot3(vGrowth, Nsum);
206
207 const float alignment = dot3(Nsum, diffCenters);
208 if (alignment > 0.0f) {
209 if (vn < 0.0f)
210 return; // sphere convention: approaching if vn>0
211 } else {
212 if (vn > 0.0f)
213 return; // inverted convention
214 }
215
216 const float Nsq = dot3(Nsum, Nsum);
217 float wA_n = Nsq * invMassA + genInvMass(TauA, invIA, qA);
218 float wB_n = Nsq * invMassB + genInvMass(TauB, invIB, qB);
219 // Shock propagation (Guendelman et al. 2003) for persistent LOADED body-body contacts: an
220 // inelastic pairwise solve conserves momentum, so a deep column merely homogenises its fall
221 // (the floor drains one layer per sweep and the pile never cools -- the phantom-fall
222 // state). Treating the LOWER body of a loaded contact as static drains the column's
223 // momentum through the support chain into the ground: the upper body is corrected, the
224 // lower keeps its (already supported) velocity. Near-horizontal pairs stay symmetric; new
225 // contacts and g = 0 runs are untouched (momentum-conserving impacts with material
226 // restitution).
227 // ... but ONLY when the lower body is not rising and is grounded (ShockGate).
228 bool applyA = true, applyB = true;
229 if (usePersist && persistent(idx) != 0 && idB >= 0) {
230 const ShockGate gate(sub3(ldF3(posPred, idA), ldF3(posPred, idB)), gHat,
231 restVelThreshold); // ghost-aware pair geometry
232 if (gate.lowerB(vB, gHat) && grounded(realB) > 0) {
233 wB_n = 0.0f;
234 applyB = false;
235 restitution = 0.0f; // shock pass is inelastic: e > 0 one-sided would bounce bodies
236 // off the ground with unpaid momentum
237 } else if (gate.lowerA(vA, gHat) && grounded(realA) > 0) {
238 wA_n = 0.0f;
239 applyA = false;
240 restitution = 0.0f;
241 }
242 }
243 const float wTotal = wA_n + wB_n;
244 if (wTotal <= 0.0f)
245 return;
246 // Mass-split Jacobi: the same numerator against copies of mass m / n.
247 const float wSolve =
248 massSplit ? static_cast<float>(velCounts(realA)) * wA_n +
249 ((idB >= 0) ? static_cast<float>(velCounts(realB)) * wB_n : 0.0f)
250 : wTotal;
251
252 // Resting-contact regularization (the standard PBD/XPBD restitution threshold): bounce only
253 // when the physical approach speed |vn|/|Nsum| exceeds ~2 g dt (what one substep of free
254 // fall gains). Below it the contact is RESTING — its vn is integration noise, and bouncing
255 // it every substep across a dense pile's contact chains (impulses Jacobi-SUMMED per body,
256 // no mass splitting) pumps energy without bound: a settled 180k glass-bead bed switched to
257 // e=0.8 reached |v| ~ 3e6 cells/s within 15 substeps. With e=0 the impulse still cancels
258 // the approach velocity — exactly the quasi-static dissipation a resting pile needs.
259 if (Kokkos::fabs(vn) < restVelThreshold * lenN)
260 restitution = 0.0f;
261
262 const float lambda = (-restitution * vn - vn) / wSolve;
263
264 const F3 Jlin = scale3(Nsum, lambda);
265 const F3 JangA = scale3(TauA, lambda);
266 const F3 JangB = scale3(TauB, lambda);
267
268 // Linear delta on A.
269 if (applyA) {
270 Kokkos::atomic_add(&deltaVel(realA, 0), Jlin.x * invMassA);
271 Kokkos::atomic_add(&deltaVel(realA, 1), Jlin.y * invMassA);
272 Kokkos::atomic_add(&deltaVel(realA, 2), Jlin.z * invMassA);
273 // Angular delta on A: dw_world = R (invI_local * (R^T Jang)).
274 {
275 const F3 Jl = invRotateVector(qA, JangA);
276 const F3 dwl{Jl.x * invIA.x, Jl.y * invIA.y, Jl.z * invIA.z};
277 const F3 dww = rotateVector(qA, dwl);
278 Kokkos::atomic_add(&deltaAngVel(realA, 0), dww.x);
279 Kokkos::atomic_add(&deltaAngVel(realA, 1), dww.y);
280 Kokkos::atomic_add(&deltaAngVel(realA, 2), dww.z);
281 }
282 }
283 if (idB >= 0 && applyB) {
284 Kokkos::atomic_add(&deltaVel(realB, 0), -Jlin.x * invMassB);
285 Kokkos::atomic_add(&deltaVel(realB, 1), -Jlin.y * invMassB);
286 Kokkos::atomic_add(&deltaVel(realB, 2), -Jlin.z * invMassB);
287 const F3 Jl = invRotateVector(qB, JangB);
288 const F3 dwl{Jl.x * invIB.x, Jl.y * invIB.y, Jl.z * invIB.z};
289 const F3 dww = rotateVector(qB, dwl);
290 Kokkos::atomic_add(&deltaAngVel(realB, 0), dww.x);
291 Kokkos::atomic_add(&deltaAngVel(realB, 1), dww.y);
292 Kokkos::atomic_add(&deltaAngVel(realB, 2), dww.z);
293 if (!massSplit)
294 Kokkos::atomic_add(&velCounts(realB), 1);
295 }
296 if (applyA && !massSplit)
297 Kokkos::atomic_add(&velCounts(realA), 1);
298 });
299 space.fence();
300}
301
309template <class V3, class Vi>
310inline void applyVelocityDeltasAveraged(int n, V3 velPred, V3 angVelPred, V3 deltaVel,
311 V3 deltaAngVel, Vi velCounts, bool averaged = true) {
312 CpExec space;
313 Kokkos::parallel_for(
314 "peclet::dem::apply_vel_avg", Kokkos::RangePolicy<CpExec>(space, 0, n), KOKKOS_LAMBDA(int i) {
315 const int count = velCounts(i);
316 if (count <= 0)
317 return;
318 // Over-relaxed average: omega=2 halves the convergence loss of plain 1/count averaging
319 // (the crush-dissipation rate) while staying far below the raw-sum overshoot (omega=count)
320 // that detonates a resting pile at e=0.8. count==1 (binary collision) stays exact.
321 const float f = averaged ? Kokkos::fmin(1.0f, 2.0f / static_cast<float>(count)) : 1.0f;
322 for (int c = 0; c < 3; ++c) {
323 velPred(i, c) += deltaVel(i, c) * f;
324 angVelPred(i, c) += deltaAngVel(i, c) * f;
325 deltaVel(i, c) = 0.0f;
326 deltaAngVel(i, c) = 0.0f;
327 }
328 velCounts(i) = 0;
329 });
330 space.fence();
331}
332
333// ============================ colored Gauss–Seidel velocity solve ============================
334// The Jacobi solve above sums every touching manifold's impulse onto a body, then relaxes the sum
335// by the contact count to stay stable — a stable but UNDER-converged approximation that
336// under-dissipates in dense multi-contact regions (effective restitution rises above the prescribed
337// e). The colored Gauss–Seidel path removes that approximation: graph-colour the manifolds so no
338// two sharing a real body share a colour, then sweep colour-by-colour applying each impulse IN
339// PLACE (read the current velocity, apply, write) — a body sees the updates of every
340// previously-solved contact in the same sweep. Within a colour the manifolds are an independent set
341// (no shared body), so the in-place read-modify-write is race-free WITHOUT atomics or averaging,
342// and the fixed-point is the true coupled multi-contact solution, so the dissipation is correct by
343// construction. count==1 (a binary collision) is identical to the Jacobi path; the difference is
344// confined to dense clusters.
345
349 Kokkos::View<const ManifoldC*, CpMem> manifolds;
350 Kokkos::View<const int*, CpMem> realIdx;
351 Kokkos::View<const unsigned char*, CpMem> sleepMask;
355 static constexpr ColorLabels labels() {
356 return {"peclet::dem::color_init_bodies", "peclet::dem::color_init_manifolds",
357 "peclet::dem::color_reset_winner", "peclet::dem::color_contend",
358 "peclet::dem::color_commit", "peclet::dem::color_max",
359 "peclet::dem::color_leftover"};
360 }
361 KOKKOS_INLINE_FUNCTION int initialColor(int idx) const {
362 const ManifoldC m = manifolds(idx);
363 if (m.num_points <= 0 || (sleepOn && sleepMask(idx) != 0))
364 return -2; // inactive or a frozen (both-asleep) island manifold
365 // Periodic twin dedup (§4.2 item 2): single-rank only; under MPI ownership already
366 // excludes the non-owned twin (dedupTwins = !Hooks::distributed).
367 if (dedupTwins && m.bodyB >= 0 && realIdx(m.bodyA) > realIdx(m.bodyB))
368 return -2; // periodic dedup: the (realA<=realB) twin carries this contact
369 return -1;
370 }
371 KOKKOS_INLINE_FUNCTION ColorEdge edge(int idx) const {
372 const ManifoldC m = manifolds(idx);
373 const int ea = ov.slotA(idx, realIdx(m.bodyA));
374 const int eb = (m.bodyB >= 0) ? ov.slotB(idx, realIdx(m.bodyB)) : -1;
375 return {ea, eb, colorKey(idx)};
376 }
377};
378
383inline int colorManifolds(Kokkos::View<const ManifoldC*, CpMem> manifolds, int numManifolds,
384 Kokkos::View<const int*, CpMem> realIdx, int numReal,
385 Kokkos::View<int*, CpMem> mColor, const ColorScratch& scratch,
386 int& leftover, Kokkos::View<const unsigned char*, CpMem> sleepMask = {},
387 SlotOverride ov = {}, bool dedupTwins = true, int vertexSpan = 0) {
388 const ManifoldEdges edges{manifolds, realIdx, sleepMask, ov, sleepMask.extent(0) > 0, dedupTwins};
389 return colorEdges(edges, numManifolds, numReal, vertexSpan, mColor, scratch, leftover);
390}
391
408inline int colorManifoldsIncremental(Kokkos::View<const ManifoldC*, CpMem> manifolds,
409 int numManifolds, Kokkos::View<const int*, CpMem> realIdx,
410 int numReal, const CarriedColors& carried,
411 Kokkos::View<int*, CpMem> mColor, const ColorScratch& scratch,
412 int& leftover, bool forceFull,
413 Kokkos::View<const unsigned char*, CpMem> sleepMask = {},
414 bool dedupTwins = true) {
415 const Kokkos::View<const unsigned long long*, CpMem> prevKeys = carried.keys;
416 const Kokkos::View<const int*, CpMem> prevColor = carried.color;
417 const int prevCount = carried.count;
418 const Kokkos::View<long long*, CpMem> bodyWinner = scratch.bodyWinner;
419 const Kokkos::View<std::uint64_t*, CpMem> bodyMask = scratch.bodyColorMask;
420 leftover = 0;
421 CpExec space;
422 if (numManifolds <= 0 || numReal <= 0)
423 return 0;
424 Kokkos::parallel_for(
425 "peclet::dem::icolor_init_bodies", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
426 KOKKOS_LAMBDA(int i) { bodyMask(i) = 0; });
427 const bool full = forceFull || prevCount <= 0;
428 const bool sleepOn = sleepMask.extent(0) > 0;
429 // Seed each manifold's colour: -2 inactive/dedup/both-asleep, else the carried colour (matched by
430 // pair key) or -1 (new / full recolour).
431 Kokkos::parallel_for(
432 "peclet::dem::icolor_seed", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
433 KOKKOS_LAMBDA(int idx) {
434 const ManifoldC m = manifolds(idx);
435 if (m.num_points <= 0 || (sleepOn && sleepMask(idx))) {
436 mColor(idx) = -2; // inactive or a frozen (both-asleep) island manifold
437 return;
438 }
439 if (dedupTwins && m.bodyB >= 0 && realIdx(m.bodyA) > realIdx(m.bodyB)) {
440 mColor(idx) = -2; // periodic dedup twin
441 return;
442 }
443 int c = -1;
444 if (!full) {
445 const unsigned long long k = pairKeyOf(m, realIdx);
446 int lo = 0, hi = prevCount;
447 while (lo < hi) {
448 const int mid = (lo + hi) >> 1;
449 if (prevKeys(mid) < k)
450 lo = mid + 1;
451 else
452 hi = mid;
453 }
454 if (lo < prevCount && prevKeys(lo) == k) {
455 const int pc = prevColor(lo);
456 if (pc >= 0)
457 c = pc; // carry (leftover -1 last step -> re-arbitrate as new)
458 }
459 }
460 mColor(idx) = c;
461 });
462 // Seed the per-body masks from the carried colours (survivors are conflict-free on single-GPU).
463 if (!full)
464 Kokkos::parallel_for(
465 "peclet::dem::icolor_seed_mask", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
466 KOKKOS_LAMBDA(int idx) {
467 const int c = mColor(idx);
468 if (c < 0)
469 return;
470 const ManifoldC m = manifolds(idx);
471 const std::uint64_t bit = std::uint64_t(1) << c;
472 Kokkos::atomic_or(&bodyMask(realIdx(m.bodyA)), bit);
473 if (m.bodyB >= 0)
474 Kokkos::atomic_or(&bodyMask(realIdx(m.bodyB)), bit);
475 });
476 // Jones-Plassmann arbitration over the uncoloured (-1) set only — identical body of work to
477 // colorManifolds, but the frozen carried colours restrict it to the few new manifolds.
478 int remaining = 1, prevRemaining = -1;
479 const int maxRounds = numManifolds + 2; // §12 S7: bounded by the vertices coloured
480 for (int round = 0; round < maxRounds && remaining > 0; ++round) {
481 Kokkos::parallel_for(
482 "peclet::dem::icolor_reset_winner", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
483 KOKKOS_LAMBDA(int i) { bodyWinner(i) = -1; });
484 Kokkos::parallel_for(
485 "peclet::dem::icolor_contend", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
486 KOKKOS_LAMBDA(int idx) {
487 if (mColor(idx) != -1)
488 return;
489 const ManifoldC m = manifolds(idx);
490 const long long key = colorKey(idx);
491 Kokkos::atomic_max(&bodyWinner(realIdx(m.bodyA)), key);
492 if (m.bodyB >= 0)
493 Kokkos::atomic_max(&bodyWinner(realIdx(m.bodyB)), key);
494 });
495 int rem = 0;
496 Kokkos::parallel_reduce(
497 "peclet::dem::icolor_commit", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
498 KOKKOS_LAMBDA(int idx, int& acc) {
499 if (mColor(idx) != -1)
500 return;
501 const ManifoldC m = manifolds(idx);
502 const int ea = realIdx(m.bodyA);
503 const int eb = (m.bodyB >= 0) ? realIdx(m.bodyB) : -1;
504 const long long key = colorKey(idx);
505 if (bodyWinner(ea) != key || (eb >= 0 && bodyWinner(eb) != key)) {
506 acc += 1;
507 return;
508 }
509 std::uint64_t forbidden = bodyMask(ea);
510 if (eb >= 0)
511 forbidden |= bodyMask(eb);
512 int c = 0; // lowest free colour of 64; never forced (§4.2 item 1)
513 while (c < kColorPalette && ((forbidden >> c) & 1))
514 ++c;
515#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 3
516 if (c > 62)
517 c = 62; // G13 mutant 3: the old forced colour 62
518#endif
519 if (c == kColorPalette) {
520 mColor(idx) = kColorUncolourable;
521 return;
522 }
523 mColor(idx) = c;
524 const std::uint64_t bit = std::uint64_t(1) << c;
525 bodyMask(ea) |= bit;
526 if (eb >= 0)
527 bodyMask(eb) |= bit;
528 },
529 rem);
530 space.fence();
531 if (rem == prevRemaining)
532 break; // safety bound only (see colorManifolds)
533 prevRemaining = rem;
534 remaining = rem;
535 }
536 int maxc = -1;
537 Kokkos::parallel_reduce(
538 "peclet::dem::icolor_max", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
539 KOKKOS_LAMBDA(int idx, int& mx) {
540 if (mColor(idx) > mx)
541 mx = mColor(idx);
542 },
543 Kokkos::Max<int>(maxc));
544 Kokkos::parallel_reduce(
545 "peclet::dem::icolor_leftover", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
546 KOKKOS_LAMBDA(int idx, int& acc) {
547 if (mColor(idx) == -1 || mColor(idx) == kColorUncolourable)
548 acc += 1;
549 },
550 leftover);
551 space.fence();
552 return maxc + 1;
553}
554
566
569inline void computeVn0(Kokkos::View<const ManifoldC*, CpMem> manifolds, int numManifolds,
570 const BodyPred& pred, Kokkos::View<const int*, CpMem> realIdx,
571 float growthRate, Kokkos::View<float*, CpMem> vn0,
572 Kokkos::View<float* [3], CpMem> vt0, bool dedupTwins = true) {
573 const Kokkos::View<const float* [3], CpMem> velPred = pred.velPred, angVelPred = pred.angVelPred;
574 using detail::ld3;
575 CpExec space;
576 Kokkos::parallel_for(
577 "peclet::dem::pgs_vn0", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
578 KOKKOS_LAMBDA(int idx) {
579 const ManifoldC m = manifolds(idx);
580 if (m.num_points <= 0)
581 return;
582 const int idA = m.bodyA, idB = m.bodyB;
583 const int realA = realIdx(idA);
584 if (dedupTwins && idB >= 0 && realA > realIdx(idB))
585 return; // periodic dedup
586 const float invN = 1.0f / static_cast<float>(m.num_points);
587 const F3 Nsum{m.normal_sum.x, m.normal_sum.y, m.normal_sum.z};
590 const F3 vA = ld3(velPred, realA), wA = ld3(angVelPred, realA);
591 F3 vB{0, 0, 0}, wB{0, 0, 0};
592 if (idB >= 0) {
593 vB = ld3(velPred, realIdx(idB));
594 wB = ld3(angVelPred, realIdx(idB));
595 } else {
596 vB = scale3(F3{m.wallVel_sum.x, m.wallVel_sum.y, m.wallVel_sum.z}, invN);
597 }
598 const F3 rAavg = scale3(F3{m.rA_sum.x, m.rA_sum.y, m.rA_sum.z}, invN);
599 const F3 rBavg = scale3(F3{m.rB_sum.x, m.rB_sum.y, m.rB_sum.z}, invN);
600 const F3 diffCenters = (idB < 0) ? rAavg : sub3(rAavg, rBavg);
601 const F3 vGrowth = scale3(diffCenters, growthRate);
602 float vn = dot3(vA, Nsum) + dot3(wA, TauA) + dot3(vB, F3{-Nsum.x, -Nsum.y, -Nsum.z}) +
603 dot3(wB, TauB);
604 vn += dot3(vGrowth, Nsum);
605 vn0(idx) = vn;
606 // Pre-solve tangential surface velocity at the averaged contact point (physical units):
607 // the reference for the tangential-restitution target -beta * vt0 (Walton impact law).
608 {
609 const float lenN = Kokkos::sqrt(dot3(Nsum, Nsum));
610 F3 vt{0, 0, 0};
611 if (lenN > 1e-9f) {
612 const F3 nhat = scale3(Nsum, 1.0f / lenN);
613 const int realB2 = (idB >= 0) ? realIdx(idB) : -1;
614 const F3 wAv = ld3(angVelPred, realA);
615 const F3 wBv = (realB2 >= 0) ? ld3(angVelPred, realB2) : F3{0, 0, 0};
616 const F3 vrel = sub3(add3(vA, cross3v(wAv, rAavg)), add3(vB, cross3v(wBv, rBavg)));
617 vt = sub3(vrel, scale3(nhat, dot3(vrel, nhat)));
618 }
619 vt0(idx, 0) = vt.x;
620 vt0(idx, 1) = vt.y;
621 vt0(idx, 2) = vt.z;
622 }
623 });
624}
625
641inline void updateRestitutionBank(Kokkos::View<const ManifoldC*, CpMem> manifolds, int numManifolds,
642 const BodyState& bodies, const BodyPred& pred,
643 Kokkos::View<const int*, CpMem> realIdx, float growthRate,
644 float restitutionNormal, float restVelThreshold,
645 Kokkos::View<const float*, CpMem> vn0, const PairLedger& ledger,
646 Kokkos::View<const float*, CpMem> restRel,
647 bool dedupTwins = true) {
648 const Kokkos::View<const float*, CpMem> lambdaAcc = ledger.lambda;
649 const Kokkos::View<float*, CpMem> restBank = ledger.restBank, restVPeak = ledger.restVPeak;
650 const Kokkos::View<const float*, CpMem> invMass = bodies.invMass;
651 const Kokkos::View<const float* [3], CpMem> invInertia = bodies.invInertia;
652 const Kokkos::View<const float* [4], CpMem> quat = bodies.quat;
653 const Kokkos::View<const float* [3], CpMem> velPred = pred.velPred, angVelPred = pred.angVelPred;
654 using detail::genInvMass;
655 using detail::ld3;
656 CpExec space;
657 Kokkos::parallel_for(
658 "peclet::dem::rest_bank_update", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
659 KOKKOS_LAMBDA(int idx) {
660 const ManifoldC m = manifolds(idx);
661 if (m.num_points <= 0)
662 return;
663 const int idA = m.bodyA, idB = m.bodyB;
664 const int realA = realIdx(idA);
665 const int realB = (idB >= 0) ? realIdx(idB) : idB;
666 if (dedupTwins && idB >= 0 && realA > realB)
667 return; // periodic dedup: the canonical twin owns the bank
668 const float invN = 1.0f / static_cast<float>(m.num_points);
669 const F3 Nsum{m.normal_sum.x, m.normal_sum.y, m.normal_sum.z};
670 const float lenN = Kokkos::sqrt(dot3(Nsum, Nsum));
671 if (lenN < 1e-9f)
672 return;
675 const F3 vA = ld3(velPred, realA), wA = ld3(angVelPred, realA);
676 F3 vB{0, 0, 0}, wB{0, 0, 0};
677 if (idB >= 0) {
678 vB = ld3(velPred, realB);
679 wB = ld3(angVelPred, realB);
680 } else {
681 vB = scale3(F3{m.wallVel_sum.x, m.wallVel_sum.y, m.wallVel_sum.z}, invN);
682 }
683 const F3 rAavg = scale3(F3{m.rA_sum.x, m.rA_sum.y, m.rA_sum.z}, invN);
684 const F3 rBavg = scale3(F3{m.rB_sum.x, m.rB_sum.y, m.rB_sum.z}, invN);
685 const F3 diffCenters = (idB < 0) ? rAavg : sub3(rAavg, rBavg);
686 const F3 vGrowth = scale3(diffCenters, growthRate);
687 float vn = dot3(vA, Nsum) + dot3(wA, TauA) + dot3(vB, F3{-Nsum.x, -Nsum.y, -Nsum.z}) +
688 dot3(wB, TauB);
689 vn += dot3(vGrowth, Nsum);
690 const float alignment = dot3(Nsum, diffCenters);
691 const float sgn = (alignment > 0.0f) ? 1.0f : -1.0f;
692 // Symmetric effective inverse mass (the release/bank ledger is momentum bookkeeping at
693 // the pair's own masses, independent of any stabilization sidedness this substep).
694 const F3 invIA = ld3(invInertia, realA);
695 const F3 invIB = (idB >= 0) ? ld3(invInertia, realB) : F3{0, 0, 0};
696 const F4 qA = F4{quat(realA, 0), quat(realA, 1), quat(realA, 2), quat(realA, 3)};
697 const F4 qB = (idB >= 0)
698 ? F4{quat(realB, 0), quat(realB, 1), quat(realB, 2), quat(realB, 3)}
699 : F4{0, 0, 0, 1};
700 const float Nsq = dot3(Nsum, Nsum);
701 const float wTotal = Nsq * invMass(realA) + genInvMass(TauA, invIA, qA) +
702 Nsq * ((idB >= 0) ? invMass(realB) : 0.0f) +
703 genInvMass(TauB, invIB, qB);
704 if (wTotal <= 0.0f)
705 return;
706 float e = restitutionNormal;
707 {
708 const float ra = m.restitution_sum * invN;
709 if (ra >= 0.0f)
710 e = ra;
711 }
712 const float v0til = sgn * vn0(idx);
713 const float vtilEnd = sgn * vn;
714 float owed = restBank(idx);
715 // Event state: refresh the peak on a kinetic approach, age it 1/256 per substep.
716 float vPeak = restVPeak(idx) * (1.0f - 1.0f / 256.0f);
717 if (v0til > restVelThreshold * lenN)
718 vPeak = Kokkos::fmax(vPeak, v0til / lenN);
719 if (vPeak > restVelThreshold) {
720 // Active event: bank e x this substep's compression FLUX (full applied normal impulse
721 // minus the reflection share — the momentum the chain actually transmitted; the
722 // m_eff-scale approach-destruction measure under-banks a chain-loaded impact by ~3000x),
723 // pay down the separation already delivered, and deduct the release channel's spend.
724 // A clean one-substep binary impact nets 0: pTot = (1+e) m_eff v0, pR = e m_eff v0.
725 const float pR = Kokkos::fmax(0.0f, -vtilEnd) / wTotal * lenN;
726 const float pTot = Kokkos::fmax(lambdaAcc(idx), 0.0f) * lenN;
727 const float pC = Kokkos::fmax(0.0f, pTot - pR);
728 owed += e * pC - pR - Kokkos::fmax(restRel(idx), 0.0f) * lenN;
729 restBank(idx) = Kokkos::fmax(owed, 0.0f);
730 restVPeak(idx) = vPeak;
731 } else {
732 restBank(idx) = 0.0f; // event aged out (or none): the residual budget evaporates
733 restVPeak(idx) = 0.0f;
734 }
735 });
736}
737
744inline void decayBodyOrphan(Kokkos::View<float*, CpMem> orphan,
745 Kokkos::View<float*, CpMem> orphanVPeak, int numOwned,
746 float restVelThreshold) {
747 CpExec space;
748 Kokkos::parallel_for(
749 "peclet::dem::rest_orphan_decay", Kokkos::RangePolicy<CpExec>(space, 0, numOwned),
750 KOKKOS_LAMBDA(int i) {
751 const float decayed = orphanVPeak(i) * (1.0f - 1.0f / 64.0f);
752 if (decayed <= restVelThreshold || orphan(i) <= 0.0f) {
753 orphan(i) = 0.0f;
754 orphanVPeak(i) = 0.0f;
755 } else {
756 orphan(i) *= (1.0f - 1.0f / 64.0f);
757 orphanVPeak(i) = decayed;
758 }
759 });
760}
761
775 const PairLedger& prev, Kokkos::View<const unsigned char*, CpMem> matched, int prevCount,
776 Kokkos::View<const float*, CpMem> invMass, Kokkos::View<float*, CpMem> orphan,
777 Kokkos::View<float*, CpMem> orphanVPeak, Kokkos::View<const int*, CpMem> gidSorted = {},
778 Kokkos::View<const int*, CpMem> slotSorted = {}, int ownedLimit = -1) {
779 const Kokkos::View<const unsigned long long*, CpMem> prevKeys = prev.keys;
780 const Kokkos::View<const float*, CpMem> prevRestBank = prev.restBank;
781 const Kokkos::View<const float*, CpMem> prevRestVPeak = prev.restVPeak;
782 // ownedLimit >= 0 (the distributed step: numReal): credit a dead entry only on the rank that
783 // owns its LOWER-gid endpoint -- with symmetric visibility (§5.1) exactly the pair's owner, so
784 // an entry carried on both endpoints' ranks (migration pack) is credited once
785 // (docs/contact_solve_framework.md §6.3). -1: no restriction (single rank, byte-identical).
786 CpExec space;
787 const int nMap = static_cast<int>(gidSorted.extent(0));
788 const int nBody = static_cast<int>(orphan.extent(0));
789 Kokkos::parallel_for(
790 "peclet::dem::rest_orphan_scatter", Kokkos::RangePolicy<CpExec>(space, 0, prevCount),
791 KOKKOS_LAMBDA(int e) {
792 if (matched(e))
793 return;
794 const float owed = prevRestBank(e);
795 if (owed <= 0.0f)
796 return;
797 const unsigned long long k = prevKeys(e);
798 if (k == ~0ull)
799 return;
800 const unsigned hi = static_cast<unsigned>(k >> 32);
801 const unsigned lo = static_cast<unsigned>(k & 0xFFFFFFFFu);
802 auto resolve = [&](unsigned id) -> int {
803 if (nMap == 0) // single-GPU: identities ARE real slots
804 return (static_cast<int>(id) < nBody) ? static_cast<int>(id) : -1;
805 int a = 0, b = nMap; // MPI: binary-search the sorted gid -> slot map
806 while (a < b) {
807 const int m = (a + b) >> 1;
808 if (gidSorted(m) < static_cast<int>(id))
809 a = m + 1;
810 else
811 b = m;
812 }
813 return (a < nMap && gidSorted(a) == static_cast<int>(id)) ? slotSorted(a) : -1;
814 };
815 const int sA = resolve(hi);
816 if (ownedLimit >= 0 && !(sA >= 0 && sA < ownedLimit))
817 return; // not the pair's owner: a stale copy is never credited
818 const int sB = (lo != 0xFFFFFFFFu) ? resolve(lo) : -1;
819 const float vpk = prevRestVPeak(e);
820 float shareA = 1.0f; // boundary (wall) pair: everything to the particle
821 if (lo != 0xFFFFFFFFu) {
822 if (sB >= 0 && sA >= 0) {
823 const float wA = invMass(sA), wB = invMass(sB);
824 if (wA + wB > 0.0f)
825 shareA = wB / (wA + wB); // heavier endpoint (smaller invMass) keeps more
826 } else {
827 shareA = 0.5f; // body-body with an unresolvable endpoint (MPI edge): conservative half
828 }
829 }
830 if (sA >= 0 && shareA > 0.0f) {
831 Kokkos::atomic_add(&orphan(sA), owed * shareA);
832 Kokkos::atomic_max(&orphanVPeak(sA), vpk);
833 }
834 if (sB >= 0 && shareA < 1.0f) {
835 Kokkos::atomic_add(&orphan(sB), owed * (1.0f - shareA));
836 Kokkos::atomic_max(&orphanVPeak(sB), vpk);
837 }
838 });
839}
840
843inline std::tuple<double, float, int> restBankStats(Kokkos::View<const float*, CpMem> bank, int n) {
844 double s = 0.0;
845 float mx = 0.0f;
846 int cnt = 0;
847 if (n > 0) {
848 Kokkos::parallel_reduce(
849 "peclet::dem::rest_bank_stats", Kokkos::RangePolicy<CpExec>(0, n),
850 KOKKOS_LAMBDA(int i, double& ls, float& lm, int& lc) {
851 const float v = bank(i);
852 ls += v;
853 if (v > lm)
854 lm = v;
855 if (v > 0.0f)
856 ++lc;
857 },
858 s, Kokkos::Max<float>(mx), Kokkos::Sum<int>(cnt));
859 }
860 return {s, mx, cnt};
861}
862
871inline void computeSideFlags(Kokkos::View<const ManifoldC*, CpMem> manifolds, int numManifolds,
872 Kokkos::View<const int*, CpMem> realIdx, const ShockPropagation& shock,
873 Kokkos::View<const float* [3], CpMem> velPred, float riseThr,
874 Kokkos::View<unsigned char*, CpMem> sideFlag,
875 Kokkos::View<const float*, CpMem> vn0, float approachThr,
876 bool dedupTwins = true) {
877 const Kokkos::View<const unsigned char*, CpMem> persistent = shock.persistent,
878 grounded = shock.grounded;
879 const Kokkos::View<const float* [3], CpMem> posPred = shock.posPred;
880 const F3 gHat = shock.gHat;
881 using detail::ld3;
882 CpExec space;
883 Kokkos::parallel_for(
884 "peclet::dem::pgs_side_flags", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
885 KOKKOS_LAMBDA(int idx) {
886 const unsigned char wasPersistent = persistent(idx); // read BEFORE the write: the caller
887 sideFlag(idx) = 0; // may alias persistent and sideFlag (flag reuses the persistence view)
888 const ManifoldC m = manifolds(idx);
889 if (m.num_points <= 0 || m.bodyB < 0 || wasPersistent == 0)
890 return;
891 // BALLISTIC GATE: one-sided grounding is a statics device -- a pair whose pre-solve
892 // relative normal speed exceeds the quasi-static scale (a few substeps of free fall)
893 // is shock-loaded or shearing and must stay momentum-conserving. Without this, a fast
894 // impactor meets an infinite-mass bed (measured: a 5 m/s ball stops at the surface of a
895 // 25k bed) and flowing regions over-resist (silo discharge -24%).
896 if (Kokkos::fabs(vn0(idx)) > approachThr)
897 return;
898 const int realA = realIdx(m.bodyA), realB = realIdx(m.bodyB);
899 if (dedupTwins && realA > realB)
900 return; // periodic dedup
901 const F3 dx = sub3(ldF3(posPred, m.bodyA), ldF3(posPred, m.bodyB));
902 const float up = -(dx.x * gHat.x + dx.y * gHat.y + dx.z * gHat.z); // >0: A above B
903 const float thr = 0.3f * Kokkos::sqrt(dot3(dx, dx));
904 if (up > thr && -dot3(ld3(velPred, realB), gHat) <= riseThr && grounded(realB) > 0) {
905 sideFlag(idx) = 1;
906 } else if (up < -thr && -dot3(ld3(velPred, realA), gHat) <= riseThr &&
907 grounded(realA) > 0) {
908 sideFlag(idx) = 2;
909 }
910 });
911}
912
915inline void warmStartApply(Kokkos::View<const ManifoldC*, CpMem> manifolds, int numManifolds,
916 const BodyState& bodies, const BodyPred& pred,
917 Kokkos::View<const int*, CpMem> realIdx,
918 Kokkos::View<const float*, CpMem> warmP,
919 Kokkos::View<float* [3], CpMem> warmT, bool dedupTwins = true) {
920 const Kokkos::View<const float*, CpMem> invMass = bodies.invMass;
921 const Kokkos::View<const float* [3], CpMem> invInertia = bodies.invInertia;
922 const Kokkos::View<const float* [4], CpMem> quat = bodies.quat;
923 const Kokkos::View<float* [3], CpMem> velPred = pred.velPred, angVelPred = pred.angVelPred;
924 using detail::ld3;
925 CpExec space;
926 Kokkos::parallel_for(
927 "peclet::dem::pgs_warm_apply", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
928 KOKKOS_LAMBDA(int idx) {
929 const float p = warmP(idx);
930 F3 lt{warmT(idx, 0), warmT(idx, 1), warmT(idx, 2)};
931 const bool hasT = (lt.x != 0.0f || lt.y != 0.0f || lt.z != 0.0f);
932 if (p == 0.0f && !hasT)
933 return;
934 const ManifoldC m = manifolds(idx);
935 if (m.num_points <= 0)
936 return;
937 const int idA = m.bodyA, idB = m.bodyB;
938 const int realA = realIdx(idA);
939 const int realB = (idB >= 0) ? realIdx(idB) : idB;
940 if (dedupTwins && idB >= 0 && realA > realB)
941 return; // periodic dedup (warmP is 0 for dups anyway)
942 const float invN = 1.0f / static_cast<float>(m.num_points);
943 const F3 Nsum{m.normal_sum.x, m.normal_sum.y, m.normal_sum.z};
946 const F3 rAavg = scale3(F3{m.rA_sum.x, m.rA_sum.y, m.rA_sum.z}, invN);
947 const F3 rBavg = scale3(F3{m.rB_sum.x, m.rB_sum.y, m.rB_sum.z}, invN);
948 const F3 diffCenters = (idB < 0) ? rAavg : sub3(rAavg, rBavg);
949 const float alignment = dot3(Nsum, diffCenters);
950 const float sgn = (alignment > 0.0f) ? 1.0f : -1.0f;
951 const float lambda = -sgn * p;
952 const F3 Jlin = scale3(Nsum, lambda);
953 const float invMassA = invMass(realA);
954 const float invMassB = (idB >= 0) ? invMass(realB) : 0.0f;
955 Kokkos::atomic_add(&velPred(realA, 0), Jlin.x * invMassA);
956 Kokkos::atomic_add(&velPred(realA, 1), Jlin.y * invMassA);
957 Kokkos::atomic_add(&velPred(realA, 2), Jlin.z * invMassA);
958 {
959 const F4 qA = F4{quat(realA, 0), quat(realA, 1), quat(realA, 2), quat(realA, 3)};
960 const F3 Jl = invRotateVector(qA, scale3(TauA, lambda));
961 const F3 invIA = ld3(invInertia, realA);
962 const F3 dwl{Jl.x * invIA.x, Jl.y * invIA.y, Jl.z * invIA.z};
963 const F3 dww = rotateVector(qA, dwl);
964 Kokkos::atomic_add(&angVelPred(realA, 0), dww.x);
965 Kokkos::atomic_add(&angVelPred(realA, 1), dww.y);
966 Kokkos::atomic_add(&angVelPred(realA, 2), dww.z);
967 }
968 if (idB >= 0) {
969 Kokkos::atomic_add(&velPred(realB, 0), -Jlin.x * invMassB);
970 Kokkos::atomic_add(&velPred(realB, 1), -Jlin.y * invMassB);
971 Kokkos::atomic_add(&velPred(realB, 2), -Jlin.z * invMassB);
972 const F4 qB = F4{quat(realB, 0), quat(realB, 1), quat(realB, 2), quat(realB, 3)};
973 const F3 Jl = invRotateVector(qB, scale3(TauB, lambda));
974 const F3 invIB = ld3(invInertia, realB);
975 const F3 dwl{Jl.x * invIB.x, Jl.y * invIB.y, Jl.z * invIB.z};
976 const F3 dww = rotateVector(qB, dwl);
977 Kokkos::atomic_add(&angVelPred(realB, 0), dww.x);
978 Kokkos::atomic_add(&angVelPred(realB, 1), dww.y);
979 Kokkos::atomic_add(&angVelPred(realB, 2), dww.z);
980 }
981 // Tangential warm impulse: project the stored world-frame accumulator onto the CURRENT
982 // tangent plane (the normal moved a little between substeps), write it back so the sweep
983 // accumulator starts consistent, then apply +lt on A / -lt on B at the averaged arms.
984 if (hasT) {
985 const float lenN2 = Kokkos::sqrt(dot3(Nsum, Nsum));
986 if (lenN2 > 1e-9f) {
987 const F3 nhat = scale3(Nsum, 1.0f / lenN2);
988 lt = sub3(lt, scale3(nhat, dot3(lt, nhat)));
989 }
990 warmT(idx, 0) = lt.x;
991 warmT(idx, 1) = lt.y;
992 warmT(idx, 2) = lt.z;
993 Kokkos::atomic_add(&velPred(realA, 0), lt.x * invMassA);
994 Kokkos::atomic_add(&velPred(realA, 1), lt.y * invMassA);
995 Kokkos::atomic_add(&velPred(realA, 2), lt.z * invMassA);
996 {
997 const F4 qA = F4{quat(realA, 0), quat(realA, 1), quat(realA, 2), quat(realA, 3)};
998 const F3 Jl = invRotateVector(qA, cross3v(rAavg, lt));
999 const F3 invIA = ld3(invInertia, realA);
1000 const F3 dwl{Jl.x * invIA.x, Jl.y * invIA.y, Jl.z * invIA.z};
1001 const F3 dww = rotateVector(qA, dwl);
1002 Kokkos::atomic_add(&angVelPred(realA, 0), dww.x);
1003 Kokkos::atomic_add(&angVelPred(realA, 1), dww.y);
1004 Kokkos::atomic_add(&angVelPred(realA, 2), dww.z);
1005 }
1006 if (idB >= 0) {
1007 Kokkos::atomic_add(&velPred(realB, 0), -lt.x * invMassB);
1008 Kokkos::atomic_add(&velPred(realB, 1), -lt.y * invMassB);
1009 Kokkos::atomic_add(&velPred(realB, 2), -lt.z * invMassB);
1010 const F4 qB = F4{quat(realB, 0), quat(realB, 1), quat(realB, 2), quat(realB, 3)};
1011 const F3 Jl = invRotateVector(qB, cross3v(rBavg, scale3(lt, -1.0f)));
1012 const F3 invIB = ld3(invInertia, realB);
1013 const F3 dwl{Jl.x * invIB.x, Jl.y * invIB.y, Jl.z * invIB.z};
1014 const F3 dww = rotateVector(qB, dwl);
1015 Kokkos::atomic_add(&angVelPred(realB, 0), dww.x);
1016 Kokkos::atomic_add(&angVelPred(realB, 1), dww.y);
1017 Kokkos::atomic_add(&angVelPred(realB, 2), dww.z);
1018 }
1019 }
1020 });
1021}
1022
1034 Kokkos::View<const ManifoldC*, CpMem> manifolds;
1035 Kokkos::View<const float*, CpMem> invMass;
1036 Kokkos::View<const float* [3], CpMem> invInertia;
1037 Kokkos::View<const float* [4], CpMem> quat;
1038 Kokkos::View<float* [3], CpMem> velPred;
1039 Kokkos::View<float* [3], CpMem> angVelPred;
1040 Kokkos::View<const int*, CpMem> realIdx;
1044 Kokkos::View<float, CpMem> maxApproach;
1045 // Quasi-static residual (corrections on contacts with |vn0| <= 4 restVelThreshold): the
1046 // multilevel pass's stop criterion. The colored caller aliases this to maxApproach (the
1047 // duplicate atomic_max is idempotent), so main-loop behaviour is unchanged.
1048 Kokkos::View<float, CpMem> maxApproachQS;
1049 Kokkos::View<float*, CpMem> lambdaAcc;
1050 Kokkos::View<const float*, CpMem> vn0;
1051 Kokkos::View<const unsigned char*, CpMem> sideFlag;
1052 Kokkos::View<float* [3], CpMem> lambdaT;
1054 Kokkos::View<const float* [3], CpMem> vt0;
1056 Kokkos::View<const float*, CpMem> posImpulse;
1057 // Event-level (Poisson) restitution release (restitutionModel == 1; both views empty
1058 // otherwise): restBank(idx) is the pair's remaining OWED separation impulse (physical units,
1059 // warm-carried by pair key) and restRel(idx) the per-substep release accumulator (lambda
1060 // units, zeroed each substep). Per-substep Newton restitution stays ALIVE alongside the
1061 // bank — its micro-reflections are genuine returned energy, and the accounting's pR term
1062 // deducts each one from the owed budget so the channels never double-count (measured: forcing
1063 // e = 0 on persistent contacts cost more rebound than the bank recovered). restBank is
1064 // writable: a releasing pair whose own budget rails can DRAW from its bodies' orphan accounts
1065 // (transferred into restBank at the moment of need, so the post-solve accounting sees one
1066 // consistent pair ledger). Same-body contacts never run concurrently (colouring), so the
1067 // in-place body-account read-modify-write is race-free without atomics.
1068 Kokkos::View<float*, CpMem> restBank;
1069 Kokkos::View<float*, CpMem> restRel;
1070 // Event peak approach speed (physical): caps the release separation-velocity target at
1071 // e x vPeak — the event-level rebound speed — so a large flux-banked budget against a light
1072 // partner becomes a SUSTAINED unloading push over many substeps (the Hertz-like collective
1073 // rebound) instead of an impulsive dump (a 190 m/s kick to a 1e-5 kg grain, measured absurd).
1074 Kokkos::View<const float*, CpMem> restVPeak;
1075 // Orphan accounts (see Particles::bodyOrphan): balance + carried event peak speed per REAL
1076 // body. The peak matters as much as the balance — a contact formed late under a decelerating
1077 // impactor only saw the residual approach, so its own e*vPeak target would cap the rebound at
1078 // e x the late-stage speed; the orphaned peak restores the full event's velocity scale.
1079 Kokkos::View<float*, CpMem> restOrphan;
1080 Kokkos::View<const float*, CpMem> restOrphanVPeak;
1081 // Hub-copy slot overrides + split relaxation (docs/contact_solve_framework.md §4.4, §4.5);
1082 // empty = realIdx, no relaxation. Every state access below uses realA / realB.
1084
1088 };
1089
1094 struct Row {
1096 int idB, realA, realB; // idB < 0: wall manifold (realB = idB)
1100 PairVelocity vel; // loaded by gatherRow
1101 float invN, restitution, eMat; // restitution after the material override; weighRow may zero it
1103 float lenN;
1104 F3 vGrowth; // from here on: written by weighRow
1105 float vn, sgn, wTotal;
1106 unsigned char sf;
1108 };
1109
1114 };
1115
1117 KOKKOS_FORCEINLINE_FUNCTION void applyLinear(int real, F3 dLin, float invMass) const {
1118 velPred(real, 0) += dLin.x * invMass;
1119 velPred(real, 1) += dLin.y * invMass;
1120 velPred(real, 2) += dLin.z * invMass;
1121 }
1122
1125 KOKKOS_FORCEINLINE_FUNCTION void applyAngular(int real, F3 dAngWorld, F3 invI, F4 q) const {
1126 const F3 Jl = invRotateVector(q, dAngWorld);
1127 const F3 dwl{Jl.x * invI.x, Jl.y * invI.y, Jl.z * invI.z};
1128 const F3 dww = rotateVector(q, dwl);
1129 angVelPred(real, 0) += dww.x;
1130 angVelPred(real, 1) += dww.y;
1131 angVelPred(real, 2) += dww.z;
1132 }
1133
1136 KOKKOS_FORCEINLINE_FUNCTION void recordCorrection(int idx, float lenN, float corr) const {
1137 Kokkos::atomic_max(&maxApproach(), corr);
1138 if (Kokkos::fabs(vn0(idx)) <= 4.0f * restVelThreshold * lenN)
1139 Kokkos::atomic_max(&maxApproachQS(), corr);
1140 }
1141
1143 KOKKOS_FORCEINLINE_FUNCTION static float normalVelocity(const PairVelocity& v, F3 Nsum, F3 TauA,
1144 F3 TauB, F3 vGrowth) {
1145 float vn = dot3(v.vA, Nsum) + dot3(v.wA, TauA) + dot3(v.vB, F3{-Nsum.x, -Nsum.y, -Nsum.z}) +
1146 dot3(v.wB, TauB);
1147 vn += dot3(vGrowth, Nsum);
1148 return vn;
1149 }
1150
1153 KOKKOS_FORCEINLINE_FUNCTION void gatherRow(int idx, Row& r) const {
1154 using detail::ld3;
1155 const ManifoldC m = manifolds(idx);
1156 const int idA = m.bodyA, idB = m.bodyB;
1157 const int realA = ov.slotA(idx, realIdx(idA));
1158 const int realB = (idB >= 0) ? ov.slotB(idx, realIdx(idB)) : idB;
1159 const float invMassA = invMass(realA);
1160 const float invMassB = (idB >= 0) ? invMass(realB) : 0.0f;
1161 const F3 invIA = ld3(invInertia, realA);
1162 const F3 invIB = (idB >= 0) ? ld3(invInertia, realB) : F3{0, 0, 0};
1163 const F4 qA = F4{quat(realA, 0), quat(realA, 1), quat(realA, 2), quat(realA, 3)};
1164 const F4 qB = (idB >= 0) ? F4{quat(realB, 0), quat(realB, 1), quat(realB, 2), quat(realB, 3)}
1165 : F4{0, 0, 0, 1};
1166 const F3 vA = ld3(velPred, realA), wA = ld3(angVelPred, realA);
1167 F3 vB{0, 0, 0}, wB{0, 0, 0};
1168 const float invN = 1.0f / static_cast<float>(m.num_points);
1169 float restitution = restitutionNormal;
1170 if (idB >= 0) {
1171 vB = ld3(velPred, realB);
1172 wB = ld3(angVelPred, realB);
1173 } else {
1174 vB = scale3(F3{m.wallVel_sum.x, m.wallVel_sum.y, m.wallVel_sum.z}, invN);
1175 }
1176 { // per-wall AND per-pair material override (a < 0 average keeps the global material)
1177 const float ra = m.restitution_sum * invN;
1178 if (ra >= 0.0f)
1179 restitution = ra;
1180 }
1181 const float eMat = restitution; // raw material e (release cap), before the event gates
1182 const F3 nSum{m.normal_sum.x, m.normal_sum.y, m.normal_sum.z};
1185 const F3 rAavg = scale3(F3{m.rA_sum.x, m.rA_sum.y, m.rA_sum.z}, invN);
1186 const F3 rBavg = scale3(F3{m.rB_sum.x, m.rB_sum.y, m.rB_sum.z}, invN);
1187 const float lenN = Kokkos::sqrt(dot3(nSum, nSum));
1188 r = Row{.m = m,
1189 .idB = idB,
1190 .realA = realA,
1191 .realB = realB,
1192 .invMassA = invMassA,
1193 .invMassB = invMassB,
1194 .invIA = invIA,
1195 .invIB = invIB,
1196 .qA = qA,
1197 .qB = qB,
1198 .vel = PairVelocity{.vA = vA, .wA = wA, .vB = vB, .wB = wB},
1199 .invN = invN,
1200 .restitution = restitution,
1201 .eMat = eMat,
1202 .Nsum = nSum,
1203 .TauA = tauA,
1204 .TauB = tauB,
1205 .rAavg = rAavg,
1206 .rBavg = rBavg,
1207 .lenN = lenN};
1208 }
1209
1211 KOKKOS_FORCEINLINE_FUNCTION void weighRow(int idx, Row& r) const {
1212 using detail::genInvMass;
1213 const int idB = r.idB;
1214 const float invMassA = r.invMassA, invMassB = r.invMassB;
1215 const F3 invIA = r.invIA, invIB = r.invIB;
1216 const F4 qA = r.qA, qB = r.qB;
1217 float restitution = r.restitution;
1218 const F3 nSum = r.Nsum, tauA = r.TauA, tauB = r.TauB, rAavg = r.rAavg, rBavg = r.rBavg;
1219 const F3 diffCenters = (idB < 0) ? rAavg : sub3(rAavg, rBavg);
1220 const F3 vGrowth = scale3(diffCenters, growthRate);
1221 const float vn = normalVelocity(r.vel, nSum, tauA, tauB, vGrowth);
1222 const float alignment = dot3(nSum, diffCenters);
1223 const float sgn = (alignment > 0.0f) ? 1.0f : -1.0f;
1224 const float nSq = dot3(nSum, nSum);
1225 float wAn = nSq * invMassA + genInvMass(tauA, invIA, qA);
1226 float wBn = nSq * invMassB + genInvMass(tauB, invIB, qB);
1227 // Shock propagation INSIDE the PGS sweep (Guendelman staged solve, per-contact form):
1228 // sidedness was decided ONCE this substep (computeSideFlags) so the warm start,
1229 // accumulator and every sweep share one consistent ledger. The held ground side absorbs
1230 // the reaction (recursively down to the floor); e is forced 0 on one-sided contacts.
1231 bool applyA = true, applyB = true;
1232 const unsigned char sf = sideFlag(idx);
1233 if (sf == 1) {
1234 wBn = 0.0f;
1235 applyB = false;
1236 restitution = 0.0f;
1237 } else if (sf == 2) {
1238 wAn = 0.0f;
1239 applyA = false;
1240 restitution = 0.0f;
1241 }
1242 const float wTotal = wAn + wBn;
1243 r.vGrowth = vGrowth;
1244 r.vn = vn;
1245 r.sgn = sgn;
1246 r.wTotal = wTotal;
1247 r.sf = sf;
1248 r.applyA = applyA;
1249 r.applyB = applyB;
1250 r.restitution = restitution;
1251 }
1252
1255 KOKKOS_FORCEINLINE_FUNCTION void releaseIncrement(int idx, const Row& r, const ReleaseBudget& b,
1256 float vtil3) const {
1257 const int idB = r.idB, realA = r.realA, realB = r.realB;
1258 const float invMassA = r.invMassA, invMassB = r.invMassB;
1259 const F3 invIA = r.invIA, invIB = r.invIB;
1260 const F4 qA = r.qA, qB = r.qB;
1261 const F3 nSum = r.Nsum, tauA = r.TauA, tauB = r.TauB;
1262 const float eMat = r.eMat, lenN = r.lenN, sgn = r.sgn, wTotal = r.wTotal;
1263 const float vPeak = b.vPeak, orphA = b.orphA, orphB = b.orphB;
1264 float owed = b.owed;
1265 // Symmetric release: both endpoints are pushed. (A one-sided variant that held a
1266 // grounded lower side was measured WORSE on the 25k Dosta impact — +0.60 vs +0.88
1267 // rebound — because the light partner's downward reaction is what re-compresses and
1268 // re-releases the layers below; it was retired with the env A/B in 1.0.0.)
1269 const bool relA = true, relB = (idB >= 0);
1270 const float wRel = wTotal;
1271 if (wRel > 0.0f) {
1272 // Separation-velocity target: the event-level rebound speed e x vPeak. The budget is
1273 // enforced by the accumulator clamp alone — folding it into the velocity target
1274 // (owed * wRel) prematurely stalls a one-sided release against a heavy impactor
1275 // (owed/m_ball ~ cm/s) with most of the budget unspent. Physical velocity -> vtil
1276 // units is x lenN.
1277 const float vTphys = eMat * vPeak;
1278 const float targetR = -vTphys * lenN;
1279 const float dpR = (vtil3 - targetR) / wRel;
1280 float cap = owed / lenN; // physical budget in lambda units
1281 const float rOld = restRel(idx);
1282 float rNew = rOld + dpR;
1283 if (rNew < 0.0f)
1284 rNew = 0.0f;
1285 // Own budget railed with orphan balance at the endpoints: draw the shortfall from the
1286 // body accounts INTO the pair bank (heavier-first order is irrelevant; drained in
1287 // sequence). The drawn amount is spent by this very increment, so the post-solve
1288 // accounting's owed -= released cancels it exactly.
1289 if (rNew > cap && (orphA > 0.0f || orphB > 0.0f)) {
1290 const float draw = drawOrphans(realA, realB, (rNew - cap) * lenN, orphA, orphB);
1291 if (draw > 0.0f) {
1292 owed += draw;
1293 restBank(idx) = owed;
1294 cap = owed / lenN;
1295 }
1296 }
1297 if (rNew > cap)
1298 rNew = cap;
1299 const float dR = rNew - rOld;
1300 if (dR != 0.0f) {
1301 restRel(idx) = rNew;
1302 recordCorrection(idx, lenN, Kokkos::fabs(dR) * wRel / lenN);
1303 const float lambdaR = -sgn * dR;
1304 const F3 JlinR = scale3(nSum, lambdaR);
1305 if (relA) {
1306 applyLinear(realA, JlinR, invMassA);
1307 applyAngular(realA, scale3(tauA, lambdaR), invIA, qA);
1308 }
1309 if (relB) {
1310 applyLinear(realB, F3{-JlinR.x, -JlinR.y, -JlinR.z}, invMassB);
1311 applyAngular(realB, scale3(tauB, lambdaR), invIB, qB);
1312 }
1313 }
1314 }
1315 }
1316
1319 KOKKOS_FORCEINLINE_FUNCTION float drawOrphans(int realA, int realB, float need, float orphA,
1320 float orphB) const {
1321 float draw = 0.0f;
1322 if (orphA > 0.0f) {
1323 const float d = Kokkos::fmin(need, orphA);
1324 restOrphan(realA) = orphA - d;
1325 need -= d;
1326 draw += d;
1327 }
1328 if (need > 0.0f && orphB > 0.0f) {
1329 const float d = Kokkos::fmin(need, orphB);
1330 restOrphan(realB) = orphB - d;
1331 draw += d;
1332 }
1333 return draw;
1334 }
1335
1336 KOKKOS_FUNCTION void solveOne(int idx) const {
1337 using detail::genInvMass;
1338 using detail::ld3;
1339 {
1340 Row r;
1341 gatherRow(idx, r);
1342 if (r.lenN < 1e-9f)
1343 return;
1344 weighRow(idx, r);
1345 if (r.wTotal <= 0.0f)
1346 return;
1347 // Restitution bias on the PRE-SOLVE approach (resting threshold as in the one-shot path).
1348 const float v0til = r.sgn * vn0(idx);
1349 const ManifoldC m = r.m;
1350 const int idB = r.idB, realA = r.realA, realB = r.realB;
1351 const float invMassA = r.invMassA, invMassB = r.invMassB;
1352 const F3 invIA = r.invIA, invIB = r.invIB;
1353 const F4 qA = r.qA, qB = r.qB;
1354 // eMat is unused here since A3 (the release increment reads r.eMat); removing this unpack
1355 // changes GCC's FMA pairing on contracting host builds (code-health WO-14), so it stays.
1356 const float invN = r.invN, eMat = r.eMat;
1357 const F3 Nsum = r.Nsum, TauA = r.TauA, TauB = r.TauB, rAavg = r.rAavg, rBavg = r.rBavg;
1358 const float lenN = r.lenN;
1359 const F3 vGrowth = r.vGrowth;
1360 const float sgn = r.sgn, wTotal = r.wTotal;
1361 const unsigned char sf = r.sf;
1362 const bool applyA = r.applyA, applyB = r.applyB;
1363 float restitution = r.restitution;
1364 const float vn = r.vn;
1365 if (Kokkos::fabs(vn0(idx)) < restVelThreshold * lenN)
1366 restitution = 0.0f;
1367 // Poisson mode keeps per-substep Newton restitution ALIVE alongside the bank: the
1368 // micro-reflections it produces are genuine returned energy (measured: forcing e = 0 on
1369 // persistent contacts cost more rebound than the bank recovered), and the accounting's pR
1370 // term deducts every reflection from the owed budget, so the two channels never
1371 // double-count.
1372 //
1373 // The restitution target is Moreau's (docs/contact_physics_followups.md §4, decided
1374 // 2026-09-26): -e v0til on EVERY closed contact whose pre-solve |vn0| reaches the resting
1375 // threshold (restitution is already 0 below it and on one-sided contacts). A pre-separating
1376 // pair driven into approach may approach up to e |v0til| before it resists. For a uniform e
1377 // one converged substep changes the kinetic energy by -1/2 (1-e)/(1+e) lambda^T W lambda <= 0
1378 // (§4.1); Newton's 0 for a pre-separating contact CREATED energy (+13 % in one step of a
1379 // dense e = 1 cluster). The Poisson bank (restRel non-empty) keeps Newton's per-substep
1380 // targets, whose micro-reflections its accounting relies on (R-C4).
1381 const float target =
1382 restRel.extent(0) > 0
1383 ? ((v0til > 0.0f) ? -restitution * v0til : 0.0f)
1384 : ((Kokkos::fabs(vn0(idx)) >= restVelThreshold * lenN) ? -restitution * v0til : 0.0f);
1385 const float vtil = sgn * vn;
1386 float dp = (vtil - target) / wTotal;
1387 if (ov.relax(realA, realB))
1388 dp *= ov.omega; // split relaxation before the clamp (§4.5; omega_vel = 1)
1389 const float pOld = lambdaAcc(idx);
1390 float pNew = pOld + dp;
1391 if (pNew < 0.0f)
1392 pNew = 0.0f;
1393 const float dApplied = pNew - pOld;
1394 if (dApplied != 0.0f) {
1395 lambdaAcc(idx) = pNew;
1396 recordCorrection(idx, lenN, Kokkos::fabs(dApplied) * wTotal / lenN);
1397 const float lambda = -sgn * dApplied;
1398 const F3 Jlin = scale3(Nsum, lambda);
1399 const F3 JangA = scale3(TauA, lambda);
1400 const F3 JangB = scale3(TauB, lambda);
1401 if (applyA) {
1402 applyLinear(realA, Jlin, invMassA);
1403 applyAngular(realA, JangA, invIA, qA);
1404 }
1405 if (idB >= 0 && applyB) {
1406 applyLinear(realB, F3{-Jlin.x, -Jlin.y, -Jlin.z}, invMassB);
1407 applyAngular(realB, JangB, invIB, qB);
1408 }
1409 } // dApplied != 0
1410
1411 // ---- Event-level (Poisson) restitution release ----
1412 // A pair with banked compression (restBank > 0) that is NOT in a kinetic approach pushes
1413 // toward the event's separation-velocity target -owed*w — what releasing the full remaining
1414 // budget delivers against the pair's effective mass, i.e. the event-level rebound speed.
1415 // The push runs through its OWN accumulator clamped to [0, owed] (the friction-cone-shaped
1416 // budget cap): a free pair leaves at the target speed, while a loaded chain re-absorbs the
1417 // attempt through lambda >= 0 on its other contacts with the total injected impulse bounded
1418 // by the budget — velocity-targeted, never impulsive, no unbounded force fight. One-sided
1419 // (side-flagged) contacts are held externally and never release. Spent budget is deducted
1420 // once per substep by updateRestitutionBank. Unloading detection: KINETICALLY
1421 // separating pre-solve approach (beyond the resting threshold) — jitter separations during
1422 // compression (position-solve pushback, chain oscillation) fire sub-threshold every substep
1423 // and would drain the bank as fast as it fills (measured: bank plateaued at ~1/6 of the
1424 // event flux with a v0til < 0 gate); the genuine rebound onset separates kinetically.
1425 if (restRel.extent(0) > 0 && sf == 0 && v0til < -restVelThreshold * lenN) {
1426 float owed = restBank(idx);
1427 float vPeak = restVPeak.extent(0) > 0 ? restVPeak(idx) : 0.0f;
1428 // Orphan availability at the endpoints: makes budget-less fresh pairs under an event
1429 // carrier eligible, and lifts the velocity target to the orphaned event peak.
1430 float orphA = 0.0f, orphB = 0.0f;
1431 if (restOrphan.extent(0) > 0) {
1432 orphA = restOrphan(realA);
1433 if (orphA > 0.0f)
1434 vPeak = Kokkos::fmax(vPeak, restOrphanVPeak(realA));
1435 if (idB >= 0) {
1436 orphB = restOrphan(realB);
1437 if (orphB > 0.0f)
1438 vPeak = Kokkos::fmax(vPeak, restOrphanVPeak(realB));
1439 }
1440 }
1441 if ((owed > 0.0f || orphA > 0.0f || orphB > 0.0f) && vPeak > 0.0f) {
1442 const F3 vA3 = ld3(velPred, realA), wA3 = ld3(angVelPred, realA);
1443 F3 vB3{0, 0, 0}, wB3{0, 0, 0};
1444 if (idB >= 0) {
1445 vB3 = ld3(velPred, realB);
1446 wB3 = ld3(angVelPred, realB);
1447 } else {
1448 vB3 = scale3(F3{m.wallVel_sum.x, m.wallVel_sum.y, m.wallVel_sum.z}, invN);
1449 }
1450 float vn3 = dot3(vA3, Nsum) + dot3(wA3, TauA) + dot3(vB3, F3{-Nsum.x, -Nsum.y, -Nsum.z}) +
1451 dot3(wB3, TauB);
1452 vn3 += dot3(vGrowth, Nsum);
1453 const float vtil3 = sgn * vn3;
1455 idx, r, ReleaseBudget{.owed = owed, .vPeak = vPeak, .orphA = orphA, .orphB = orphB},
1456 vtil3);
1457 }
1458 }
1459
1460 // ---- Friction cone (sequential tangential impulse) ----
1461 // Accumulated world-frame tangential impulse lambdaT on body A, updated by the same
1462 // colored nonlinear GS: incremental impulse -vt/w_t along the current slip direction,
1463 // then projection onto the Coulomb disc |lambdaT| <= mu * lambdaN (physical impulse:
1464 // the normal accumulator is scaled by |Nsum|). Static stick falls out naturally: at
1465 // vt = 0 the accumulator holds whatever tangential load the cone admits. Sidedness
1466 // mirrors the normal solve (a held side neither moves nor adds compliance).
1467 {
1468 float mu = frictionDynamic;
1469 const float fa = m.friction_sum * invN;
1470 if (fa >= 0.0f)
1471 mu = fa;
1472 F3 ltOld{lambdaT(idx, 0), lambdaT(idx, 1), lambdaT(idx, 2)};
1473 const bool haveOld = (ltOld.x != 0.0f || ltOld.y != 0.0f || ltOld.z != 0.0f);
1474 if (mu > 0.0f || haveOld) {
1475 const F3 nhat = scale3(Nsum, 1.0f / lenN);
1476 const F3 vA2 = ld3(velPred, realA), wA2 = ld3(angVelPred, realA);
1477 F3 vB2{0, 0, 0}, wB2{0, 0, 0};
1478 if (idB >= 0) {
1479 vB2 = ld3(velPred, realB);
1480 wB2 = ld3(angVelPred, realB);
1481 } else {
1482 vB2 = scale3(F3{m.wallVel_sum.x, m.wallVel_sum.y, m.wallVel_sum.z}, invN);
1483 }
1484 const F3 vrel = sub3(add3(vA2, cross3v(wA2, rAavg)), add3(vB2, cross3v(wB2, rBavg)));
1485 const F3 vt = sub3(vrel, scale3(nhat, dot3(vrel, nhat)));
1486 // Walton tangential restitution: for a COLLIDING contact the target surface
1487 // velocity is -beta * vt0 (pre-solve tangential velocity); sustained contacts
1488 // (below the resting threshold) and one-sided stabilization contacts run beta = 0
1489 // -- the same event classification that gates normal restitution. The cone clamp
1490 // below turns this into the stick/slide transition of the (e, mu, beta) law.
1491 float beta = restitutionTangent;
1492 if (beta != 0.0f && (sf != 0 || Kokkos::fabs(vn0(idx)) < restVelThreshold * lenN))
1493 beta = 0.0f;
1494 F3 vtErr = vt;
1495 if (beta != 0.0f && vt0.extent(0) > 0) {
1496 F3 v0{vt0(idx, 0), vt0(idx, 1), vt0(idx, 2)};
1497 v0 = sub3(v0, scale3(nhat, dot3(v0, nhat))); // current tangent plane
1498 vtErr = add3(vt, scale3(v0, beta));
1499 }
1500 const float vtLen = Kokkos::sqrt(dot3(vtErr, vtErr));
1501 F3 ltNew = ltOld;
1502 float wT = invMassA + invMassB;
1503 if (vtLen > 1e-9f) {
1504 const F3 that = scale3(vtErr, 1.0f / vtLen);
1505 float wAt = (sf == 2) ? 0.0f : invMassA + genInvMass(cross3v(rAavg, that), invIA, qA);
1506 float wBt = (sf == 1 || idB < 0)
1507 ? 0.0f
1508 : invMassB + genInvMass(cross3v(rBavg, that), invIB, qB);
1509 wT = wAt + wBt;
1510 if (wT > 1e-9f)
1511 ltNew = add3(ltOld, scale3(that, -vtLen / wT));
1512 }
1513 ltNew = sub3(ltNew, scale3(nhat, dot3(ltNew, nhat)));
1514 // Coulomb bound = mu * TOTAL normal load: velocity-impulse channel (lambdaAcc,
1515 // physical impulse = lambdaAcc * |Nsum|) + the position-projection channel carried
1516 // from last substep (already physical impulse units).
1517 float nTot = Kokkos::fmax(lambdaAcc(idx), 0.0f) * lenN;
1518 // The carry is a QUASI-STATIC corrector: for colliding contacts the one-substep lag
1519 // double-counts (crater contacts already carry a large velocity impulse) -- gate by
1520 // the same event classification as e and beta.
1521 if (posImpulse.extent(0) > 0 && Kokkos::fabs(vn0(idx)) < restVelThreshold * lenN)
1522 nTot += Kokkos::fmax(posImpulse(idx), 0.0f);
1523 const float bound = mu * nTot;
1524 const float ltLen = Kokkos::sqrt(dot3(ltNew, ltNew));
1525 if (ltLen > bound)
1526 ltNew = (bound > 0.0f) ? scale3(ltNew, bound / ltLen) : F3{0, 0, 0};
1527 const F3 dApp = sub3(ltNew, ltOld);
1528 if (dApp.x != 0.0f || dApp.y != 0.0f || dApp.z != 0.0f) {
1529 lambdaT(idx, 0) = ltNew.x;
1530 lambdaT(idx, 1) = ltNew.y;
1531 lambdaT(idx, 2) = ltNew.z;
1532 const float dLen = Kokkos::sqrt(dot3(dApp, dApp));
1533 if (wT > 1e-9f)
1534 recordCorrection(idx, lenN, dLen * wT);
1535 if (applyA) {
1536 applyLinear(realA, dApp, invMassA);
1537 applyAngular(realA, cross3v(rAavg, dApp), invIA, qA);
1538 }
1539 if (idB >= 0 && applyB) {
1540 applyLinear(realB, F3{-dApp.x, -dApp.y, -dApp.z}, invMassB);
1541 applyAngular(realB, cross3v(rBavg, scale3(dApp, -1.0f)), invIB, qB);
1542 }
1543 }
1544 }
1545 }
1546 }
1547 }
1548};
1549
1554 Kokkos::View<const float*, CpMem> invMass;
1555 Kokkos::View<const float* [3], CpMem> invInertia;
1556 Kokkos::View<const float* [4], CpMem> quat;
1557 Kokkos::View<float* [3], CpMem> velPred;
1558 Kokkos::View<float* [3], CpMem> angVelPred;
1559 Kokkos::View<const int*, CpMem> realIdx;
1561};
1562
1565 Kokkos::View<float*, CpMem> bank, rel;
1566 Kokkos::View<const float*, CpMem> vPeak;
1567 Kokkos::View<float*, CpMem> orphan, orphanPeak; // orphanPeak writable (the copies' seeds/folds)
1568};
1569
1575 Kokkos::View<const ManifoldC*, CpMem> manifolds, const VelocitySweepBodies& bodies,
1576 float growthRate, float restitutionNormal, float restVelThreshold,
1577 Kokkos::View<float, CpMem> maxApproach, Kokkos::View<float, CpMem> maxApproachQS,
1578 Kokkos::View<float*, CpMem> lambdaAcc, Kokkos::View<const float*, CpMem> vn0,
1579 Kokkos::View<const unsigned char*, CpMem> sideFlag, Kokkos::View<float* [3], CpMem> lambdaT,
1580 float frictionDynamic, Kokkos::View<const float* [3], CpMem> vt0, float restitutionTangent,
1581 Kokkos::View<const float*, CpMem> posImpulse, const PoissonBankViews& bank) {
1582 return PGSManifoldSweep{manifolds, bodies.invMass,
1583 bodies.invInertia, bodies.quat,
1584 bodies.velPred, bodies.angVelPred,
1585 bodies.realIdx, growthRate,
1586 restitutionNormal, restVelThreshold,
1587 maxApproach, maxApproachQS.data() ? maxApproachQS : maxApproach,
1588 lambdaAcc, vn0,
1589 sideFlag, lambdaT,
1590 frictionDynamic, vt0,
1591 restitutionTangent, posImpulse,
1592 bank.bank, bank.rel,
1593 bank.vPeak, bank.orphan,
1594 bank.orphanPeak, bodies.ov};
1595}
1596
1601inline bool solveVelocityPGS(const PGSManifoldSweep& f, int numManifolds,
1602 const ColorSchedule& sched, const FusedLoopSpec* loop = nullptr) {
1603 const Kokkos::View<const int*, CpMem> mColor = sched.color;
1604 const int numColors = sched.numColors;
1605 const Kokkos::View<const int*, CpMem> colorPerm = sched.perm;
1606 const std::vector<int>* colorOffs = sched.offs;
1607 const FusedSweepCtx* fused = sched.fused;
1608 CpExec space;
1609 // Fused mode (CUDA): one persistent kernel iterates the colours device-side with a grid
1610 // barrier between them — same per-manifold math, same colour ordering, bit-identical to the
1611 // launch loop below (see solver_fused.hpp). Loop mode additionally iterates the whole
1612 // adaptive loop on-device against the residual the caller's stop would have read.
1613#ifdef KOKKOS_ENABLE_CUDA
1614 if (loop) {
1615 if (fused && fused->maxBucket > 0 && colorOffs)
1616 return demLaunchFusedSweepLoop(space, f, colorPerm, *fused, numColors, *loop,
1617 f.maxApproachQS.data());
1618 return false;
1619 }
1620 if (fused && fused->maxBucket > 0 && colorOffs &&
1621 demLaunchFusedColorSweep(space, f, colorPerm, *fused, numColors))
1622 return true;
1623#else
1624 (void)fused;
1625 if (loop)
1626 return false;
1627#endif
1628 // Dense-bucket mode (colorOffs from buildColorBuckets): each colour launch covers only
1629 // its own manifolds instead of scanning all of them — bit-identical (colour classes are
1630 // body-disjoint). No fence: the caller's residual readback synchronizes, and an explicit fence
1631 // here would serialize host submission with GPU execution (the step is submission-bound).
1632 for (int color = 0; color < numColors; ++color) {
1633 if (colorOffs) {
1634 const int b = (*colorOffs)[color], e = (*colorOffs)[color + 1];
1635 if (b == e)
1636 continue;
1637 Kokkos::parallel_for(
1638 "peclet::dem::solve_velocity_pgs", Kokkos::RangePolicy<CpExec>(space, b, e),
1639 KOKKOS_LAMBDA(int i2) { f.solveOne(colorPerm(i2)); });
1640 } else {
1641 Kokkos::parallel_for(
1642 "peclet::dem::solve_velocity_pgs", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
1643 KOKKOS_LAMBDA(int idx) {
1644 if (mColor(idx) == color)
1645 f.solveOne(idx);
1646 });
1647 }
1648 }
1649 return true;
1650}
1651
1660inline void buildLevelColorBuckets(Kokkos::View<const ManifoldC*, CpMem> manifolds,
1661 int numManifolds, Kokkos::View<const int*, CpMem> realIdx,
1662 Kokkos::View<const int*, CpMem> mColor,
1663 Kokkos::View<const int*, CpMem> heights,
1664 Kokkos::View<int*, CpMem> keys, Kokkos::View<int*, CpMem> perm,
1665 std::vector<std::pair<int, int>>& buckets) {
1666 buckets.clear();
1667 if (numManifolds <= 0)
1668 return;
1669 CpExec space;
1670 Kokkos::parallel_for(
1671 "peclet::dem::level_keys", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
1672 KOKKOS_LAMBDA(int idx) {
1673 perm(idx) = idx;
1674 const int c = mColor(idx);
1675 const ManifoldC m = manifolds(idx);
1676 if (m.num_points <= 0 || c < 0) {
1677 keys(idx) = INT_MAX;
1678 return;
1679 }
1680 int h = heights(realIdx(m.bodyA));
1681 if (m.bodyB >= 0) {
1682 const int hB = heights(realIdx(m.bodyB));
1683 if (hB < h)
1684 h = hB;
1685 }
1686 if (h > 1023)
1687 h = 1023;
1688 keys(idx) = h * 64 + c;
1689 });
1690 const auto rng = Kokkos::pair<int, int>(0, numManifolds);
1691 auto kd = Kokkos::subview(keys, rng);
1692 auto pd = Kokkos::subview(perm, rng);
1693 Kokkos::Experimental::sort_by_key(space, kd, pd);
1694 auto hk = Kokkos::create_mirror_view(kd);
1695 Kokkos::deep_copy(space, hk, kd);
1696 for (int b = 0; b < numManifolds && hk(b) != INT_MAX;) {
1697 int e = b + 1;
1698 while (e < numManifolds && hk(e) == hk(b))
1699 ++e;
1700 buckets.emplace_back(b, e);
1701 b = e;
1702 }
1703}
1704
1711inline void solveVelocityPGSBuckets(const PGSManifoldSweep& f, Kokkos::View<const int*, CpMem> perm,
1712 const std::vector<std::pair<int, int>>& buckets, bool topDown) {
1713 CpExec space;
1714 const int nb = static_cast<int>(buckets.size());
1715 for (int i = 0; i < nb; ++i) {
1716 const auto [b, e] = buckets[topDown ? nb - 1 - i : i];
1717 Kokkos::parallel_for(
1718 "peclet::dem::solve_velocity_pgs_lvl", Kokkos::RangePolicy<CpExec>(space, b, e),
1719 KOKKOS_LAMBDA(int i2) { f.solveOne(perm(i2)); });
1720 }
1721 space.fence();
1722}
1723
1728KOKKOS_INLINE_FUNCTION int xPopcount(unsigned long long m) {
1729 int n = 0;
1730 while (m != 0ull) {
1731 m &= m - 1ull;
1732 ++n;
1733 }
1734 return n;
1735}
1736KOKKOS_INLINE_FUNCTION int xHolder(unsigned long long mask, long long t, int numColors) {
1737 const int tc = static_cast<int>(t % numColors);
1738 if ((mask >> tc) & 1ull)
1739 return tc;
1740 int j = static_cast<int>(t % xPopcount(mask));
1741 for (int b = 0; b < 64; ++b)
1742 if ((mask >> b) & 1ull) {
1743 if (j == 0)
1744 return b;
1745 --j;
1746 }
1747 return -1; // unreachable: popcount(mask) >= 2 at every call
1748}
1749
1753 Kokkos::View<const unsigned long long*, CpMem> mask;
1754 int color = 0, numColors = 1;
1755 long long t = 0;
1756 KOKKOS_INLINE_FUNCTION bool fires(int slotA, int slotB) const {
1757 if (mask.extent(0) == 0)
1758 return true;
1759 const unsigned long long mA = mask(slotA);
1760 if (xPopcount(mA) >= 2 && xHolder(mA, t, numColors) != color)
1761 return false;
1762 if (slotB >= 0) {
1763 const unsigned long long mB = mask(slotB);
1764 if (xPopcount(mB) >= 2 && xHolder(mB, t, numColors) != color)
1765 return false;
1766 }
1767 return true;
1768 }
1769};
1770
1773inline void computeXGate(Kokkos::View<const ManifoldC*, CpMem> manifolds, int nm,
1774 Kokkos::View<const int*, CpMem> realIdx,
1775 Kokkos::View<const unsigned long long*, CpMem> velMask,
1776 Kokkos::View<unsigned char*, CpMem> gate, int color, int numColors,
1777 long long t) {
1778 Kokkos::parallel_for(
1779 "peclet::dem::x_gate", Kokkos::RangePolicy<CpExec>(0, nm), KOKKOS_LAMBDA(int idx) {
1780 const ManifoldC m = manifolds(idx);
1781 bool fire = true;
1782 const unsigned long long mA = velMask(realIdx(m.bodyA));
1783 if (xPopcount(mA) >= 2 && xHolder(mA, t, numColors) != color)
1784 fire = false;
1785 if (m.bodyB >= 0) {
1786 const unsigned long long mB = velMask(realIdx(m.bodyB));
1787 if (xPopcount(mB) >= 2 && xHolder(mB, t, numColors) != color)
1788 fire = false;
1789 }
1790 gate(idx) = fire ? 1 : 0;
1791 });
1792}
1793
1794inline long long countUnfired(Kokkos::View<const unsigned char*, CpMem> gate, int nm) {
1795 long long n = 0;
1796 Kokkos::parallel_reduce(
1797 "peclet::dem::x_unfired", Kokkos::RangePolicy<CpExec>(0, nm),
1798 KOKKOS_LAMBDA(int idx, long long& acc) { acc += gate(idx) == 0 ? 1 : 0; }, n);
1799 return n;
1800}
1801
1805 Kokkos::View<const ManifoldC*, CpMem> manifolds;
1807 Kokkos::View<const int*, CpMem> mColor;
1809};
1810
1813KOKKOS_FORCEINLINE_FUNCTION F3 angularDelta(F3 jang, F3 invI, F4 q) {
1814 const F3 Jl = invRotateVector(q, jang);
1815 const F3 dwl{Jl.x * invI.x, Jl.y * invI.y, Jl.z * invI.z};
1816 return rotateVector(q, dwl);
1817}
1818
1826inline void solveVelocityColoredGS(const ColoredManifolds& colored,
1827 const VelocitySweepBodies& bodies, float growthRate,
1828 float restitutionNormal, float restVelThreshold,
1829 Kokkos::View<float, CpMem> maxApproach, XGateSpec xg = {},
1830 const ShockPropagation& shock = {}) {
1831 const Kokkos::View<const ManifoldC*, CpMem> manifolds = colored.manifolds;
1832 const int numManifolds = colored.numManifolds, numColors = colored.numColors;
1833 const Kokkos::View<const int*, CpMem> mColor = colored.mColor;
1834 const Kokkos::View<const float*, CpMem> invMass = bodies.invMass;
1835 const Kokkos::View<const float* [3], CpMem> invInertia = bodies.invInertia;
1836 const Kokkos::View<const float* [4], CpMem> quat = bodies.quat;
1837 const Kokkos::View<float* [3], CpMem> velPred = bodies.velPred, angVelPred = bodies.angVelPred;
1838 const Kokkos::View<const int*, CpMem> realIdx = bodies.realIdx;
1839 const SlotOverride ov = bodies.ov;
1840 const Kokkos::View<const unsigned char*, CpMem> persistent = shock.persistent,
1841 grounded = shock.grounded;
1842 const Kokkos::View<const float* [3], CpMem> posPred = shock.posPred;
1843 const F3 gHat = shock.gHat;
1844 using detail::genInvMass;
1845 using detail::ld3;
1846 CpExec space;
1847 const bool usePersist = persistent.extent(0) > 0;
1848 for (int color = 0; color < numColors; ++color) {
1849 Kokkos::parallel_for(
1850 "peclet::dem::solve_velocity_gs", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
1851 KOKKOS_LAMBDA(int idx) {
1852 if (mColor(idx) != color)
1853 return;
1854 const ManifoldC m = manifolds(idx);
1855
1856 const int idA = m.bodyA, idB = m.bodyB;
1857 // hub-copy slot overrides (§4.4; empty = realIdx): every state access uses realA/B
1858 const int realA = ov.slotA(idx, realIdx(idA));
1859 const int realB = (idB >= 0) ? ov.slotB(idx, realIdx(idB)) : idB;
1860
1861 const float invMassA = invMass(realA);
1862 const float invMassB = (idB >= 0) ? invMass(realB) : 0.0f;
1863 const F3 invIA = ld3(invInertia, realA);
1864 const F3 invIB = (idB >= 0) ? ld3(invInertia, realB) : F3{0, 0, 0};
1865 const F4 qA = F4{quat(realA, 0), quat(realA, 1), quat(realA, 2), quat(realA, 3)};
1866 const F4 qB = (idB >= 0)
1867 ? F4{quat(realB, 0), quat(realB, 1), quat(realB, 2), quat(realB, 3)}
1868 : F4{0, 0, 0, 1};
1869
1870 const F3 vA = ld3(velPred, realA), wA = ld3(angVelPred, realA);
1871 F3 vB{0, 0, 0}, wB{0, 0, 0};
1872 if (idB >= 0) {
1873 vB = ld3(velPred, realB);
1874 wB = ld3(angVelPred, realB);
1875 }
1876
1877 const F3 Nsum{m.normal_sum.x, m.normal_sum.y, m.normal_sum.z};
1878 const F3 TauA{m.torque_armA_sum.x, m.torque_armA_sum.y, m.torque_armA_sum.z};
1879 const F3 TauB{m.torque_armB_sum.x, m.torque_armB_sum.y, m.torque_armB_sum.z};
1880
1881 const float invN = 1.0f / static_cast<float>(m.num_points);
1882
1883 float restitution = restitutionNormal;
1884 if (idB < 0)
1885 vB = scale3(F3{m.wallVel_sum.x, m.wallVel_sum.y, m.wallVel_sum.z}, invN);
1886 { // per-wall AND per-pair material override (a < 0 average keeps the global material)
1887 const float ra = m.restitution_sum * invN;
1888 if (ra >= 0.0f)
1889 restitution = ra;
1890 }
1891 const F3 rAavg = scale3(F3{m.rA_sum.x, m.rA_sum.y, m.rA_sum.z}, invN);
1892 const F3 rBavg = scale3(F3{m.rB_sum.x, m.rB_sum.y, m.rB_sum.z}, invN);
1893
1894 const float lenN = Kokkos::sqrt(dot3(Nsum, Nsum));
1895 if (lenN < 1e-9f)
1896 return;
1897
1898 const F3 diffCenters = (idB < 0) ? rAavg : sub3(rAavg, rBavg);
1899 const F3 vGrowth = scale3(diffCenters, growthRate);
1900
1901 float vn = dot3(vA, Nsum) + dot3(wA, TauA) + dot3(vB, F3{-Nsum.x, -Nsum.y, -Nsum.z}) +
1902 dot3(wB, TauB);
1903 vn += dot3(vGrowth, Nsum);
1904
1905 const float alignment = dot3(Nsum, diffCenters);
1906 if (alignment > 0.0f) {
1907 if (vn < 0.0f)
1908 return;
1909 } else {
1910 if (vn > 0.0f)
1911 return;
1912 }
1913
1914 const float Nsq = dot3(Nsum, Nsum);
1915 float wA_n = Nsq * invMassA + genInvMass(TauA, invIA, qA);
1916 float wB_n = Nsq * invMassB + genInvMass(TauB, invIB, qB);
1917 // Shock propagation for persistent loaded contacts -- see solveVelocity and ShockGate.
1918 bool applyA = true, applyB = true;
1919 if (usePersist && persistent(idx) != 0 && idB >= 0) {
1920 const ShockGate gate(sub3(ldF3(posPred, idA), ldF3(posPred, idB)), gHat,
1921 restVelThreshold);
1922 if (gate.lowerB(vB, gHat) && grounded(realB) > 0) {
1923 wB_n = 0.0f;
1924 applyB = false;
1925 restitution = 0.0f; // shock pass is inelastic — see solveVelocity
1926 } else if (gate.lowerA(vA, gHat) && grounded(realA) > 0) {
1927 wA_n = 0.0f;
1928 applyA = false;
1929 restitution = 0.0f;
1930 }
1931 }
1932 const float wTotal = wA_n + wB_n;
1933 if (wTotal <= 0.0f)
1934 return;
1935
1936 // Record this approaching pair's physical approach speed for the adaptive stop: the
1937 // caller ends the velocity loop once no manifold approaches faster than the resting
1938 // threshold.
1939 Kokkos::atomic_max(&maxApproach(), Kokkos::fabs(vn) / lenN);
1940 // Rank-level X (docs/contact_solve_framework.md §1.4): a gated contact whose rank does
1941 // not hold one of its rank-split bodies in this sync interval records its approach (the
1942 // stop must not end while it still approaches) but writes nothing.
1943 if (!xg.fires(realIdx(idA), idB >= 0 ? realIdx(idB) : -1))
1944 return;
1945
1946 if (Kokkos::fabs(vn) < restVelThreshold * lenN)
1947 restitution = 0.0f;
1948
1949 const float lambda = (-restitution * vn - vn) / wTotal;
1950
1951 const F3 Jlin = scale3(Nsum, lambda);
1952 const F3 JangA = scale3(TauA, lambda);
1953 const F3 JangB = scale3(TauB, lambda);
1954
1955 // Linear + angular delta on A (dw_world = R (invI_local * (R^T Jang))), applied in place.
1956 if (applyA) {
1957 velPred(realA, 0) += Jlin.x * invMassA;
1958 velPred(realA, 1) += Jlin.y * invMassA;
1959 velPred(realA, 2) += Jlin.z * invMassA;
1960 {
1961 const F3 dww = angularDelta(JangA, invIA, qA);
1962 angVelPred(realA, 0) += dww.x;
1963 angVelPred(realA, 1) += dww.y;
1964 angVelPred(realA, 2) += dww.z;
1965 }
1966 }
1967 if (idB >= 0 && applyB) {
1968 velPred(realB, 0) += -Jlin.x * invMassB;
1969 velPred(realB, 1) += -Jlin.y * invMassB;
1970 velPred(realB, 2) += -Jlin.z * invMassB;
1971 const F3 dww = angularDelta(JangB, invIB, qB);
1972 angVelPred(realB, 0) += dww.x;
1973 angVelPred(realB, 1) += dww.y;
1974 angVelPred(realB, 2) += dww.z;
1975 }
1976 });
1977 // No host fence here: consecutive parallel_for on one execution space are stream-ordered on the
1978 // device, so colour c+1's kernel already observes colour c's in-place writes (the Gauss–Seidel
1979 // dependency). A per-colour fence would only stall the host. One fence after the sweep
1980 // suffices.
1981 }
1982 space.fence();
1983}
1984
1985} // namespace peclet::dem
1986
1987#endif // DEM_SOLVER_VELOCITY_HPP
dem — portable (Kokkos) contact->manifold reduction, replacing the thrust-based reduce_contacts_to_ma...
dem — portable POD types + math + analytic SDFs shared by the Kokkos kernel ports.
float genInvMass(F3 tau, F3 invIlocal, F4 q)
F3 ld3(Kokkos::View< const float *[3], CpMem > v, int i)
int xHolder(unsigned long long mask, long long t, int numColors)
void solveVelocityPGSBuckets(const PGSManifoldSweep &f, Kokkos::View< const int *, CpMem > perm, const std::vector< std::pair< int, int > > &buckets, bool topDown)
Level-ordered symmetric sweep: launch one PGS kernel per (level, colour) bucket, ascending (bottom-up...
void solveVelocityColoredGS(const ColoredManifolds &colored, const VelocitySweepBodies &bodies, float growthRate, float restitutionNormal, float restVelThreshold, Kokkos::View< float, CpMem > maxApproach, XGateSpec xg={}, const ShockPropagation &shock={})
Colored Gauss–Seidel normal-restitution solve: sweep the numColors colour classes in order,...
PGSManifoldSweep makePGSManifoldSweep(Kokkos::View< const ManifoldC *, CpMem > manifolds, const VelocitySweepBodies &bodies, float growthRate, float restitutionNormal, float restVelThreshold, Kokkos::View< float, CpMem > maxApproach, Kokkos::View< float, CpMem > maxApproachQS, Kokkos::View< float *, CpMem > lambdaAcc, Kokkos::View< const float *, CpMem > vn0, Kokkos::View< const unsigned char *, CpMem > sideFlag, Kokkos::View< float *[3], CpMem > lambdaT, float frictionDynamic, Kokkos::View< const float *[3], CpMem > vt0, float restitutionTangent, Kokkos::View< const float *, CpMem > posImpulse, const PoissonBankViews &bank)
Build the shared per-manifold sweep functor (the colored launch loop, the fused kernels and the fused...
int colorEdges(const EdgeAccessor &edges, int numEdges, int numVertices, int vertexSpan, Kokkos::View< int *, CpMem > color, const ColorScratch &scratch, int &leftover)
Greedy graph colouring of an edge set: no two edges sharing a colouring vertex get the same colour.
int xPopcount(unsigned long long m)
Rank-level X (docs/contact_solve_framework.md §1.4): the holder of a body whose velocity activity mas...
F3 cross3v(F3 a, F3 b)
Kokkos::View< int *, CpMem > Vi
CpExec::memory_space CpMem
void computeSideFlags(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const int *, CpMem > realIdx, const ShockPropagation &shock, Kokkos::View< const float *[3], CpMem > velPred, float riseThr, Kokkos::View< unsigned char *, CpMem > sideFlag, Kokkos::View< const float *, CpMem > vn0, float approachThr, bool dedupTwins=true)
Decide each persistent contact's treatment ONCE per substep (before any impulse is applied): 0 = symm...
void warmStartApply(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, const BodyState &bodies, const BodyPred &pred, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const float *, CpMem > warmP, Kokkos::View< float *[3], CpMem > warmT, bool dedupTwins=true)
Apply the warm-start impulses up front (order-independent: fixed impulses, atomic adds).
F3 invRotateVector(F4 q, F3 v)
void scatterOrphanBanks(const PairLedger &prev, Kokkos::View< const unsigned char *, CpMem > matched, int prevCount, Kokkos::View< const float *, CpMem > invMass, Kokkos::View< float *, CpMem > orphan, Kokkos::View< float *, CpMem > orphanVPeak, Kokkos::View< const int *, CpMem > gidSorted={}, Kokkos::View< const int *, CpMem > slotSorted={}, int ownedLimit=-1)
Orphan transfer: previous-ledger entries NOT matched by any current manifold (their pair died this su...
F3 ldF3(const V &v, int i)
F3 rotateVector(F4 q, F3 v)
void solveVelocity(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, const BodyState &bodies, const BodyPred &pred, Kokkos::View< const int *, CpMem > realIdx, float growthRate, float restitutionNormal, float restVelThreshold, Kokkos::View< float *[3], CpMem > deltaVel, Kokkos::View< float *[3], CpMem > deltaAngVel, Kokkos::View< int *, CpMem > velCounts, Kokkos::View< const int *, CpMem > onlyColor={}, int colorFilter=0, const ShockPropagation &shock={}, bool massSplit=false, bool dedupTwins=true)
Accumulate normal-restitution velocity deltas for numManifolds manifolds.
std::tuple< double, float, int > restBankStats(Kokkos::View< const float *, CpMem > bank, int n)
Poisson-restitution diagnostics: (sum, max, count>0) over the committed owed-impulse store (namespace...
float dot3(F3 a, F3 b)
F3 sub3(F3 a, F3 b)
Kokkos::DefaultExecutionSpace CpExec
Kokkos::View< float *[3], CpMem > V3
void computeVn0(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, const BodyPred &pred, Kokkos::View< const int *, CpMem > realIdx, float growthRate, Kokkos::View< float *, CpMem > vn0, Kokkos::View< float *[3], CpMem > vt0, bool dedupTwins=true)
-— Warm-started projected Gauss-Seidel (PGS) velocity solve -— Nonsmooth contact dynamics (Moreau-Jea...
void updateRestitutionBank(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, const BodyState &bodies, const BodyPred &pred, Kokkos::View< const int *, CpMem > realIdx, float growthRate, float restitutionNormal, float restVelThreshold, Kokkos::View< const float *, CpMem > vn0, const PairLedger &ledger, Kokkos::View< const float *, CpMem > restRel, bool dedupTwins=true)
Event-level (Poisson) restitution bookkeeping, once per substep AFTER all velocity phases (restitutio...
void applyVelocityDeltasAveraged(int n, V3 velPred, V3 angVelPred, V3 deltaVel, V3 deltaAngVel, Vi velCounts, bool averaged=true)
Apply the accumulated velocity deltas AVERAGED by the per-body manifold count — the velocity- solve t...
void computeXGate(Kokkos::View< const ManifoldC *, CpMem > manifolds, int nm, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const unsigned long long *, CpMem > velMask, Kokkos::View< unsigned char *, CpMem > gate, int color, int numColors, long long t)
The per-manifold fire gate of sync interval t: 1 iff this rank (colour color) holds every endpoint wh...
F3 scale3(F3 a, float s)
F3 angularDelta(F3 jang, F3 invI, F4 q)
World-frame angular velocity change of an angular impulse jang on a body with diagonal local inverse ...
long long colorKey(int idx)
splitmix32 finalizer: a well-mixed pseudo-random priority per edge index.
constexpr int kColorUncolourable
int colorManifoldsIncremental(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const int *, CpMem > realIdx, int numReal, const CarriedColors &carried, Kokkos::View< int *, CpMem > mColor, const ColorScratch &scratch, int &leftover, bool forceFull, Kokkos::View< const unsigned char *, CpMem > sleepMask={}, bool dedupTwins=true)
Incremental (warm-started) manifold colouring for the single-GPU PGS path.
F3 add3(F3 a, F3 b)
long long countUnfired(Kokkos::View< const unsigned char *, CpMem > gate, int nm)
Diagnostics (iterCounters): the number of gated-off manifolds of one sweep.
int colorManifolds(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const int *, CpMem > realIdx, int numReal, Kokkos::View< int *, CpMem > mColor, const ColorScratch &scratch, int &leftover, Kokkos::View< const unsigned char *, CpMem > sleepMask={}, SlotOverride ov={}, bool dedupTwins=true, int vertexSpan=0)
Greedy graph-colour the manifolds: no two manifolds sharing a real body get the same colour (colorEdg...
constexpr int kColorPalette
Colouring palette (docs/contact_solve_framework.md §4.2 item 1): the greedy takes the lowest colour f...
void countVelocityJacobi(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< int *, CpMem > counts, bool dedupTwins=true)
Mass-split Jacobi count pass (docs/contact_solve_framework.md §3.1, D3): per body (REAL index),...
void decayBodyOrphan(Kokkos::View< float *, CpMem > orphan, Kokkos::View< float *, CpMem > orphanVPeak, int numOwned, float restVelThreshold)
Orphan-account aging, once per substep over the OWNED bodies: both the balance and the carried event ...
bool solveVelocityPGS(const PGSManifoldSweep &f, int numManifolds, const ColorSchedule &sched, const FusedLoopSpec *loop=nullptr)
Returns true when the sweep (or, with loop, the whole iteration loop) was submitted; false ONLY in lo...
unsigned long long pairKeyOf(const ManifoldC &m, Kokkos::View< const int *, CpMem > realIdx)
Persistent-contact detection for the gravity-gated restitution rule.
void buildLevelColorBuckets(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const int *, CpMem > mColor, Kokkos::View< const int *, CpMem > heights, Kokkos::View< int *, CpMem > keys, Kokkos::View< int *, CpMem > perm, std::vector< std::pair< int, int > > &buckets)
Bucket the active coloured manifolds by (support level, colour) for the level-ordered ("multilevel") ...
dem — fused colour sweeps: one persistent kernel per sweep instead of one kernel launch per colour.
The substep's predicted body state (Particles::bodyPred()).
Kokkos::View< float *[3], CpMem > velPred
Kokkos::View< float *[3], CpMem > angVelPred
A body's state, one row per particle slot (Particles::bodyState()).
Kokkos::View< float *[3], CpMem > invInertia
Kokkos::View< float *, CpMem > invMass
Kokkos::View< float *[4], CpMem > quat
The previous substep's colour ledger for an incremental colouring: the key-sorted pair keys,...
Kokkos::View< const unsigned long long *, CpMem > keys
Kokkos::View< const int *, CpMem > color
One colouring edge as the arbitration sees it: the colouring vertices of its A / B ends (b = -1 for a...
Kernel labels of one colorEdges instantiation (each caller keeps its own profiling names).
The colour schedule of one coloured Gauss–Seidel sweep: each item's colour and the colour count,...
Kokkos::View< const int *, CpMem > perm
const FusedSweepCtx * fused
const std::vector< int > * offs
Kokkos::View< const int *, CpMem > color
Per-vertex scratch of the Jones-Plassmann colourings: the round's winning edge key and the committed-...
Kokkos::View< long long *, CpMem > bodyWinner
Kokkos::View< std::uint64_t *, CpMem > bodyColorMask
The colour classes one coloured sweep visits: manifolds [0, numManifolds), labelled by mColor in [0,...
Kokkos::View< const ManifoldC *, CpMem > manifolds
Kokkos::View< const int *, CpMem > mColor
Device-side iteration loop: run up to maxIters sweeps of the colour classes inside ONE kernel,...
Device-side context for a fused colour sweep: the colour offsets (numColors+1, uploaded from buildCol...
Portable mirror of ManifoldConstraint.
The manifold edge source of colorEdges: vertex realIdx(body) or its hub copy slot through ov,...
int initialColor(int idx) const
Kokkos::View< const unsigned char *, CpMem > sleepMask
ColorEdge edge(int idx) const
static constexpr ColorLabels labels()
Kokkos::View< const ManifoldC *, CpMem > manifolds
Kokkos::View< const int *, CpMem > realIdx
The endpoints' velocities (B on a wall: the wall's average velocity, zero spin).
The Poisson release's budget: the pair's owed impulse, the release speed scale and the endpoints' orp...
One manifold's constraint row as the three impulse channels share it: the manifold,...
One full colored PGS sweep.
Kokkos::View< float, CpMem > maxApproach
Kokkos::View< float, CpMem > maxApproachQS
Kokkos::View< float *[3], CpMem > lambdaT
Kokkos::View< const float *, CpMem > restOrphanVPeak
void applyLinear(int real, F3 dLin, float invMass) const
Linear velocity update of body slot real by the world-frame impulse dLin.
Kokkos::View< const float *, CpMem > invMass
Kokkos::View< const float *[4], CpMem > quat
Kokkos::View< const int *, CpMem > realIdx
Kokkos::View< const float *[3], CpMem > vt0
static float normalVelocity(const PairVelocity &v, F3 Nsum, F3 TauA, F3 TauB, F3 vGrowth)
The pair's normal approach velocity along Nsum (arm sums TauA/TauB), growth included.
Kokkos::View< const float *[3], CpMem > invInertia
Kokkos::View< const unsigned char *, CpMem > sideFlag
void gatherRow(int idx, Row &r) const
Row, part 1: the manifold, its endpoints' slots, mass data and velocities, the averaged normal and ar...
Kokkos::View< float *, CpMem > lambdaAcc
void recordCorrection(int idx, float lenN, float corr) const
Residual record of one applied correction: the adaptive stop's maxApproach and, on quasi-static conta...
Kokkos::View< float *[3], CpMem > velPred
Kokkos::View< const float *, CpMem > restVPeak
Kokkos::View< const float *, CpMem > vn0
Kokkos::View< float *, CpMem > restOrphan
Kokkos::View< const float *, CpMem > posImpulse
Kokkos::View< const ManifoldC *, CpMem > manifolds
void weighRow(int idx, Row &r) const
Row, part 2: the approach velocity, the sign, the side gates and the effective mass.
void releaseIncrement(int idx, const Row &r, const ReleaseBudget &b, float vtil3) const
One release increment: the budget-capped push toward the event's separation-velocity target,...
Kokkos::View< float *[3], CpMem > angVelPred
Kokkos::View< float *, CpMem > restRel
float drawOrphans(int realA, int realB, float need, float orphA, float orphB) const
Draw up to need from the endpoints' orphan balances (A first, then B); returns the amount drawn.
void applyAngular(int real, F3 dAngWorld, F3 invI, F4 q) const
Angular velocity update of body slot real by the world-frame angular impulse dAngWorld (rotated into ...
Kokkos::View< float *, CpMem > restBank
The pair-keyed warm-start ledger: pair key, converged normal and tangential impulses,...
Kokkos::View< float *, CpMem > restVPeak
Kokkos::View< float *, CpMem > restBank
Kokkos::View< unsigned long long *, CpMem > keys
Kokkos::View< float *, CpMem > lambda
Event-level (Poisson) restitution views, all empty when the model is off.
Kokkos::View< float *, CpMem > orphan
Kokkos::View< float *, CpMem > rel
Kokkos::View< const float *, CpMem > vPeak
Kokkos::View< float *, CpMem > bank
Kokkos::View< float *, CpMem > orphanPeak
The geometric and rise gate of shock propagation (see solveVelocity) for one persistent body-body pai...
bool lowerB(F3 vB, F3 gHat) const
B is the lower, non-rising body (velocity vB).
ShockGate(F3 dx, F3 gHat, float restVelThreshold)
bool lowerA(F3 vA, F3 gHat) const
A is the lower, non-rising body (velocity vA).
Shock propagation for persistent loaded contacts (see solveVelocity): the persistence flags,...
Kokkos::View< const float *[3], CpMem > posPred
Kokkos::View< const unsigned char *, CpMem > grounded
Kokkos::View< const unsigned char *, CpMem > persistent
Per-edge slot overrides of a phase's hub copies (docs/contact_solve_framework.md §4....
The bodies a velocity sweep reads and updates in place: mass data and orientation,...
Kokkos::View< float *[3], CpMem > velPred
Kokkos::View< float *[3], CpMem > angVelPred
Kokkos::View< const int *, CpMem > realIdx
Kokkos::View< const float *[4], CpMem > quat
Kokkos::View< const float *[3], CpMem > invInertia
Kokkos::View< const float *, CpMem > invMass
Rank-level X evaluated inline in the one-shot sweep (only for the manifolds of the colour being swept...
Kokkos::View< const unsigned long long *, CpMem > mask
bool fires(int slotA, int slotB) const