peclet-dem 1.1.0
Performance-portable XPBD Discrete Element Method (Kokkos + ArborX)
Loading...
Searching...
No Matches
solve_driver.hpp
Go to the documentation of this file.
1
31#ifndef DEM_SOLVE_DRIVER_HPP
32#define DEM_SOLVE_DRIVER_HPP
33
34#include <algorithm>
35#include <cstdlib>
36#include <Kokkos_Core.hpp>
37#include <stdexcept>
38#include <string>
39#include <utility>
40#include <vector>
41
42#include "broadphase_arborx.hpp"
44#include "particles.hpp"
45#include "solve_copies.hpp"
46#include "solver_friction.hpp"
47#include "solver_multilevel.hpp"
48#include "solver_position.hpp"
49#include "solver_velocity.hpp"
50
51namespace peclet::dem {
52
53inline int readInt(Kokkos::View<int, CpMem> v) {
54 int h;
55 Kokkos::deep_copy(h, v);
56 return h;
57}
58inline float readFloat(Kokkos::View<float, CpMem> v) {
59 float h;
60 Kokkos::deep_copy(h, v);
61 return h;
62}
63
66inline void fillGidBase(Vi gid, int n, int base) {
67 Kokkos::parallel_for(
68 "peclet::dem::gid_base", Kokkos::RangePolicy<CpExec>(0, n),
69 KOKKOS_LAMBDA(int i) { gid(i) = base + i; });
70 Kokkos::fence();
71}
72
78inline float maxOwnedRadius(const Particles& P) {
79 if (P.numReal <= 0)
80 return P.globalScale * P.baseRadius;
81 float mx = 0.0f;
82 auto sc = P.scale;
83 Kokkos::parallel_reduce(
84 "peclet::dem::max_scale", Kokkos::RangePolicy<CpExec>(0, P.numReal),
85 KOKKOS_LAMBDA(int i, float& m) { m = sc(i) > m ? sc(i) : m; }, Kokkos::Max<float>(mx));
86 return mx * P.globalScale * P.baseRadius;
87}
88
94inline void fillWorldRadii(Vf scale, Vf rad, float gs, float bR, int n) {
95 CpExec space;
96 Kokkos::parallel_for(
97 "peclet::dem::world_radii", Kokkos::RangePolicy<CpExec>(space, 0, n),
98 KOKKOS_LAMBDA(int i) { rad(i) = scale(i) * gs * bR; });
99 space.fence();
100}
101
112inline int findCollisionsGrow(Particles& P, float margin) {
113 const float boxCap = std::max(std::max(P.domain.size.x, P.domain.size.y), P.domain.size.z);
114 int np = findCollisionsArborX(P.posPred, P.crad(), P.numParticles, P.numReal, margin, P.pairs,
115 P.pairCount, boxCap);
116 if (np > static_cast<int>(P.pairs.extent(0))) {
117 const int grown = np + np / 2 + 64; // 1.5× + slack
118 Kokkos::realloc(Kokkos::WithoutInitializing, P.pairs, grown);
119 P.maxPairs = grown;
120 np = findCollisionsArborX(P.posPred, P.crad(), P.numParticles, P.numReal, margin, P.pairs,
121 P.pairCount, boxCap);
122 }
123 return std::min(np, static_cast<int>(P.pairs.extent(0)));
124}
125
134inline int findCollisionsVerlet(Particles& P, float margin, float maxRad) {
135 const float skin = P.verletSkinFrac * maxRad;
136 bool rebuild = (P.impNumPairs < 0);
137 if (!rebuild) {
138 float md2 = 0.0f;
139 auto pp = P.posPred;
140 auto rp = P.impRefPos;
141 Kokkos::parallel_reduce(
142 "peclet::dem::verlet_disp", Kokkos::RangePolicy<CpExec>(0, P.numReal),
143 KOKKOS_LAMBDA(int i, float& acc) {
144 const float dx = pp(i, 0) - rp(i, 0), dy = pp(i, 1) - rp(i, 1), dz = pp(i, 2) - rp(i, 2);
145 const float d = dx * dx + dy * dy + dz * dz;
146 if (d > acc)
147 acc = d;
148 },
149 Kokkos::Max<float>(md2));
150 Kokkos::fence();
151 // Growth grows radii between rebuilds; a pair can close by ~2x the radius growth with no CoM
152 // motion, so fold it into the displacement budget.
153 const float grow = std::max(0.0f, maxRad - P.impRefMaxRad);
154 if (std::sqrt(md2) + 2.0f * grow > 0.5f * skin)
155 rebuild = true;
156 }
157 if (rebuild) {
158 const int np = findCollisionsGrow(P, margin + skin); // candidate list at margin + skin
159 const auto rng = Kokkos::pair<int, int>(0, P.numReal);
160 Kokkos::deep_copy(Kokkos::subview(P.impRefPos, rng, Kokkos::ALL),
161 Kokkos::subview(P.posPred, rng, Kokkos::ALL));
162 P.impNumPairs = np;
163 P.impRefMaxRad = maxRad;
164 return np;
165 }
166 return P.impNumPairs; // reuse the cached candidate list (P.pairs is unchanged)
167}
168
169#ifdef KOKKOS_ENABLE_CUDA
177struct CudaIterGraph {
178 cudaGraphExec_t exec = nullptr;
179 template <class F>
180 bool capture(CpExec& space, F&& emit, void*& cacheSlot) {
181 cudaStream_t str = space.cuda_stream();
182 if (cudaStreamBeginCapture(str, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
183 (void)cudaGetLastError();
184 return false;
185 }
186 emit();
187 cudaGraph_t g = nullptr;
188 if (cudaStreamEndCapture(str, &g) != cudaSuccess || g == nullptr) {
189 (void)cudaGetLastError();
190 return false;
191 }
192 // Instantiation dominates the per-step graph cost (~10 us/node); the topology is stable
193 // step-to-step, so refresh last step's executable in place and only re-instantiate when the
194 // structure genuinely changed (bucket emptiness pattern / colour count shifts).
195 if (cacheSlot != nullptr) {
196 exec = static_cast<cudaGraphExec_t>(cacheSlot);
197 cudaGraphExecUpdateResultInfo ri;
198 if (cudaGraphExecUpdate(exec, g, &ri) != cudaSuccess) {
199 (void)cudaGetLastError();
200 cudaGraphExecDestroy(exec);
201 exec = nullptr;
202 cacheSlot = nullptr;
203 }
204 }
205 if (exec == nullptr) {
206 if (cudaGraphInstantiate(&exec, g, nullptr, nullptr, 0) != cudaSuccess) {
207 (void)cudaGetLastError();
208 exec = nullptr;
209 }
210 cacheSlot = exec;
211 }
212 cudaGraphDestroy(g);
213 return exec != nullptr;
214 }
215 void launch(CpExec& space) { cudaGraphLaunch(exec, space.cuda_stream()); }
216 // the executable is owned by the cross-step cache slot, not this per-step handle
217};
220#define PECLET_DEM_GRAPH_LOOP(useVar, graphVar, emitVar, slotVar) \
221 if constexpr (!Hooks::distributed) { \
222 if (P.cudaGraphs) \
223 useVar = graphVar.capture(space, emitVar, slotVar); \
224 }
225#else
227 template <class F>
228 bool capture(CpExec&, F&&, void*&) {
229 return false;
230 }
231 void launch(CpExec&) {}
232};
233#define PECLET_DEM_GRAPH_LOOP(useVar, graphVar, emitVar, slotVar) (void)graphVar;
234#endif
235
241struct RankK {
242 bool exchanges = false;
243 // Rank-level X (§1.4, WO-6): this rank's colour col(r), the number of colours C of the rank
244 // graph, and the sync interval (solver iterations per sync) that the holder cycle steps with.
245 int color = 0;
246 int numColors = 1;
248};
249
252 static constexpr bool distributed = false;
253 float allMax(float v) const { return v; }
254 float allMaxAny(float v, bool&) const { return v; }
255 bool syncPoint(int) const { return false; }
256 int visibleManifolds(int nm) const { return nm; }
257 void beginSolve(Particles&) const {}
258 void syncVelocities(Particles&) const {}
260 void syncPositions(Particles&) const {}
263 // Rank-level M (docs/contact_solve_framework.md §13.3): a single rank has no remote copies, so
264 // the opening is "step 0" only -- k = max(1, a(own)) = WO-4's groupK, which the driver uses
265 // directly -- and there is no rank-level k to expose.
266 RankK rankK() const { return {}; }
267 void openVelocityPhase(Particles&, bool) const {}
268 void openPositionCounts(Particles&, bool) const {}
270};
271
274inline int* demIterCountSlot(Particles& P, int slot) {
275 if (P.iterCountDev.extent(0) < 2)
276 P.iterCountDev = Kokkos::View<int*, CpMem>("peclet::dem::iter_count", 2);
277 return P.iterCountDev.data() + slot;
278}
279
281inline int demReadIterCount(const Particles& P, int slot) {
282 if (!P.iterCounters || P.iterCountDev.extent(0) < 2)
283 return -1;
284 int v = -1;
285 Kokkos::deep_copy(v, Kokkos::subview(P.iterCountDev, slot));
286 return v;
287}
288
293 Kokkos::View<int*, CpMem> edgeA, edgeB; // a failed phase's colouring edges (scratch)
294 std::string msg;
295 bool pending = false;
296
297 void note(const char* phase, Kokkos::View<const int*, CpMem> color, int n,
298 Kokkos::View<const int*, CpMem> vertexDegree) {
299 // Name the first uncolourable edge's vertices and their degrees (host readback, error path).
300 auto hc = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), color);
301 auto ha = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), edgeA);
302 auto hb = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), edgeB);
303 auto hd = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), vertexDegree);
304 int bad = 0, first = -1;
305 for (int e = 0; e < n; ++e)
306 if (hc(e) == -1 || hc(e) == kColorUncolourable) {
307 ++bad;
308 if (first < 0)
309 first = e;
310 }
311 std::string m = std::string("colouring invariant violated: ") + std::to_string(bad) + " " +
312 phase + " uncolourable edges after hub splitting";
313 if (first >= 0) {
314 m += " (first: vertex " + std::to_string(ha(first)) + ", degree " +
315 std::to_string(ha(first) >= 0 ? hd(ha(first)) : 0);
316 if (hb(first) >= 0)
317 m += "; vertex " + std::to_string(hb(first)) + ", degree " + std::to_string(hd(hb(first)));
318 m += ")";
319 }
320 msg += (msg.empty() ? "" : "; ") + m;
321 }
322
323 // The colouring invariant (§4.2 item 4, §12 S3): a single rank throws now; the distributed step
324 // votes the flag in its first stop Allreduce and every rank throws there (a rank-local throw
325 // would leave the others waiting in a collective).
326 template <class Hooks>
327 void seal() {
328 pending = !msg.empty();
329 if constexpr (!Hooks::distributed) {
330 if (pending)
331 throw std::runtime_error(msg);
332 }
333 }
334
335 template <class Hooks>
336 float vote(const Hooks& hooks, float res) {
337 bool bad = pending;
338 pending = false;
339 const float r = hooks.allMaxAny(res, bad);
340 if (bad)
341 throw std::runtime_error(
342 msg.empty() ? std::string("colouring invariant violated on another rank") : msg);
343 return r;
344 }
345};
346
348inline void growCopySlots(Particles& P, int slotBase, int nCopies) {
349 if (slotBase + nCopies > P.capacity)
350 P.ensureCapacity(slotBase + nCopies + 64);
351}
352
357template <class Hooks>
358inline int colorVelocityPhase(Particles& P, int nm, int nBodies, bool usePersistPre,
359 bool incrColorOff,
360 const Kokkos::View<const unsigned char*, CpMem> mSleep,
361 PhaseCopies& vcs, int slotBase, ColoringInvariant& inv) {
362 Kokkos::View<int*, CpMem>& edgeA = inv.edgeA;
363 Kokkos::View<int*, CpMem>& edgeB = inv.edgeB;
364 int velLeftover = 0;
365 int numColors = 0;
366 // Incremental colouring (single-GPU PGS path only): carry surviving pairs' colours across
367 // substeps, re-arbitrating only the new manifolds. Bit-identical colouring FORM to the full
368 // recolour; forced full on the fresh substep and when the colour count creeps > 1.3x the last
369 // full recolour (compaction keeps the serialized-phase count bounded). Under MPI or g == 0 the
370 // full recolour stays (a carried colour can cross a rank boundary it never arbitrated against).
371 const bool incrColor = usePersistPre && P.velocityUseGS && !Hooks::distributed && !incrColorOff;
372 if (incrColor) {
373 // A substep coloured through hub copies carried per-COPY colours: recolour in full.
374 bool didFull = (P.prevPairCount <= 0) || P.velCopiesLastSubstep;
375 numColors = colorManifoldsIncremental(P.manifolds, nm, P.realIndices, nBodies,
377 velLeftover, /*forceFull*/ didFull, mSleep);
378 if (!didFull && P.velLastFullColors > 0 && numColors > (P.velLastFullColors * 13) / 10) {
379 numColors = colorManifoldsIncremental(
380 P.manifolds, nm, P.realIndices, nBodies, P.prevManifoldColors(), P.manifoldColor,
381 P.colorScratch(), velLeftover, /*forceFull*/ true, mSleep);
382 didFull = true;
383 }
384 if (didFull)
385 P.velLastFullColors = numColors;
386 } else {
387 numColors = colorManifolds(P.manifolds, nm, P.realIndices, nBodies, P.manifoldColor,
388 P.colorScratch(), velLeftover, mSleep, {},
389 /*dedupTwins*/ !Hooks::distributed);
390 }
391 if (velLeftover > 0 && nm > 0) {
392 // Attempt failed: hub copies over the vertices realIdx(body) (§4.4), full recolour.
393 edgeA = Kokkos::View<int*, CpMem>("peclet::dem::copies_eA", nm);
394 edgeB = Kokkos::View<int*, CpMem>("peclet::dem::copies_eB", nm);
396 Kokkos::View<const int*, CpMem>(P.manifoldColor), edgeA, edgeB);
397 growCopyView(P.vertexDegree, static_cast<std::size_t>(nBodies), "peclet::dem::vertexDegree");
398 vertexDegree(edgeA, edgeB, nm, nBodies, P.vertexDegree);
399 buildHubCopies(edgeA, edgeB, nm, nBodies, slotBase, P.vertexDegree, vcs);
400 growCopySlots(P, slotBase, vcs.nCopies);
401 const SlotOverride ovColor{vcs.slotA, vcs.slotB, {}, 1.0f};
402 numColors = colorManifolds(P.manifolds, nm, P.realIndices, nBodies, P.manifoldColor,
403 P.colorScratch(), velLeftover, mSleep, ovColor,
404 /*dedupTwins*/ !Hooks::distributed, slotBase + vcs.nCopies);
405 if (incrColor)
406 P.velLastFullColors = numColors;
407 buildCopyGroups(P.realIndices, nBodies, P.numReal, P.vertexDegree, {}, vcs,
408 /*identityBodies*/ true);
409 P.splitStats.lightHubs = countLightHubs(vcs, edgeA, edgeB, nm, nBodies,
410 Kokkos::View<const float*, CpMem>(P.invMass));
411 if (velLeftover > 0)
412 inv.note("velocity", Kokkos::View<const int*, CpMem>(P.manifoldColor), nm, P.vertexDegree);
413 }
414 P.velCopiesLastSubstep = vcs.nCopies > 0;
415 return numColors;
416}
417
423template <class Hooks>
424inline int colorPositionPhase(Particles& P, int nc, int nm, bool usePersistPre, bool incrColorOff,
425 const Kokkos::View<const unsigned char*, CpMem> cSleep,
426 PhaseCopies& pcs, int slotBase, ColoringInvariant& inv,
427 int& numPosUnits, PosUnits& posUnits) {
428 Kokkos::View<int*, CpMem>& edgeA = inv.edgeA;
429 Kokkos::View<int*, CpMem>& edgeB = inv.edgeB;
430 int posLeftover = 0;
431 int numPosColors = 0;
432 // Incremental position colouring, same single-GPU PGS gate + creep policy as the velocity path.
433 const bool incrPosColor =
434 usePersistPre && P.velocityUseGS && !Hooks::distributed && !incrColorOff;
435 bool posDidFull = false;
436 numPosUnits = buildPositionUnits(P.contacts, nc, P.unitStart, P.unitContacts, nm);
437 P.numPosUnits = numPosUnits;
438 // All singletons (spheres): the unit map is the identity -- the empty PosUnits, so the
439 // sweeps and passes index contacts directly (no two-level indirection per contact).
440 if (numPosUnits != nc)
441 posUnits = PosUnits{Kokkos::subview(Kokkos::View<const int*, CpMem>(P.unitStart),
442 Kokkos::pair<int, int>(0, numPosUnits + 1)),
443 Kokkos::subview(Kokkos::View<const int*, CpMem>(P.unitContacts),
444 Kokkos::pair<int, int>(0, nc))};
445 if (incrPosColor) {
446 posDidFull = (P.posPrevContactCount <= 0);
447 numPosColors = colorContactsIncremental(
448 P.contacts, numPosUnits, P.numParticles, P.prevContactColors(), P.unitColor, P.contactKeys,
449 P.colorScratch(), posLeftover, /*forceFull*/ posDidFull, cSleep, posUnits);
450 if (!posDidFull && P.posLastFullColors > 0 && numPosColors > (P.posLastFullColors * 13) / 10) {
451 numPosColors = colorContactsIncremental(
452 P.contacts, numPosUnits, P.numParticles, P.prevContactColors(), P.unitColor,
453 P.contactKeys, P.colorScratch(), posLeftover, /*forceFull*/ true, cSleep, posUnits);
454 posDidFull = true;
455 }
456 if (posDidFull)
457 P.posLastFullColors = numPosColors;
458 } else {
459 numPosColors = colorContacts(P.contacts, numPosUnits, P.numParticles, P.unitColor,
460 P.colorScratch(), posLeftover, cSleep, posUnits);
461 }
462 // Position vertices are raw slots. demStep's periodic images are local copies of their body
463 // (§WO-4 item 2): they join its fold group, which needs the per-slot degree even without hubs.
464 const bool images = !Hooks::distributed && P.numParticles > P.numReal;
465 if ((posLeftover > 0 || images) && numPosUnits > 0) {
466 edgeA = Kokkos::View<int*, CpMem>("peclet::dem::copies_eA", numPosUnits);
467 edgeB = Kokkos::View<int*, CpMem>("peclet::dem::copies_eB", numPosUnits);
468 positionEdgeEnds(P.contacts, posUnits, numPosUnits,
469 Kokkos::View<const int*, CpMem>(P.unitColor), edgeA, edgeB);
470 growCopyView(P.vertexDegree, static_cast<std::size_t>(P.numParticles),
471 "peclet::dem::vertexDegree");
472 vertexDegree(edgeA, edgeB, numPosUnits, P.numParticles, P.vertexDegree);
473 if (posLeftover > 0) {
474 // Attempt failed: hub copies over the raw slots (§4.4), full recolour (the incremental
475 // path falls back to this full path with copies).
476 buildHubCopies(edgeA, edgeB, numPosUnits, P.numParticles, slotBase, P.vertexDegree, pcs);
477 growCopySlots(P, slotBase, pcs.nCopies);
478 const SlotOverride ovColor{pcs.slotA, pcs.slotB, {}, 1.0f};
479 numPosColors =
480 colorContacts(P.contacts, numPosUnits, P.numParticles, P.unitColor, P.colorScratch(),
481 posLeftover, cSleep, posUnits, ovColor, slotBase + pcs.nCopies);
482 if (incrPosColor) {
483 posDidFull = true;
484 P.posLastFullColors = numPosColors;
485 }
486 if (posLeftover > 0)
487 inv.note("position", Kokkos::View<const int*, CpMem>(P.unitColor), numPosUnits,
488 P.vertexDegree);
489 }
491 images ? Kokkos::View<const float* [3], CpMem>(P.imageShift)
492 : Kokkos::View<const float* [3], CpMem>(),
493 pcs, /*identityBodies*/ Hooks::distributed);
494 }
495 // Every contact carries its unit's colour: the per-contact ledger commit below and the
496 // diagnostics read it.
497 expandUnitColors(posUnits, numPosUnits, Kokkos::View<const int*, CpMem>(P.unitColor),
498 P.contactColor);
499 if (incrPosColor) {
500 // Commit this substep's (contact key, colour) for next substep's warm gather.
501 commitContactColor(Kokkos::View<const unsigned long long*, CpMem>(P.contactKeys),
502 Kokkos::View<const int*, CpMem>(P.contactColor), P.prevContactKeys,
504 P.posPrevContactCount = nc;
505 }
506 return numPosColors;
507}
508
511inline float withConsensus(Particles& P, float res, bool cons) {
512 if (!cons)
513 return res;
514 const float c = readFloat(P.maxConsensus);
515 Kokkos::deep_copy(P.maxConsensus, 0.0f);
516 return std::max(res, c);
517}
518
525 int numPosUnits = 0;
527 float posTol = 0.0f;
528 float fusedOff = -1.0f;
529 bool stopsOn = true;
530 bool posCopiesOn = false;
531 bool posCons = false;
532};
533
537template <class Hooks, class EmitPosIter, class SyncPos>
538inline void runOverlapProjection(Particles& P, int nc, const Hooks& hooks, CpExec& space,
539 const PositionSolveContext& ctx, EmitPosIter&& emitPosIter,
540 SyncPos&& syncPos, ColoringInvariant& inv) {
541 const auto& posUnits = ctx.posUnits;
542 const auto& numPosUnits = ctx.numPosUnits;
543 const auto& posSched = ctx.posSched;
544 const auto& posTol = ctx.posTol;
545 const auto& fusedOff = ctx.fusedOff;
546 const auto& stopsOn = ctx.stopsOn;
547 const auto& posCopiesOn = ctx.posCopiesOn;
548 const auto& posCons = ctx.posCons;
549 // Device-side position loop (CUDA, single-rank): all overlap-projection iterations + the
550 // adaptive stop in ONE kernel. Disabled while the phase has copies (the fold runs between
551 // iterations on the host-driven path).
552 bool posLoopDone = false;
553 if constexpr (!Hooks::distributed) {
554 if (P.velocityUseGS && !posCopiesOn && posSched.fused) {
555 FusedLoopSpec spec{P.positionIterations, stopsOn ? posTol : fusedOff, true};
556 if (P.iterCounters) // diagnostics (§12 S12)
557 spec.iters = demIterCountSlot(P, 1);
558 Kokkos::deep_copy(space, P.maxOverlap, 0.0f); // the largest violation over the device loop
559 posLoopDone =
560 solvePositionColoredGS(P.contacts, posUnits, numPosUnits, posSched, P.invMass, P.posPred,
562 &spec, {}, P.posResidual, P.positionOmega);
563 }
564 }
565 bool graphPos = false;
566 CudaIterGraph gPos;
567 if (!posLoopDone && P.velocityUseGS) {
568 PECLET_DEM_GRAPH_LOOP(graphPos, gPos, emitPosIter, P.graphCache[3])
569 }
570 P.splitStats.posItersUsed = posLoopDone ? demReadIterCount(P, 1) : 0;
571 if (posCons)
572 Kokkos::deep_copy(P.maxConsensus, 0.0f);
573 for (int it = 0; !posLoopDone && it < P.positionIterations; ++it) {
575 if (P.velocityUseGS) {
576 if (graphPos)
577 gPos.launch(space);
578 else
579 emitPosIter();
580 // Every active unit is coloured (§4.2): the count-averaged fallback is gone; the stop's
581 // Allreduce carries the colouring-invariant vote if the velocity loop did not.
582 const float posRes = inv.vote(hooks, withConsensus(P, readFloat(P.posResidual), posCons));
583 // Adaptive stop (WO-12): end once no contact's projection moves it by more than posTol
584 // (|d| w, retractions included). Fixed positionIterations is the cap. Distributed:
585 // Allreduce-MAXed so all ranks break together.
586 if (stopsOn && posRes < posTol)
587 break;
588 } else {
589 // Mass-split Jacobi (see the velocity branch): count, global counts, solve, add.
591 hooks.syncContactCounts(P);
592 solvePosition(P.contacts, nc, P.bodyState(), P.bodyPred(), P.bodyDelta(), P.maxOverlap, {}, 0,
593 /*massSplit=*/true);
594 applyUpdates(P.numParticles, P.bodyPred(), P.bodyDelta(), /*averaged=*/false);
595 }
596 if constexpr (Hooks::distributed) {
597 if (hooks.syncPoint(it))
598 syncPos();
599 }
600 }
601 if constexpr (Hooks::distributed)
602 syncPos(); // final owner->ghost refresh of the position phase
603}
604
608template <class Hooks>
609inline void solvePositionPhase(Particles& P, int nc, int nm, const Hooks& hooks, CpExec& space,
610 PhaseCopies& pcs, int slotBase, bool rankM, bool usePGS,
611 const PosUnits posUnits, int numPosUnits,
612 const ColorSchedule& posSched, bool stopsOn, float fusedOff,
613 ColoringInvariant& inv) {
614 // Position-phase copies (§4.4, §4.5; demStep's periodic images, §WO-4 item 2): seeded after the
615 // predict (and, under MPI, the publish). An image is re-seeded to its body's predicted position
616 // plus its generation shift, so its increments are relative to the body.
617 const bool posCopiesOn = pcs.nGroups > 0;
618 Kokkos::View<const float*, CpMem> invMassPos = P.invMass;
619 Kokkos::View<const float* [3], CpMem> invInertiaPos = P.invInertia;
620 SlotOverride posOv{};
621 // Rank-level M in the position phase (§13.3 step 9): an exchanging rank on the GS paths (both
622 // openings made k_pos). The solve views carry each raw slot's global k_pos (a hub copy its
623 // base's); the local fold still divides by the local count a; the syncs are M in the halo.
624 const bool posM = rankM && P.velocityUseGS;
625 if (posM) {
626 buildSolveViewsRankK(P, pcs, slotBase + (posCopiesOn ? pcs.nCopies : 0), P.invMass,
627 P.invInertia, Kokkos::View<const int*, CpMem>(P.kPos));
628 invMassPos = P.invMassSolve;
629 invInertiaPos = P.invInertiaSolve;
630 if (posCopiesOn) {
631 seedCopySlotState(P, pcs);
632 markCopySeeds(pcs, P.posPred, {}, {}, {});
633 if (pcs.nHubs > 0)
634 posOv = SlotOverride{pcs.slotA, pcs.slotB, {}, 1.0f};
635#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 7
636 posOv = SlotOverride{pcs.slotA, pcs.slotB, P.splitSlot, 1.5f}; // G13 mutant 7
637#endif
638 }
639 } else if (posCopiesOn) {
640 buildSolveViews(P, pcs, slotBase + pcs.nCopies, P.invMass, P.invInertia);
641 seedCopySlotState(P, pcs);
642 markCopySeeds(pcs, P.posPred, {}, {}, {});
643 invMassPos = P.invMassSolve;
644 invInertiaPos = P.invInertiaSolve;
645 // The slot overrides only: the overlap projection is never relaxed (§13.1).
646 if (pcs.nHubs > 0)
647 posOv = SlotOverride{pcs.slotA, pcs.slotB, {}, 1.0f};
648#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 7
649 posOv = SlotOverride{pcs.slotA, pcs.slotB, P.splitSlot, 1.5f}; // G13 mutant 7
650#endif
651 }
652 Kokkos::Profiling::popRegion();
653 Kokkos::Profiling::pushRegion("dem::solve::pos");
654 auto syncPos = [&] {
655 if constexpr (Hooks::distributed) {
656 hooks.syncPositions(P);
657 if (posCopiesOn)
658 markCopySeeds(pcs, P.posPred, {}, {}, {});
659 }
660 };
661
662 // Overlap resolved once the deepest penetration falls below ~0.01% of a particle radius.
663 const float posTol = 1e-4f * P.baseRadius * P.globalScale;
664 {
665 auto pc = Kokkos::subview(P.posLambdaContact, Kokkos::pair<int, int>(0, nc));
666 Kokkos::deep_copy(pc, 0.0f);
667 }
668
669 // One position iteration (async residual zero + colored overlap sweep), graph-captured on
670 // the single-GPU path like the velocity loops.
671 // WO-12: the accumulated, retractable projection (§13.5) at omega = P.positionOmega; the stop
672 // reads the position change (posResidual), maxOverlap the largest violation seen.
673 auto emitPosIter = [&] {
674 Kokkos::deep_copy(space, P.maxOverlap, 0.0f);
675 Kokkos::deep_copy(space, P.posResidual, 0.0f);
676 solvePositionColoredGS(P.contacts, posUnits, numPosUnits, posSched, invMassPos, P.posPred,
677 P.quatPred, P.quat, invInertiaPos, P.maxOverlap, P.posLambdaContact,
678 nullptr, posOv, P.posResidual, P.positionOmega);
679 if (posCopiesOn)
680 foldCopies(space, pcs, P.posPred, {}, {}, {}, P.maxConsensus);
681 };
682 // §12 S14: the position phase folds its consensus corrections (|dx| of a local fold or an M
683 // sync, absolute like maxOverlap) into its stop vote, exactly as the velocity phase does.
684 const bool posCons = posCopiesOn || posM;
685 const PositionSolveContext posCtx{.posUnits = posUnits,
686 .numPosUnits = numPosUnits,
687 .posSched = posSched,
688 .posTol = posTol,
689 .fusedOff = fusedOff,
690 .stopsOn = stopsOn,
691 .posCopiesOn = posCopiesOn,
692 .posCons = posCons};
693 runOverlapProjection(P, nc, hooks, space, posCtx, emitPosIter, syncPos, inv);
694 // Position-channel Coulomb-bound carry (PGS path): next substep's friction cone sees
695 // mu * (velocity-impulse channel + this position-channel load). Without it a jostled bed's
696 // bound under-counts the true normal force and stick leaks (measured: 99% sliding wall
697 // contacts in the benchmark drum while the Hertz reference sticks).
698 if (usePGS && nm > 0)
701 Kokkos::Profiling::popRegion();
702}
703
707 Kokkos::View<const float*, CpMem> invMass,
708 Kokkos::View<const float* [3], CpMem> invInertia,
709 SlotOverride ov = {}) {
710 return VelocitySweepBodies{.invMass = invMass,
711 .invInertia = invInertia,
712 .quat = P.quat,
713 .velPred = P.velPred,
714 .angVelPred = P.angVelPred,
715 .realIdx = P.realIndices,
716 .ov = ov};
717}
718
721 return PoissonBankViews{.bank = on ? P.restBank : Kokkos::View<float*, CpMem>(),
722 .rel = on ? P.restRel : Kokkos::View<float*, CpMem>(),
723 .vPeak = on ? Kokkos::View<const float*, CpMem>(P.restVPeak)
724 : Kokkos::View<const float*, CpMem>(),
725 .orphan = on ? P.bodyOrphan : Kokkos::View<float*, CpMem>(),
726 .orphanPeak = on ? P.bodyOrphanVPeak : Kokkos::View<float*, CpMem>()};
727}
728
737 int numColors = 0;
738 Kokkos::View<const int*, CpMem> velPermC;
739 const FusedSweepCtx* velFusedP = nullptr;
740 Kokkos::View<const float*, CpMem> invMassVel;
741 Kokkos::View<const float* [3], CpMem> invInertiaVel;
743 // Event-level (Poisson) restitution views (empty when off).
746 F3 gHat{0, 0, 0};
747 float gMagP = 0.0f;
748 int nmVisible = 0;
749 bool usePGS = false;
750 bool poisson = false;
751 bool legacyFriction = false;
752 bool sleepOn = false;
753 bool wantFused = false;
754 bool xOn = false;
755 bool velCopiesOn = false;
756 bool velM = false;
757 bool velCons = false;
758 bool stopsOn = true;
759 float fusedOff = -1.0f;
760};
761
763inline void foldVelocityCopies(CpExec& space, Particles& P, const VelocitySolveContext& ctx) {
764 if (ctx.velCopiesOn)
767}
768
773template <class Hooks>
774inline void syncVelocityPhase(Particles& P, const Hooks& hooks, const VelocitySolveContext& ctx) {
775 if constexpr (Hooks::distributed) {
776 if (ctx.velM) {
777 hooks.syncVelocities(P);
778 if (ctx.velCopiesOn)
780 ctx.poissonViews.orphanPeak, /*shareFromBase*/ true);
781 return;
782 }
783 if (ctx.velCopiesOn)
785 hooks.syncVelocities(P);
786 if (ctx.velCopiesOn)
789 }
790}
791
795template <class Hooks>
796inline bool launchFusedVelocityLoop(Particles& P, int nm, float vRest,
797 const VelocitySolveContext& ctx) {
798 const auto& velSched = ctx.velSched;
799 const auto& velFusedP = ctx.velFusedP;
800 const auto& usePGS = ctx.usePGS;
801 const auto& velCopiesOn = ctx.velCopiesOn;
802 const auto& stopsOn = ctx.stopsOn;
803 const auto& fusedOff = ctx.fusedOff;
804 bool velLoopDone = false;
805 if constexpr (!Hooks::distributed) {
806 if (usePGS && P.velocityUseGS && !velCopiesOn && velFusedP) {
807 FusedLoopSpec spec{P.velocityIterations, stopsOn ? 0.02f * vRest : fusedOff, false};
808 if (P.iterCounters) // diagnostics (§12 S12): the loop writes its count on the device
809 spec.iters = demIterCountSlot(P, 0);
810 velLoopDone = solveVelocityPGS(
812 P.growthRate, P.restitutionNormal, vRest, P.maxApproach, {},
813 P.lambdaAcc, P.vn0,
814 Kokkos::View<const unsigned char*, CpMem>(P.sideFlags), P.lambdaT,
816 Kokkos::View<const float*, CpMem>(P.posImpulse), ctx.poissonViews),
817 nm, velSched, &spec);
818 }
819 }
820 return velLoopDone;
821}
822
825inline void oneShotVelocityIteration(Particles& P, int nm, int it, float vRest, CpExec& space,
826 const VelocitySolveContext& ctx) {
827 const auto& numColors = ctx.numColors;
828 const auto& invMassVel = ctx.invMassVel;
829 const auto& invInertiaVel = ctx.invInertiaVel;
830 const auto& velOv = ctx.velOv;
831 const auto& rk = ctx.rk;
832 const auto& xOn = ctx.xOn;
833 Kokkos::deep_copy(space, P.maxApproach, 0.0f);
834 // Rank-level X (§1.4, WO-6): in sync interval t a contact fires only if this rank holds
835 // every rank-split endpoint; a non-firing contact still records its approach for the stop.
836 XGateSpec xGate; // evaluated inline in the sweep (no separate pass)
837 if (xOn) {
838 const long long t = P.solveEpoch + it / rk.syncInterval;
839 xGate = XGateSpec{Kokkos::View<const unsigned long long*, CpMem>(P.velMask), rk.color,
840 rk.numColors, t};
841 if (P.iterCounters) { // diagnostics only: the explicit gate pass, to count the unfired
843 Kokkos::View<const unsigned long long*, CpMem>(P.velMask), P.xGate, rk.color,
844 rk.numColors, t);
846 }
847 }
849 .numManifolds = nm,
850 .mColor = P.manifoldColor,
851 .numColors = numColors},
852 VelocitySweepBodies{.invMass = invMassVel,
853 .invInertia = invInertiaVel,
854 .quat = P.quat,
855 .velPred = P.velPred,
856 .angVelPred = P.angVelPred,
857 .realIdx = P.realIndices,
858 .ov = velOv},
859 P.growthRate, P.restitutionNormal, vRest, P.maxApproach, xGate);
860 foldVelocityCopies(space, P, ctx);
861}
862
867template <class Hooks>
868inline void massSplitVelocityIteration(Particles& P, int nm, const Hooks& hooks, float vRest) {
870 /*dedupTwins*/ !Hooks::distributed);
871 hooks.syncContactCounts(P);
874 {}, /*massSplit=*/true,
875 /*dedupTwins*/ !Hooks::distributed);
877 P.constraintCounts, /*averaged=*/false);
878}
879
885template <class Hooks>
886inline void solveVelocityPhase(Particles& P, int nc, int nm, const Hooks& hooks, CpExec& space,
887 const VelocitySolveContext& ctx, ColoringInvariant& inv) {
888 const auto& velSched = ctx.velSched;
889 const auto& invMassVel = ctx.invMassVel;
890 const auto& invInertiaVel = ctx.invInertiaVel;
891 const auto& velOv = ctx.velOv;
892 const auto& gMagP = ctx.gMagP;
893 const auto& usePGS = ctx.usePGS;
894 const auto& legacyFriction = ctx.legacyFriction;
895 const auto& velCons = ctx.velCons;
896 const auto& stopsOn = ctx.stopsOn;
897 // Restitution threshold ~ the speed one substep of free fall gains: below it a contact is
898 // RESTING and bounces with e=0 (see solveVelocity — dense-pile energy-bomb guard).
899 const float vRest = 2.0f * P.dt * gMagP;
900 // One PGS velocity iteration (async residual zero + full colour sweep). Captured as a CUDA
901 // graph and replayed per iteration on the single-GPU path: the step is host-submission-bound
902 // (measured 3,300 launches / ~11 ms per step at 25k), and replay collapses each iteration's
903 // launch storm into one. The residual readback between replays is unchanged, so the adaptive
904 // stop — and the physics — are bit-identical to the submission path.
905 auto emitVelIter = [&] {
906 Kokkos::deep_copy(space, P.maxApproach, 0.0f);
908 P.manifolds, velocitySweepBodies(P, invMassVel, invInertiaVel, velOv),
910 P.vn0, Kokkos::View<const unsigned char*, CpMem>(P.sideFlags), P.lambdaT,
912 Kokkos::View<const float*, CpMem>(P.posImpulse), ctx.poissonViews),
913 nm, velSched);
914 foldVelocityCopies(space, P, ctx);
915 };
916 // Device-side iteration loop (CUDA, single-rank): the whole adaptive velocity loop as ONE
917 // kernel — same sweeps, same residual, same stop; the per-iteration readback and the graph
918 // capture disappear. The final residual stays in P.maxApproach for the stabilization trigger.
919 const bool velLoopDone = launchFusedVelocityLoop<Hooks>(P, nm, vRest, ctx);
920 bool graphVel = false;
921 CudaIterGraph gVel;
922 if (!velLoopDone && usePGS && P.velocityUseGS) {
923 PECLET_DEM_GRAPH_LOOP(graphVel, gVel, emitVelIter, P.graphCache[0])
924 }
925 P.splitStats.velItersUsed = velLoopDone ? demReadIterCount(P, 0) : 0;
926 if (velCons)
927 Kokkos::deep_copy(P.maxConsensus, 0.0f);
928 Kokkos::Profiling::popRegion();
929 Kokkos::Profiling::pushRegion("dem::solve::vel");
930 for (int it = 0; !velLoopDone && it < P.velocityIterations; ++it) {
932 if (legacyFriction)
934 P.growthRate,
935 /*dedupTwins*/ !Hooks::distributed);
936 if (P.velocityUseGS) {
937 if (usePGS) {
938 if (graphVel)
939 gVel.launch(space);
940 else
941 emitVelIter();
942 } else {
943 oneShotVelocityIteration(P, nm, it, vRest, space, ctx);
944 }
945 // Every active manifold is coloured (§4.2): the count-averaged fallback is gone. The stop's
946 // Allreduce carries the colouring-invariant vote (inv.vote; no extra message).
947 const float velRes = inv.vote(hooks, withConsensus(P, readFloat(P.maxApproach), velCons));
948 // Adaptive stop. One-shot GS: end once no pair approaches above the resting threshold. PGS:
949 // maxApproach records the largest APPLIED correction, and meaningful increments are ~g dt
950 // (they propagate a chain one link per sweep), so the tolerance must sit well below vRest or
951 // the stop starves deep-chain convergence permanently (measured: a 113-layer pile plateaued
952 // at vz ~ -5 with the vRest stop). Once the warm-started network is converged the first
953 // sweep's correction is ~0 and the loop still exits immediately. Distributed: the residual
954 // is Allreduce-MAXed so every rank takes the same break (collective-refresh consistency).
955 if (stopsOn && velRes <= (usePGS ? 0.02f * vRest : vRest))
956 break;
957 } else {
958 // Mass-split Jacobi (velocityUseGS off, a global setting; §3.1).
959 massSplitVelocityIteration(P, nm, hooks, vRest);
960 }
961 if constexpr (Hooks::distributed) {
962 if (hooks.syncPoint(it))
963 syncVelocityPhase(P, hooks, ctx);
964 }
965 }
966 if constexpr (Hooks::distributed)
967 syncVelocityPhase(P, hooks, ctx); // final owner->ghost refresh of the main velocity phase
968}
969
972template <class Hooks>
973inline void stabilizeOneSided(Particles& P, int nm, const Hooks& hooks, CpExec& space,
974 const VelocitySolveContext& ctx, const float vRestS) {
975 const auto& velSched = ctx.velSched;
976 const auto& velFusedP = ctx.velFusedP;
977 const auto& invMassVel = ctx.invMassVel;
978 const auto& invInertiaVel = ctx.invInertiaVel;
979 const auto& velOv = ctx.velOv;
980 const auto& gHat = ctx.gHat;
981 const auto& gMagP = ctx.gMagP;
982 const auto& velCopiesOn = ctx.velCopiesOn;
983 const auto& velCons = ctx.velCons;
984 const auto& stopsOn = ctx.stopsOn;
985 const auto& fusedOff = ctx.fusedOff;
987 ShockPropagation{.persistent = P.manifoldPersistent,
988 .posPred = P.posPred,
989 .gHat = gHat,
990 .grounded = P.groundedLevel},
991 P.velPred, 8.0f * P.dt * gMagP, P.sideFlags, P.vn0, 8.0f * P.dt * gMagP,
992 /*dedupTwins*/ !Hooks::distributed);
993 // Arrest budget: 2x the main budget -- the pass must out-pace a violent collapse, and it
994 // only ever runs when the residual says one is happening (adaptive stop ends it early).
995 auto emitOsIter = [&] {
996 Kokkos::deep_copy(space, P.maxApproach, 0.0f);
998 P.manifolds, velocitySweepBodies(P, invMassVel, invInertiaVel, velOv),
999 P.growthRate, P.restitutionNormal, vRestS, P.maxApproach, {}, P.lambdaAcc,
1000 P.vn0, Kokkos::View<const unsigned char*, CpMem>(P.sideFlags), P.lambdaT,
1002 Kokkos::View<const float*, CpMem>(P.posImpulse), ctx.poissonViews),
1003 nm, velSched);
1004 foldVelocityCopies(space, P, ctx);
1005 };
1006 bool osLoopDone = false;
1007 if constexpr (!Hooks::distributed) {
1008 if (!velCopiesOn && velFusedP) {
1009 const FusedLoopSpec spec{2 * P.velocityIterations, stopsOn ? vRestS : fusedOff, false};
1010 osLoopDone = solveVelocityPGS(
1012 P.growthRate, P.restitutionNormal, vRestS, P.maxApproach, {},
1013 P.lambdaAcc, P.vn0,
1014 Kokkos::View<const unsigned char*, CpMem>(P.sideFlags), P.lambdaT,
1016 Kokkos::View<const float*, CpMem>(P.posImpulse), ctx.poissonViews),
1017 nm, velSched, &spec);
1018 }
1019 }
1020 bool graphOs = false;
1021 CudaIterGraph gOs;
1022 if (!osLoopDone) {
1023 PECLET_DEM_GRAPH_LOOP(graphOs, gOs, emitOsIter, P.graphCache[1])
1024 }
1025 if (velCons)
1026 Kokkos::deep_copy(P.maxConsensus, 0.0f);
1027 for (int it = 0; !osLoopDone && it < 2 * P.velocityIterations; ++it) {
1028 if (graphOs)
1029 gOs.launch(space);
1030 else
1031 emitOsIter();
1032 const float osRes = hooks.allMax(withConsensus(P, readFloat(P.maxApproach), velCons));
1033 if (stopsOn && osRes <= vRestS)
1034 break;
1035 if constexpr (Hooks::distributed) {
1036 if (hooks.syncPoint(it))
1037 syncVelocityPhase(P, hooks, ctx);
1038 }
1039 }
1040}
1041
1046inline Kokkos::View<const float*, CpMem> coarseVertexInvMass(Particles& P, int nBodies, bool velM) {
1047 // Coarse vertex masses (docs/contact_solve_framework.md §13.2): after the fold the a(q)
1048 // active local copies of vertex q move together, so the coarse problem sees ONE vertex of
1049 // mass a m / k -- invMassCoarse = invMass k / a. On a single rank (and for WO-4's interim
1050 // rank-local hubs) a = k at every vertex, so invMassCoarse is P.invMass itself: the true
1051 // mass at a folded hub, not the solve view's m / k (which gained (1 - 1/s) m dV per
1052 // coarse cycle at a hub that aggregates).
1053 // Under rank-level M a rank-split vertex has a < k: invMassCoarse = invMass k / max(1, a).
1054#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 6
1055 Kokkos::View<const float*, CpMem> invMassCoarse = P.invMassSolve; // G13 mutant 6
1056#else
1057 Kokkos::View<const float*, CpMem> invMassCoarse = P.invMass;
1058#endif
1059 if (velM) {
1060 growCopyView(P.invMassCoarse, static_cast<std::size_t>(nBodies), "peclet::dem::invMassCoarse");
1061 buildInvMassCoarse(P.invMass, Kokkos::View<const int*, CpMem>(P.kVel),
1062 Kokkos::View<const int*, CpMem>(P.aVel), nBodies, P.invMassCoarse);
1063 invMassCoarse = P.invMassCoarse;
1064 }
1065 return invMassCoarse;
1066}
1067
1069inline Kokkos::View<const float* [3], CpMem> coarseVertexInvInertia(Particles& P, int nBodies,
1070 bool velM) {
1071 // The coarse vertex's inverse inertia is the same fraction
1072 // (docs/contact_physics_followups.md §2.5): P.invInertia itself wherever invMassCoarse is
1073 // P.invMass.
1074 Kokkos::View<const float* [3], CpMem> invInertiaCoarse = P.invInertia;
1075 if (velM) {
1076 growCopyView(P.invInertiaCoarse, static_cast<std::size_t>(nBodies),
1077 "peclet::dem::invInertiaCoarse");
1078 buildInvInertiaCoarse(P.invInertia, Kokkos::View<const int*, CpMem>(P.kVel),
1079 Kokkos::View<const int*, CpMem>(P.aVel), nBodies, P.invInertiaCoarse);
1080 invInertiaCoarse = P.invInertiaCoarse;
1081 }
1082 return invInertiaCoarse;
1083}
1084
1086inline void allocateMultilevelPools(Particles& P, int nBodies) {
1087 // Rigid-aggregate pools (§2.3), allocated on the first multilevel pass only.
1088 if (P.mlInvIG.extent(0) != P.mlInvMassG.extent(0)) {
1089 const std::size_t ng = P.mlInvMassG.extent(0);
1090 const auto wi = Kokkos::WithoutInitializing;
1091 P.mlOriginG = Kokkos::View<float* [3], CpMem>(Kokkos::view_alloc(wi, "mlOriginG"), ng);
1092 P.mlComOffG = Kokkos::View<float* [3], CpMem>(Kokkos::view_alloc(wi, "mlComOffG"), ng);
1093 P.mlAngG = Kokkos::View<float* [3], CpMem>(Kokkos::view_alloc(wi, "mlAngG"), ng);
1094 P.mlAngG0 = Kokkos::View<float* [3], CpMem>(Kokkos::view_alloc(wi, "mlAngG0"), ng);
1095 P.mlInvIG = Kokkos::View<float* [6], CpMem>(Kokkos::view_alloc(wi, "mlInvIG"), ng);
1096 }
1097 growCopyView(P.mlAccD, static_cast<std::size_t>(nBodies), "peclet::dem::mlAccD");
1098}
1099
1102inline void recordMultilevelHierarchy(Particles& P, int nm, int nBodies, const ContactHierarchy& H,
1103 const MlScratch& S, bool velM, bool velCopiesOn) {
1105#ifndef NDEBUG
1106 // Debug build (§13.5 WO-5 item 4): no multi-member coarse group holds an inactive vertex.
1107 if (velM && H.numLevels > 0 &&
1108 countInactiveAggregated(Kokkos::View<const int*, CpMem>(S.parent), H.parentOff[0], nBodies,
1109 H.numGroups[0], Kokkos::View<const int*, CpMem>(P.aVel)) > 0)
1110 throw std::logic_error("rank-level M: a coarse group holds a vertex with a = 0");
1111#endif
1112 if (H.numLevels > 0 && (velCopiesOn || velM)) // §13.2's positive control (diagnostic)
1114 std::max(P.splitStats.mlHubAggregated,
1115 countSplitAggregated(Kokkos::View<const int*, CpMem>(S.parent), H.parentOff[0],
1116 nBodies, H.numGroups[0],
1117 Kokkos::View<const unsigned char*, CpMem>(P.splitSlot)));
1118 P.mlLast.numManifolds = nm;
1119 P.mlLast.numBodies = nBodies;
1122}
1123
1124#ifdef KOKKOS_ENABLE_CUDA
1127template <class Hooks>
1128inline bool launchFusedMultilevelLoop(Particles& P, int nm, CpExec& space,
1129 const VelocitySolveContext& ctx, const float vRestS,
1130 const ContactHierarchy& H, MlScratch& S,
1131 const MlBodyViews& mlBody, const MlFusedCtx* mlFusedP) {
1132 const auto& velSched = ctx.velSched;
1133 const auto& numColors = ctx.numColors;
1134 const auto& velPermC = ctx.velPermC;
1135 const auto& velFusedP = ctx.velFusedP;
1136 const auto& relV = ctx.poissonViews.rel;
1137 const auto& velCopiesOn = ctx.velCopiesOn;
1138 const auto& stopsOn = ctx.stopsOn;
1139 const auto& fusedOff = ctx.fusedOff;
1140 bool mlLoopDone = false;
1141 if constexpr (!Hooks::distributed) {
1142 if (!velCopiesOn && velFusedP) {
1143 if (H.numLevels > 0 && mlFusedP) {
1144 const PGSManifoldSweep fStab = makePGSManifoldSweep(
1145 P.manifolds, velocitySweepBodies(P, P.invMass, P.invInertia), P.growthRate,
1146 P.restitutionNormal, vRestS, P.maxApproach, P.maxApproachQS, P.lambdaAcc, P.vn0,
1147 Kokkos::View<const unsigned char*, CpMem>(P.sideFlags), P.lambdaT, P.frictionDynamic,
1148 P.vt0, P.restitutionTangent, Kokkos::View<const float*, CpMem>(P.posImpulse),
1149 ctx.poissonViews);
1150 mlLoopDone = demLaunchFusedMlLoop(
1151 space, fStab, velPermC, *velFusedP, numColors,
1152 MlManifoldViews{P.manifolds, P.realIndices, P.lambdaAcc, P.maxApproachQS,
1153 Kokkos::View<const float*, CpMem>(relV)},
1154 Kokkos::View<const float*, CpMem>(P.invMass), P.velPred, S,
1155 Kokkos::View<const int*, CpMem>(P.mlBucketPerm), *mlFusedP, 2 * P.velocityIterations,
1156 stopsOn ? vRestS : fusedOff, mlBody);
1157 } else if (H.numLevels == 0) {
1158 // aggregation found nothing: the loop is plain fine sweeps on the QS residual
1159 const FusedLoopSpec spec{2 * P.velocityIterations, stopsOn ? vRestS : fusedOff, false};
1160 mlLoopDone = solveVelocityPGS(
1161 makePGSManifoldSweep(P.manifolds, velocitySweepBodies(P, P.invMass, P.invInertia),
1162 P.growthRate, P.restitutionNormal, vRestS, P.maxApproach,
1163 P.maxApproachQS, P.lambdaAcc, P.vn0,
1164 Kokkos::View<const unsigned char*, CpMem>(P.sideFlags), P.lambdaT,
1165 P.frictionDynamic, P.vt0, P.restitutionTangent,
1166 Kokkos::View<const float*, CpMem>(P.posImpulse), ctx.poissonViews),
1167 nm, velSched, &spec);
1168 }
1169 }
1170 }
1171 return mlLoopDone;
1172}
1173#endif
1174
1175template <class Hooks>
1176inline void stabilizeMultilevel(Particles& P, int nm, int nBodies, const Hooks& hooks,
1177 CpExec& space, const VelocitySolveContext& ctx,
1178 const float vRestS) {
1179 PhaseCopies& vcs = P.velCopies;
1180 const auto& velSched = ctx.velSched;
1181 const auto& invMassVel = ctx.invMassVel;
1182 const auto& invInertiaVel = ctx.invInertiaVel;
1183 const auto& velOv = ctx.velOv;
1184 const auto& relV = ctx.poissonViews.rel;
1185 const auto& gHat = ctx.gHat;
1186 const auto& gMagP = ctx.gMagP;
1187 const auto& sleepOn = ctx.sleepOn;
1188 const auto& wantFused = ctx.wantFused;
1189 const auto& velCopiesOn = ctx.velCopiesOn;
1190 const auto& velM = ctx.velM;
1191 const auto& velCons = ctx.velCons;
1192 const auto& stopsOn = ctx.stopsOn;
1193 // MULTILEVEL (GraphMG) pass: never deletes momentum, only accelerates its transport.
1194 // Greedy pairwise aggregation over the quasi-static contact graph builds super-bodies
1195 // (summed mass, momentum-weighted velocity); the fine manifolds crossing aggregate
1196 // boundaries are re-solved with the AGGREGATE masses -- the supported chain's genuinely
1197 // huge inertia plays the role the held lower side faked, so a wall contact drains a
1198 // whole column's momentum in one coarse impulse while every impulse stays symmetric.
1199 // Ballistic pairs (|vn0| > qsThr) never aggregate: an impactor keeps its fine-level,
1200 // momentum-conserving physics and its rebound. Coarse lambda shares the fine
1201 // accumulator, so the force-network ledger stays consistent for next substep's warm
1202 // start and the friction cone's Coulomb bound. See solver_multilevel.hpp. Distributed:
1203 // the hierarchy is built rank-locally over owned + ghost bodies (aggregates never cross
1204 // a rank boundary beyond the ghost band; the syncEvery refresh reconciles).
1205 const float qsThr = 8.0f * P.dt * gMagP;
1206 // Eligibility gates (mldetail::kGate*): slip keeps the pass off sustained shear (silo
1207 // bulk) without starving a crushing bed's aggregation. (The env A/B over the mask was
1208 // retired in 1.0.0; the measured-best mask is the only one that ships.)
1209 constexpr int mlGates = mldetail::kGateSlip;
1210 Kokkos::View<const float*, CpMem> invMassCoarse = coarseVertexInvMass(P, nBodies, velM);
1211 Kokkos::View<const float* [3], CpMem> invInertiaCoarse = coarseVertexInvInertia(P, nBodies, velM);
1212 allocateMultilevelPools(P, nBodies);
1214 P.mlMate, P.mlOriginG, P.mlComOffG, P.mlAngG, P.mlAngG0, P.mlInvIG, P.mlAccD};
1215 const MlBodyViews mlBody{Kokkos::View<const float* [3], CpMem>(P.posPred), P.angVelPred,
1216 Kokkos::View<const float* [4], CpMem>(P.quat), invInertiaCoarse};
1217 const MlEligibility mlElig{P.manifolds,
1218 nm,
1219 Kokkos::View<const int*, CpMem>(P.manifoldColor),
1220 Kokkos::View<const float*, CpMem>(P.vn0),
1221 Kokkos::View<const float* [3], CpMem>(P.vt0),
1222 Kokkos::View<const unsigned char*, CpMem>(P.manifoldPersistent),
1223 P.posPred,
1224 gHat,
1225 qsThr,
1226 mlGates};
1227 const ContactHierarchy H =
1228 buildContactHierarchy(mlElig, P.realIndices, invMassCoarse, nBodies, S, P.colorScratch(),
1229 /*excludeImmovable*/ sleepOn,
1230 sleepOn ? Kokkos::View<const unsigned char*, CpMem>(P.asleep)
1231 : Kokkos::View<const unsigned char*, CpMem>(),
1232 mlBody);
1233 recordMultilevelHierarchy(P, nm, nBodies, H, S, velM, velCopiesOn);
1234 // Dense per-(level, colour) buckets, built once per hierarchy (see solver_multilevel.hpp).
1235 std::vector<std::vector<int>> mlOffs;
1236 if (H.numLevels > 0) {
1237 if (static_cast<int>(P.mlBucketPerm.extent(0)) < H.numLevels * nm)
1238 Kokkos::realloc(Kokkos::WithoutInitializing, P.mlBucketPerm, H.numLevels * nm);
1239 buildCoarseBuckets(H, S, nm, P.levelKey, P.mlBucketPerm, P.bucketCursor, mlOffs);
1240 }
1241 // Fused coarse cycle (CUDA): the whole per-iteration coarse leg as ONE kernel.
1242 const MlFusedCtx mlFused = (H.numLevels > 0 && wantFused)
1243 ? demMakeMlFusedCtx(space, H, mlOffs, nm, nBodies,
1244 /*coarseSweeps*/ 2, P.mlOffsDev, P.fusedBar)
1245 : MlFusedCtx{};
1246 const MlFusedCtx* mlFusedP = mlFused.maxWork > 0 ? &mlFused : nullptr;
1247 // The loop's stop criterion is the QUASI-STATIC residual (fine corrections on contacts
1248 // with |vn0| <= 4 vRest, plus every coarse correction): the fine sweep's full residual
1249 // is dominated by ballistic contacts in flowing scenes (a discharging silo never gets
1250 // below vRest there), and gating on it burns the full budget of extra fine sweeps every
1251 // substep -- an over-convergence brake on discharge (the escalate effect, measured -7%).
1252 // The pass exists to converge the quasi-static network; once that is done, it is done.
1253 // One stabilization iteration (async QS-residual zero + fine sweep + coarse cycle),
1254 // graph-captured on the single-GPU path — this loop is THE launch storm (up to 16
1255 // iterations x [colour sweeps + per-(level, colour) coarse kernels] per substep).
1256 // With hub copies (§4.4): fold between the fine sweep and the coarse cycle (the coarse
1257 // leg reads the bases, [0, nBodies)), and re-seed the copies from the bases after it.
1258 auto emitMlIter = [&] {
1259 Kokkos::deep_copy(space, P.maxApproachQS, 0.0f);
1261 P.manifolds, velocitySweepBodies(P, invMassVel, invInertiaVel, velOv),
1263 P.lambdaAcc, P.vn0, Kokkos::View<const unsigned char*, CpMem>(P.sideFlags),
1265 Kokkos::View<const float*, CpMem>(P.posImpulse), ctx.poissonViews),
1266 nm, velSched);
1267 foldVelocityCopies(space, P, ctx);
1268 if (H.numLevels > 0) {
1271 Kokkos::View<const float*, CpMem>(relV)},
1272 nm, invMassCoarse, P.velPred, nBodies, H, S,
1273 /*coarseSweeps*/ 2, mlBody, &mlOffs, Kokkos::View<const int*, CpMem>(P.mlBucketPerm),
1274 mlFusedP);
1275 if (velCopiesOn)
1276 reseedCopies(space, vcs, P.velPred, P.angVelPred);
1277 }
1278 };
1279 // Device-side stabilization loop (CUDA, single-rank): fine sweep + coarse cycle +
1280 // adaptive stop, all iterations in ONE kernel (see demFusedMlLoopK).
1281 bool mlLoopDone = false;
1282#ifdef KOKKOS_ENABLE_CUDA
1283 mlLoopDone = launchFusedMultilevelLoop<Hooks>(P, nm, space, ctx, vRestS, H, S, mlBody, mlFusedP);
1284#endif
1285 bool graphMl = false;
1286 CudaIterGraph gMl;
1287 if (!mlLoopDone) {
1288 PECLET_DEM_GRAPH_LOOP(graphMl, gMl, emitMlIter, P.graphCache[2])
1289 }
1290 if (velCons)
1291 Kokkos::deep_copy(P.maxConsensus, 0.0f);
1292 for (int it = 0; !mlLoopDone && it < 2 * P.velocityIterations; ++it) {
1293 if (graphMl)
1294 gMl.launch(space);
1295 else
1296 emitMlIter();
1297 const float mlRes = hooks.allMax(withConsensus(P, readFloat(P.maxApproachQS), velCons));
1298 if (stopsOn && mlRes <= vRestS)
1299 break;
1300 if constexpr (Hooks::distributed) {
1301 if (hooks.syncPoint(it))
1302 syncVelocityPhase(P, hooks, ctx);
1303 }
1304 }
1305}
1306
1309template <class Hooks>
1310inline void stabilizeOrdered(Particles& P, int nm, int nBodies, const Hooks& hooks, CpExec& space,
1311 const VelocitySolveContext& ctx, const float vRestS) {
1312 const auto& invMassVel = ctx.invMassVel;
1313 const auto& invInertiaVel = ctx.invInertiaVel;
1314 const auto& velOv = ctx.velOv;
1315 const auto& bankV = ctx.poissonViews.bank;
1316 const auto& relV = ctx.poissonViews.rel;
1317 const auto& vpkC = ctx.poissonViews.vPeak;
1318 const auto& orphV = ctx.poissonViews.orphan;
1319 const Kokkos::View<const float*, CpMem> orphPk = ctx.poissonViews.orphanPeak;
1320 const auto& gHat = ctx.gHat;
1321 const auto& nmVisible = ctx.nmVisible;
1322 const auto& velCons = ctx.velCons;
1323 const auto& stopsOn = ctx.stopsOn;
1324 // ORDERED (level-ordered symmetric sweeps; measurement mode): fresh height-from-floor
1325 // BFS levels order the manifolds bottom-up + top-down. Fully symmetric, but a pairwise
1326 // inelastic impulse only EQUALIZES velocities, so a deep column still cools one halving
1327 // per cycle -- measured insufficient on the statics battery (kept for A/B comparison
1328 // against the multilevel pass).
1329 computeHeightLevels(P.manifolds, nmVisible, P.realIndices, P.posPred, gHat, P.heightLevel,
1330 nBodies);
1331 std::vector<std::pair<int, int>> buckets;
1333 P.manifolds, nm, P.realIndices, Kokkos::View<const int*, CpMem>(P.manifoldColor),
1334 Kokkos::View<const int*, CpMem>(P.heightLevel), P.levelKey, P.levelPerm, buckets);
1335 const PGSManifoldSweep sweep{P.manifolds,
1336 invMassVel,
1337 invInertiaVel,
1338 P.quat,
1339 P.velPred,
1340 P.angVelPred,
1341 P.realIndices,
1342 P.growthRate,
1344 vRestS,
1345 P.maxApproach,
1346 P.maxApproach,
1347 P.lambdaAcc,
1348 P.vn0,
1349 Kokkos::View<const unsigned char*, CpMem>(P.sideFlags),
1350 P.lambdaT,
1352 P.vt0,
1354 Kokkos::View<const float*, CpMem>(P.posImpulse),
1355 bankV,
1356 relV,
1357 vpkC,
1358 orphV,
1359 orphPk,
1360 velOv};
1361 if (velCons)
1362 Kokkos::deep_copy(P.maxConsensus, 0.0f);
1363 for (int it = 0; it < 2 * P.velocityIterations; ++it) {
1364 Kokkos::deep_copy(P.maxApproach, 0.0f);
1365 solveVelocityPGSBuckets(sweep, Kokkos::View<const int*, CpMem>(P.levelPerm), buckets,
1366 /*topDown*/ false);
1367 solveVelocityPGSBuckets(sweep, Kokkos::View<const int*, CpMem>(P.levelPerm), buckets,
1368 /*topDown*/ true);
1369 foldVelocityCopies(space, P, ctx);
1370 const float orRes = hooks.allMax(withConsensus(P, readFloat(P.maxApproach), velCons));
1371 if (stopsOn && orRes <= vRestS)
1372 break;
1373 if constexpr (Hooks::distributed) {
1374 if (hooks.syncPoint(it))
1375 syncVelocityPhase(P, hooks, ctx);
1376 }
1377 }
1378}
1379
1382template <class Hooks>
1383inline void stabilizeEscalation(Particles& P, int nm, const Hooks& hooks, CpExec& space,
1384 const VelocitySolveContext& ctx, const float vRestS) {
1385 const auto& velSched = ctx.velSched;
1386 const auto& invMassVel = ctx.invMassVel;
1387 const auto& invInertiaVel = ctx.invInertiaVel;
1388 const auto& velOv = ctx.velOv;
1389 const auto& velCons = ctx.velCons;
1390 const auto& stopsOn = ctx.stopsOn;
1391 // ESCALATION (diagnostic/fallback): keep running plain symmetric colored sweeps until
1392 // the residual drains or the 256-sweep cap -- provably correct physics, and the sweep
1393 // count it needs bounds what the ordered pass must deliver.
1394 if (velCons)
1395 Kokkos::deep_copy(P.maxConsensus, 0.0f);
1396 for (int it = 0; it < 256; ++it) {
1397 Kokkos::deep_copy(P.maxApproach, 0.0f);
1399 P.manifolds, velocitySweepBodies(P, invMassVel, invInertiaVel, velOv),
1400 P.growthRate, P.restitutionNormal, vRestS, P.maxApproach, {}, P.lambdaAcc,
1401 P.vn0, Kokkos::View<const unsigned char*, CpMem>(P.sideFlags), P.lambdaT,
1403 Kokkos::View<const float*, CpMem>(P.posImpulse), ctx.poissonViews),
1404 nm, velSched);
1405 foldVelocityCopies(space, P, ctx);
1406 const float esRes = hooks.allMax(withConsensus(P, readFloat(P.maxApproach), velCons));
1407 if (stopsOn && esRes <= vRestS)
1408 break;
1409 if constexpr (Hooks::distributed) {
1410 if (hooks.syncPoint(it))
1411 syncVelocityPhase(P, hooks, ctx);
1412 }
1413 }
1414}
1415
1420template <class Hooks>
1421inline void stabilizeVelocityPhase(Particles& P, int nm, int nBodies, const Hooks& hooks,
1422 CpExec& space, const VelocitySolveContext& ctx) {
1423 const auto& gMagP = ctx.gMagP;
1424 const auto& usePGS = ctx.usePGS;
1425 // STABILIZATION PASS: if the symmetric sweeps could not drain the residual (a collapsing
1426 // column needs ~one sweep per layer to carry its weight to the floor -- unaffordable), arrest
1427 // the remaining quasi-static approach with grounded one-sided sweeps. In dynamic scenes the
1428 // residual is below the threshold and this pass never runs, so impact/discharge/shear keep
1429 // pure momentum-conserving physics. (set_stabilization_mode('off') disables the pass.)
1430 if (usePGS) {
1431 const float vRestS = 2.0f * P.dt * gMagP;
1432 const int smode = P.stabilizationMode;
1433 if (smode != 0 && hooks.allMax(readFloat(P.maxApproach)) > vRestS) {
1434 if (smode == 1) { // ONE-SIDED grounded pass (default): held-lower-side impulses
1435 stabilizeOneSided(P, nm, hooks, space, ctx, vRestS);
1436 } else if (smode == 2) {
1437 stabilizeMultilevel(P, nm, nBodies, hooks, space, ctx, vRestS);
1438 } else if (smode == 4) {
1439 stabilizeOrdered(P, nm, nBodies, hooks, space, ctx, vRestS);
1440 } else if (smode == 3) {
1441 stabilizeEscalation(P, nm, hooks, space, ctx, vRestS);
1442 }
1443 if constexpr (Hooks::distributed)
1444 syncVelocityPhase(P, hooks, ctx); // final refresh of the stabilization phase
1445 }
1446 }
1447}
1448
1452template <class Hooks>
1453inline void closeVelocityPhase(Particles& P, int nm, const Hooks& hooks,
1454 const VelocitySolveContext& ctx) {
1455 PhaseCopies& vcs = P.velCopies;
1456 const auto& orphV = ctx.poissonViews.orphan;
1457 const auto& gMagP = ctx.gMagP;
1458 const auto& usePGS = ctx.usePGS;
1459 const auto& poisson = ctx.poisson;
1460 const auto& velCopiesOn = ctx.velCopiesOn;
1461 const auto& velM = ctx.velM;
1462 // End of the velocity phase: the orphan accounts back to balances (the bookkeeping, the legacy
1463 // friction pass and the next substep read the bases; copy slots are dead from here on).
1464 // Under rank-level M the owner rows of k_vel > 1 bodies get their balance back (§13.3 step 8;
1465 // the copies' shares are dead from here on, the next gather forwards B again).
1466 if (velM) {
1467 if (poisson)
1468 hooks.restoreOrphanBalance(P);
1469 } else if (velCopiesOn) {
1470 unfoldOrphan(vcs, orphV);
1471 }
1472 // Poisson bookkeeping runs once per substep on the FINAL velocity state (after every phase and
1473 // ghost refresh): bank this substep's kinetic compression, deduct what was returned/released.
1474 if (poisson)
1476 P.restitutionNormal, 2.0f * P.dt * gMagP, P.vn0, P.pairLedger(),
1477 Kokkos::View<const float*, CpMem>(P.restRel),
1478 /*dedupTwins*/ !Hooks::distributed);
1479 if (usePGS) { // save the converged force network for next substep's warm start
1481 // Carry the per-manifold colour by pair key (single-GPU incremental
1482 // colouring warm start; empty on the distributed path).
1483 Hooks::distributed ? Kokkos::View<const int*, CpMem>()
1484 : Kokkos::View<const int*, CpMem>(P.manifoldColor),
1485 Hooks::distributed ? Kokkos::View<int*, CpMem>() : P.prevManifoldColor);
1486 P.prevPairCount = nm;
1487 }
1488}
1489
1494 Kokkos::View<const int*, CpMem> keyIdx;
1495 F3 gHat{0, 0, 0};
1496 float gMagP = 0.0f;
1497 int nmVisible = 0;
1498 bool usePGS = false;
1499 bool poisson = false;
1500 bool rankM = false;
1501};
1502
1507template <class Hooks>
1508inline void openVelocityWarmStart(Particles& P, int nm, int nBodies, const Hooks& hooks,
1509 CpExec& space, const WarmStartContext& ws) {
1510 const auto& keyIdx = ws.keyIdx;
1511 const auto& gHat = ws.gHat;
1512 const auto& gMagP = ws.gMagP;
1513 const auto& nmVisible = ws.nmVisible;
1514 const auto& usePGS = ws.usePGS;
1515 const auto& poisson = ws.poisson;
1516 const auto& rankM = ws.rankM;
1517 if (usePGS) {
1518 if (poisson && P.prevPairCount > 0) { // reset the prev-ledger survival flags for the gather
1519 auto mt = Kokkos::subview(P.prevMatched, Kokkos::pair<int, int>(0, P.prevPairCount));
1520 Kokkos::deep_copy(mt, static_cast<unsigned char>(0));
1521 }
1522 gatherWarmLambda(P.manifolds, nmVisible, P.realIndices, keyIdx, P.prevPairLedger(),
1524 poisson ? P.prevMatched : Kokkos::View<unsigned char*, CpMem>(),
1525 /*dedupTwins*/ !Hooks::distributed);
1526 if (poisson) {
1527 { // per-substep release accumulator starts from zero every substep
1528 auto rr = Kokkos::subview(P.restRel, Kokkos::pair<int, int>(0, nm));
1529 Kokkos::deep_copy(rr, 0.0f);
1530 }
1531 // Orphan transfer: age the body accounts (owned range; MPI ghosts are mirrored), then
1532 // settle dead pairs' remaining budgets onto their endpoint bodies. Under MPI the pair-key
1533 // identities are gids, so the scatter resolves them through a sorted gid -> slot map built
1534 // over owned + ghost slots (a ghost-side credit is delivered to the owner by the velocity
1535 // reverse at the next sync; the pair's bank lives only in its owning rank's ledger).
1536 decayBodyOrphan(P.bodyOrphan, P.bodyOrphanVPeak, P.numReal, 2.0f * P.dt * gMagP);
1537 if (P.prevPairCount > 0) {
1538 Kokkos::View<const int*, CpMem> gidSorted, slotSorted;
1539 if constexpr (Hooks::distributed) {
1540 Kokkos::View<int*, CpMem> gs(
1541 Kokkos::view_alloc(space, "peclet::dem::orphan_gids", Kokkos::WithoutInitializing),
1542 nBodies);
1543 Kokkos::View<int*, CpMem> ss(
1544 Kokkos::view_alloc(space, "peclet::dem::orphan_slots", Kokkos::WithoutInitializing),
1545 nBodies);
1546 auto gid = P.gid;
1547 Kokkos::parallel_for(
1548 "peclet::dem::orphan_gid_map", Kokkos::RangePolicy<CpExec>(space, 0, nBodies),
1549 KOKKOS_LAMBDA(int i) {
1550 gs(i) = gid(i);
1551 ss(i) = i;
1552 });
1553 Kokkos::Experimental::sort_by_key(space, gs, ss);
1554 gidSorted = gs;
1555 slotSorted = ss;
1556 }
1558 P.prevPairLedger(), Kokkos::View<const unsigned char*, CpMem>(P.prevMatched),
1559 P.prevPairCount, Kokkos::View<const float*, CpMem>(P.invMass), P.bodyOrphan,
1560 P.bodyOrphanVPeak, gidSorted, slotSorted, Hooks::distributed ? P.numReal : -1);
1561 }
1562 }
1566 nBodies, /*sweeps*/ 8, /*decay*/ 8);
1567 // STAGED SOLVE (Guendelman): the main sweeps are fully momentum-conserving (side flags all
1568 // zero) -- ballistic impact, discharge and shear see correct physics. One-sided grounding is
1569 // reserved for the STABILIZATION pass below, which runs only if the main sweeps leave an
1570 // unconverged residual (a deep column mid-collapse that symmetric GS cannot arrest within the
1571 // iteration budget).
1572 {
1573 auto flags = Kokkos::subview(P.sideFlags, Kokkos::pair<int, int>(0, nm));
1574 Kokkos::deep_copy(flags, static_cast<unsigned char>(0));
1575 }
1576 computeVn0(P.manifolds, nm, P.bodyPred(), P.realIndices, P.growthRate, P.vn0, P.vt0,
1577 /*dedupTwins*/ !Hooks::distributed);
1579 P.lambdaT, /*dedupTwins*/ !Hooks::distributed);
1580 // The warm impulses just moved every owned AND ghost body: the opening (§13.3 step 5)
1581 // reconciles them raw (known impulses), makes the global k_vel / k_pos and forwards the
1582 // owners' state, balance and k, so the first sweep reads a consistent ghost state. (An
1583 // isolated rank: a no-op, as the sync it replaces.)
1584 if constexpr (Hooks::distributed)
1585 hooks.openVelocityPhase(P, poisson);
1586 } else if (P.velocityUseGS) {
1587 // The g = 0 one-shot path: the opening makes the position phase's k_pos (§13.3) and, in the
1588 // same round, the velocity activity masks of rank-level X (§1.4, WO-6). The velocity phase's
1589 // reconciliation stays c771e07's raw reverse + forward: under X at most one copy of a body
1590 // changes per sync interval, so the raw sum is exact.
1591 if constexpr (Hooks::distributed)
1592 hooks.openPositionCounts(P, /*velocityMask=*/rankM);
1593 }
1594}
1595
1599inline void countRankLevelActivity(Particles& P, int nm, bool usePersistPre,
1600 const PosUnits& posUnits, int numPosUnits) {
1601 PhaseCopies& vcs = P.velCopies;
1602 PhaseCopies& pcs = P.posCopies;
1603 const int nAll = P.numParticles + (vcs.nCopies > pcs.nCopies ? vcs.nCopies : pcs.nCopies);
1604 growCopyView(P.aVel, static_cast<std::size_t>(nAll), "peclet::dem::aVel");
1605 growCopyView(P.aPos, static_cast<std::size_t>(nAll), "peclet::dem::aPos");
1606 growCopyView(P.kVel, static_cast<std::size_t>(nAll), "peclet::dem::kVel");
1607 growCopyView(P.kPos, static_cast<std::size_t>(nAll), "peclet::dem::kPos");
1608 growCopyView(P.activityHit, static_cast<std::size_t>(nAll), "peclet::dem::activityHit");
1609 if (!usePersistPre) { // rank-level X (§1.4): the g = 0 one-shot's masks and gates
1610 growCopyView(P.velMask, static_cast<std::size_t>(nAll), "peclet::dem::velMask");
1611 growCopyView(P.xGate, static_cast<std::size_t>(nm > 0 ? nm : 1), "peclet::dem::xGate");
1612 }
1613 const SlotOverride vOv =
1614 vcs.nHubs > 0 ? SlotOverride{vcs.slotA, vcs.slotB, {}, 1.0f} : SlotOverride{};
1616 Kokkos::View<const int*, CpMem>(P.manifoldColor), vOv, P.activityHit,
1617 P.numParticles + vcs.nCopies);
1618 finishActivity(Kokkos::View<const unsigned char*, CpMem>(P.activityHit), P.numParticles, vcs,
1619 P.aVel);
1620 const SlotOverride pOv =
1621 pcs.nHubs > 0 ? SlotOverride{pcs.slotA, pcs.slotB, {}, 1.0f} : SlotOverride{};
1622 activityHitPosition(P.contacts, posUnits, numPosUnits,
1623 Kokkos::View<const int*, CpMem>(P.unitColor), pOv, P.activityHit,
1624 P.numParticles + pcs.nCopies);
1625 finishActivity(Kokkos::View<const unsigned char*, CpMem>(P.activityHit), P.numParticles, pcs,
1626 P.aPos);
1627}
1628
1632 std::vector<int> offs;
1635 SweepPlan() = default;
1636 SweepPlan(const SweepPlan&) = delete;
1637 SweepPlan& operator=(const SweepPlan&) = delete;
1638};
1639
1642inline void planColorSweeps(SweepPlan& plan, CpExec& space, Particles& P,
1643 Kokkos::View<int*, CpMem> color, int n, int numColors,
1644 Kokkos::View<int*, CpMem> perm, Kokkos::View<int*, CpMem> offsDev,
1645 bool wantFused) {
1646 const bool dense = P.velocityUseGS && n > 0 && numColors > 0;
1647 if (dense)
1648 buildColorBuckets(Kokkos::View<const int*, CpMem>(color), n, numColors, perm, P.bucketCursor,
1649 plan.offs);
1650 const Kokkos::View<const int*, CpMem> permC(perm);
1651 plan.fused = (dense && wantFused) ? demMakeFusedCtx(space, plan.offs, offsDev, P.fusedBar)
1652 : FusedSweepCtx{};
1653 plan.sched = ColorSchedule{color, numColors, permC, dense ? &plan.offs : nullptr,
1654 plan.fused.maxBucket > 0 ? &plan.fused : nullptr};
1655}
1656
1660 Kokkos::View<const float*, CpMem> invMass;
1661 Kokkos::View<const float* [3], CpMem> invInertia;
1663};
1664
1665inline VelocitySolveViews openVelocityCopies(Particles& P, int slotBase, bool velM,
1666 bool velCopiesOn, const PoissonBankViews& pv) {
1667 PhaseCopies& vcs = P.velCopies;
1668 Kokkos::View<const float*, CpMem> invMassVel = P.invMass;
1669 Kokkos::View<const float* [3], CpMem> invInertiaVel = P.invInertia;
1670 SlotOverride velOv{};
1671 if (velM) {
1672 buildSolveViewsRankK(P, vcs, slotBase + (velCopiesOn ? vcs.nCopies : 0), P.invMass,
1673 P.invInertia, Kokkos::View<const int*, CpMem>(P.kVel));
1674 invMassVel = P.invMassSolve;
1675 invInertiaVel = P.invInertiaSolve;
1676 velOv = velCopiesOn ? SlotOverride{vcs.slotA, vcs.slotB, P.splitSlot, kSplitOmegaVelocity}
1678 if (velCopiesOn) {
1679 seedCopySlotState(P, vcs);
1680 markCopySeeds(vcs, P.velPred, P.angVelPred, pv.orphan, pv.orphanPeak, /*shareFromBase*/ true);
1681 }
1682 } else if (velCopiesOn) {
1683 buildSolveViews(P, vcs, slotBase + vcs.nCopies, P.invMass, P.invInertia);
1684 seedCopySlotState(P, vcs);
1686 invMassVel = P.invMassSolve;
1687 invInertiaVel = P.invInertiaSolve;
1689 }
1690 return VelocitySolveViews{.invMass = invMassVel, .invInertia = invInertiaVel, .ov = velOv};
1691}
1692
1695inline bool gravityOn(const Particles& P) {
1696 return P.gravity.x != 0.0f || P.gravity.y != 0.0f || P.gravity.z != 0.0f;
1697}
1698
1700template <class Hooks>
1701inline bool islandSleepingOn(const Particles& P, bool gravity) {
1702 return P.sleepingEnabled && !Hooks::distributed && gravity && !P.extForceActive &&
1703 !P.extTorqueActive;
1704}
1705
1707inline bool frictionOn(const Particles& P) {
1708 return P.frictionDynamic > 0.0f || P.wallFrictionMax > 0.0f;
1709}
1710
1714template <class Hooks>
1715inline void demSolveContacts(Particles& P, int nc, int nm, int nBodies,
1716 Kokkos::View<const int*, CpMem> keyIdx, const Hooks& hooks) {
1717 CpExec space;
1718 hooks.beginSolve(P);
1719 // Rank-level X (§1.4): identical on every rank; each substep starts the holder cycle one step
1720 // later, so no rank is systematically first. Incremented on every rank and every call (np 1
1721 // included, where it is read by nothing).
1722 ++P.solveEpoch;
1723 Kokkos::Profiling::pushRegion("dem::solve::prep");
1724 const int nmVisible = hooks.visibleManifolds(nm);
1725
1726 const bool friction = frictionOn(P);
1727 const bool usePersistPre = gravityOn(P);
1728 // Incremental (warm-started) colouring (set_incremental_coloring, default on; single-GPU PGS
1729 // path). Off forces the full per-substep recolour — the pre-incremental behaviour, kept for
1730 // validation. The colouring decides the Gauss-Seidel sweep order, so this DOES change results.
1731 const bool incrColorOff = !P.incrementalColoring;
1732 // Island sleeping (single-GPU statics, gravity on, no external drag): both-asleep manifolds /
1733 // contacts are excluded from the colouring / sweeps / multilevel hierarchy (their masks were
1734 // filled by the caller). Empty views leave every colouring bit-identical to the sleeping-off
1735 // path. The caller has already swapped P.invMass to the effective (sleeper -> 0) inverse mass.
1736 const bool sleepOn = islandSleepingOn<Hooks>(P, usePersistPre);
1737 const Kokkos::View<const unsigned char*, CpMem> mSleep =
1738 sleepOn ? Kokkos::View<const unsigned char*, CpMem>(P.manifoldSleep)
1739 : Kokkos::View<const unsigned char*, CpMem>();
1740 const Kokkos::View<const unsigned char*, CpMem> cSleep =
1741 sleepOn ? Kokkos::View<const unsigned char*, CpMem>(P.contactSleep)
1742 : Kokkos::View<const unsigned char*, CpMem>();
1743 const bool legacyFriction = friction && !(usePersistPre && P.velocityUseGS);
1744 if (legacyFriction)
1746
1747 // Colour the manifold graph ONCE (topology-only; reused across the sweeps), then normal
1748 // restitution as colored Gauss–Seidel: correct multi-contact dissipation with no count-averaging
1749 // (see solver_velocity.hpp). count==1 binary collisions are identical to the old Jacobi path.
1750 int numColors = 0;
1751 // Complete colourings (docs/contact_solve_framework.md §4.2 item 4): colour each phase graph
1752 // once; if an edge found no free colour, split every vertex above kHubEdgeBudget edges into hub
1753 // copies (§4.4) and recolour that phase from scratch on the copy vertices -- guaranteed to
1754 // succeed (§1.6). Anything still uncoloured violates the colouring invariant (§12 S3): a single
1755 // rank throws here, the distributed step votes it in its first stop Allreduce and every rank
1756 // throws. Copy slots are appended at [slotBase, slotBase + nCopies); both phases reuse the range.
1757 PhaseCopies& vcs = P.velCopies;
1758 PhaseCopies& pcs = P.posCopies;
1759 vcs.nHubs = vcs.nCopies = vcs.nGroups = 0;
1760 pcs.nHubs = pcs.nCopies = pcs.nGroups = 0;
1761 const int slotBase = P.numParticles;
1762 vcs.slotBase = pcs.slotBase = slotBase;
1763 { // mlHubAggregated is the max over the step call's substeps (reset by the step entry points)
1764 const int mlAgg = P.splitStats.mlHubAggregated;
1765 const long long drift = P.splitStats.driftMigrations; // cumulative (the drift vote, §5.1)
1766 P.splitStats = SplitStats{};
1767 P.splitStats.mlHubAggregated = mlAgg;
1768 P.splitStats.driftMigrations = drift;
1769 }
1770 P.mlLast.numLevels = 0;
1772 if (P.velocityUseGS)
1773 numColors = colorVelocityPhase<Hooks>(P, nm, nBodies, usePersistPre, incrColorOff, mSleep, vcs,
1774 slotBase, inv);
1775 // Fused colour sweeps (CUDA): the whole PGS sweep — and where eligible the whole adaptive
1776 // iteration loop — as ONE kernel iterating device-side (see solver_fused.hpp); same colour
1777 // ordering, bit-identical. Default policy ("auto"): on exactly where CUDA-graph replay is
1778 // unavailable — the distributed step, or set_cuda_graphs(False); set_fused_sweeps("on"/"off")
1779 // forces either way.
1780 const bool wantFused = demFusedWanted(!Hooks::distributed && P.cudaGraphs, P.fusedSweeps);
1781 // Dense colour buckets + fused sweep for the velocity sweeps.
1782 SweepPlan velPlan;
1783 planColorSweeps(velPlan, space, P, P.manifoldColor, nm, numColors, P.velPerm, P.velOffsDev,
1784 wantFused);
1785 // Position colouring, moved here from after the velocity phase (docs/contact_solve_framework.md
1786 // §4.2 item 3): both phases are coloured at the top of the solve. Its inputs (contacts, sleep
1787 // masks, the previous substep's ledger) do not change in between, so the move is byte-identical.
1788 // The overlap projection is coloured and swept per position UNIT (§4.3): all contacts of one
1789 // body pair (or of one body and one wall, §12 S6) in one work item, in ascending contact order.
1790 // A one-point unit is exactly the old per-contact edge, key and arithmetic.
1791 int numPosColors = 0;
1792 int numPosUnits = 0;
1793 PosUnits posUnits;
1794 P.numPosUnits = 0;
1795 if (P.velocityUseGS)
1796 numPosColors = colorPositionPhase<Hooks>(P, nc, nm, usePersistPre, incrColorOff, cSleep, pcs,
1797 slotBase, inv, numPosUnits, posUnits);
1798 // Rank-level M (docs/contact_solve_framework.md §13.3): on a rank that exchanges with a
1799 // neighbour, every body touched through a ghost is a mass-split copy set across ranks. The
1800 // activity pass gives each slot its local active copy count a per phase (0 or 1 outside a hub
1801 // group, the group's count at a hub base) from the final colourings; the openings make the
1802 // global k. A rank that neither sends nor receives (np 1 closed, an isolated block) keeps WO-4's
1803 // single-rank path (k = groupK), bit for bit: §13.3 "step 0".
1804 const bool rankM = Hooks::distributed && hooks.rankK().exchanges;
1805 if (rankM && P.velocityUseGS)
1806 countRankLevelActivity(P, nm, usePersistPre, posUnits, numPosUnits);
1811 inv.seal<Hooks>();
1812 // Dense colour buckets + fused sweep for the position projection (same precedent as the
1813 // velocity sweeps: colour classes are body-disjoint => bit-identical). The buckets list unit
1814 // indices.
1815 SweepPlan posPlan;
1816 planColorSweeps(posPlan, space, P, P.unitColor, numPosUnits, numPosColors, P.posPerm,
1817 P.posOffsDev, wantFused);
1818 // Persistent-contact restitution, gravity-gated (|g| = 0 leaves behaviour untouched: growth
1819 // packing / HCS bit-identical). A pair already in contact LAST substep is loaded, not impacting:
1820 // it gets e = 0 (the impulse still cancels the approach — pure inelastic support), so the
1821 // velocity solve carries a pile's static weight through impulse chains and a settling column
1822 // actually cools; material/wall restitution stays reserved for newly formed contacts.
1823 // Warm-started PGS velocity solve (|g| > 0): gather each manifold's previous-substep converged
1824 // push impulse by pair key, record the pre-solve approach (restitution bias), and apply the warm
1825 // impulses up front -- a static pile's force network is re-established in ~one sweep. g = 0
1826 // keeps the original one-shot colored-GS path bit-identical (HCS, growth packing).
1827 const bool usePGS = usePersistPre && P.velocityUseGS;
1828 // Rank-level X (§1.4, WO-6): the g = 0 one-shot on a rank that exchanges, when the rank graph
1829 // has more than one colour (with one colour no two ranks are adjacent, so no body is split
1830 // across ranks and every contact fires).
1831 const RankK rk = hooks.rankK();
1832#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 4
1833 const bool xOn = false; // G13 mutant 4: every rank fires every contact
1834#else
1835 const bool xOn = rankM && !usePGS && P.velocityUseGS && rk.numColors > 1;
1836#endif
1837 const float gMagP = Kokkos::sqrt(P.gravity.x * P.gravity.x + P.gravity.y * P.gravity.y +
1838 P.gravity.z * P.gravity.z);
1839 const F3 gHat = usePersistPre ? F3{P.gravity.x / gMagP, P.gravity.y / gMagP, P.gravity.z / gMagP}
1840 : F3{0, 0, 0};
1841 // Event-level (Poisson) restitution: per-pair banked compression budget, released as a
1842 // budget-capped separation-velocity target during unloading (see updateRestitutionBank /
1843 // PGSManifoldSweep). Off (empty views) the sweeps run the per-substep Newton path verbatim.
1844 const bool poisson = usePGS && P.restitutionModel == 1;
1845 const PoissonBankViews pv = poissonBankViews(P, poisson);
1846 const WarmStartContext warmCtx{.keyIdx = keyIdx,
1847 .gHat = gHat,
1848 .gMagP = gMagP,
1849 .nmVisible = nmVisible,
1850 .usePGS = usePGS,
1851 .poisson = poisson,
1852 .rankM = rankM};
1853 openVelocityWarmStart(P, nm, nBodies, hooks, space, warmCtx);
1854 // Velocity-phase copies (§4.4 step 6, §4.5): seeded once the warm start -- known impulses on
1855 // true masses -- has been applied (and, under MPI, published). The sweeps, the stabilization
1856 // passes and the multilevel cycle take the solve views and the slot overrides; the fold runs in
1857 // every iteration after the sweep; every rank sync re-marks the seeds (syncVelocityPhase).
1858 const bool velCopiesOn = vcs.nGroups > 0;
1859 // Rank-level M in the velocity phase (§13.3): the PGS path on an exchanging rank. The solve
1860 // views carry each slot's global k_vel (a hub copy its base's); the local fold still divides by
1861 // the local count a (groupK); the orphan shares B / k are already set by the opening.
1862 const bool velM = rankM && usePGS;
1863 const VelocitySolveViews sv = openVelocityCopies(P, slotBase, velM, velCopiesOn, pv);
1864 // §12 S14: a velocity phase with copies (local hub copies, or rank-level M) has not converged
1865 // while copies of one body disagree. Its stop votes fold in the largest consensus correction
1866 // since the previous vote (the local folds and the M syncs atomic-max it into P.maxConsensus),
1867 // through the SAME Allreduce-MAX; it is zeroed after each read. Without copies nothing is read
1868 // or written (np 1 without copies stays byte-identical).
1869 const bool velCons = velCopiesOn || velM;
1870 // §12 S13 (test-only): with P.noAdaptiveStop every loop runs its cap; the votes still run.
1871 const bool stopsOn = !P.noAdaptiveStop;
1872 const float fusedOff = -1.0f; // a fused device loop's tolerance that never stops
1873 const VelocitySolveContext velCtx{.velSched = velPlan.sched,
1874 .numColors = numColors,
1875 .velPermC = velPlan.sched.perm,
1876 .velFusedP = velPlan.sched.fused,
1877 .invMassVel = sv.invMass,
1878 .invInertiaVel = sv.invInertia,
1879 .velOv = sv.ov,
1880 .poissonViews = pv,
1881 .rk = rk,
1882 .gHat = gHat,
1883 .gMagP = gMagP,
1884 .nmVisible = nmVisible,
1885 .usePGS = usePGS,
1886 .poisson = poisson,
1887 .legacyFriction = legacyFriction,
1888 .sleepOn = sleepOn,
1889 .wantFused = wantFused,
1890 .xOn = xOn,
1891 .velCopiesOn = velCopiesOn,
1892 .velM = velM,
1893 .velCons = velCons,
1894 .stopsOn = stopsOn,
1895 .fusedOff = fusedOff};
1896 solveVelocityPhase(P, nc, nm, hooks, space, velCtx, inv);
1897 Kokkos::Profiling::popRegion();
1898 Kokkos::Profiling::pushRegion("dem::solve::stab_fric");
1899 stabilizeVelocityPhase(P, nm, nBodies, hooks, space, velCtx);
1900 closeVelocityPhase(P, nm, hooks, velCtx);
1901 if (legacyFriction) {
1903 hooks.syncFrictionCounts(P);
1904 // World-frame inverse inertia at the phase's frozen orientation P.quat (§12 S15).
1908 if constexpr (Hooks::distributed)
1909 hooks.syncVelocities(P); // publish the friction velocity update to the ghosts
1910 }
1911
1913 if constexpr (Hooks::distributed)
1914 hooks.publishPositions(P);
1915
1916 solvePositionPhase(P, nc, nm, hooks, space, pcs, slotBase, rankM, usePGS, posUnits, numPosUnits,
1917 posPlan.sched, stopsOn, fusedOff, inv);
1918 (void)space;
1919}
1920
1921} // namespace peclet::dem
1922
1923#endif // DEM_SOLVE_DRIVER_HPP
dem — portable (ArborX) broad-phase, the Kokkos-native replacement for the CUDA-only cuBQL broad-phas...
dem — portable (Kokkos) contact->manifold reduction, replacing the thrust-based reduce_contacts_to_ma...
int countLightHubs(const PhaseCopies &H, Kokkos::View< const int *, CpMem > eA, Kokkos::View< const int *, CpMem > eB, int nE, int nV, Kokkos::View< const float *, CpMem > invMass)
Light hubs (split_stats, R-P3): velocity hubs whose mass is below 10x the mean mass of their partners...
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 stabilizeOrdered(Particles &P, int nm, int nBodies, const Hooks &hooks, CpExec &space, const VelocitySolveContext &ctx, const float vRestS)
The ORDERED stabilization pass (stabilization mode 4, measurement mode): level-ordered symmetric swee...
void vertexDegree(Kokkos::View< const int *, CpMem > eA, Kokkos::View< const int *, CpMem > eB, int nE, int nV, Kokkos::View< int *, CpMem > deg)
Per-vertex active degree over [0, nV) (§4.4 step 1). Wall edges have one endpoint.
Kokkos::View< float *, CpMem > Vf
void finishActivity(Kokkos::View< const unsigned char *, CpMem > hit, int nSlots, PhaseCopies &H, Kokkos::View< int *, CpMem > a)
a(q) from the pass (§13.3): hit(q) for a slot outside any group; at a hub base the number of its grou...
void stabilizeVelocityPhase(Particles &P, int nm, int nBodies, const Hooks &hooks, CpExec &space, const VelocitySolveContext &ctx)
The stabilization pass after the main velocity phase (Guendelman staging, Phase B): when the symmetri...
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...
void activityHitVelocity(Kokkos::View< const ManifoldC *, CpMem > manifolds, int nm, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const int *, CpMem > color, SlotOverride ov, Kokkos::View< unsigned char *, CpMem > hit, int nSlots)
Rank-level activity pass (docs/contact_solve_framework.md §13.3 C4; the distributed step only),...
bool frictionOn(const Particles &P)
A frictional wall drives friction even when the body-body material is frictionless.
bool solvePositionColoredGS(Kokkos::View< const ContactC *, CpMem > contacts, const PosUnits &units, int numContacts, const ColorSchedule &sched, Kokkos::View< const float *, CpMem > invMass, Kokkos::View< float *[3], CpMem > posPred, Kokkos::View< const float *[4], CpMem > quatPred, Kokkos::View< const float *[4], CpMem > quatStatic, Kokkos::View< const float *[3], CpMem > invInertia, Kokkos::View< float, CpMem > maxOverlap, Kokkos::View< float *, CpMem > posLambdaAcc={}, const FusedLoopSpec *loop=nullptr, SlotOverride ov={}, Kokkos::View< float, CpMem > posResidual={}, float omega=1.0f)
Colored Gauss–Seidel XPBD overlap solve: sweep the numColors colour classes in order,...
void solveContactFriction(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, const BodyState &bodies, const BodyPred &pred, Kokkos::View< const int *, CpMem > realIdx, FrManifoldCounts planeFriction, float frictionDynamic, const BodyDelta &delta)
One count-averaged Coulomb friction sweep.
void markCopySeeds(const PhaseCopies &H, Kokkos::View< float *[3], CpMem > x, Kokkos::View< float *[3], CpMem > w, Kokkos::View< float *, CpMem > orphan, Kokkos::View< float *, CpMem > orphanPeak, bool shareFromBase=false)
Mark the phase seed sigma of every group and re-seed its members from the base (§4....
void commitPosImpulse(Kokkos::View< const float *, CpMem > posLambdaContact, int numContacts, Kokkos::View< const int *, CpMem > contactSlot, Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const unsigned long long *, CpMem > keys, Kokkos::View< const unsigned long long *, CpMem > prevKeysSorted, int prevCount, float dt, Kokkos::View< float *, CpMem > scratchManifold, Kokkos::View< float *, CpMem > prevPosImpulse)
After the position solve: convert the per-contact positional lambdas into an impulse- equivalent per ...
float maxOwnedRadius(const Particles &P)
Largest effective particle radius over the owned set (= max scale × globalScale, growth included).
void applyVelocityDeltas(int n, V3 velPred, V3 angVelPred, V3 deltaVel, V3 deltaAngVel)
Add accumulated velocity/angular deltas onto the predicted velocity, then clear the delta buffers.
void applyUpdates(int n, const BodyPred &pred, const BodyDelta &delta, bool averaged=true)
Jacobi count-averaged apply of position/velocity deltas, then clear deltas + counts.
void positionEdgeEnds(Kokkos::View< const ContactC *, CpMem > contacts, const PosUnits &units, int nu, Kokkos::View< const int *, CpMem > color, Kokkos::View< int *, CpMem > eA, Kokkos::View< int *, CpMem > eB)
Position-phase colouring edges: one per unit, the leader contact's raw (bodyA, bodyB); active = the u...
bool gravityOn(const Particles &P)
Whether gravity is on (any component non-zero): it gates persistent contacts, warm-started PGS and is...
void velocityEdgeEnds(Kokkos::View< const ManifoldC *, CpMem > manifolds, int nm, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const int *, CpMem > color, Kokkos::View< int *, CpMem > eA, Kokkos::View< int *, CpMem > eB)
Velocity-phase colouring edges: the vertices realIdx(bodyA / bodyB) of each manifold (-1: a wall end,...
void solvePositionPhase(Particles &P, int nc, int nm, const Hooks &hooks, CpExec &space, PhaseCopies &pcs, int slotBase, bool rankM, bool usePGS, const PosUnits posUnits, int numPosUnits, const ColorSchedule &posSched, bool stopsOn, float fusedOff, ColoringInvariant &inv)
The position phase (docs/contact_solve_framework.md §4.4, §4.5, §13.3 step 9; WO-12): seed the positi...
Kokkos::View< int *, CpMem > Vi
void buildSolveViewsRankK(Particles &P, const PhaseCopies &H, int nSlots, Kokkos::View< const float *, CpMem > invMass, Kokkos::View< const float *[3], CpMem > invInertia, Kokkos::View< const int *, CpMem > kRank)
Solve views under rank-level M (§13.3, §4.5): invMassSolve / invInertiaSolve = k x the body's masses ...
void demSolveContacts(Particles &P, int nc, int nm, int nBodies, Kokkos::View< const int *, CpMem > keyIdx, const Hooks &hooks)
One full velocity + position contact solve over the already-built contacts/manifolds (see file commen...
int colorContacts(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, int numBodies, Kokkos::View< int *, CpMem > cColor, const ColorScratch &scratch, int &leftover, Kokkos::View< const unsigned char *, CpMem > sleepMask={}, PosUnits units={}, SlotOverride ov={}, int vertexSpan=0)
Greedy graph-colour the contacts (raw bodyA/bodyB): no two contacts sharing a body get the same colou...
void planColorSweeps(SweepPlan &plan, CpExec &space, Particles &P, Kokkos::View< int *, CpMem > color, int n, int numColors, Kokkos::View< int *, CpMem > perm, Kokkos::View< int *, CpMem > offsDev, bool wantFused)
Dense colour buckets for one phase's PGS sweeps (bit-identical: colour classes are body-disjoint) ove...
void applyVelocityAndPredictPosition(int n, const BodyState &bodies, const BodyPred &pred, float dt)
Re-integration: persist solved velocity, trapezoidal position predict, quaternion integrate.
int colorVelocityPhase(Particles &P, int nm, int nBodies, bool usePersistPre, bool incrColorOff, const Kokkos::View< const unsigned char *, CpMem > mSleep, PhaseCopies &vcs, int slotBase, ColoringInvariant &inv)
Velocity-phase colouring (docs/contact_solve_framework.md §4.2 item 4, §4.4), the PGS paths only: col...
CpExec::memory_space CpMem
int * demIterCountSlot(Particles &P, int slot)
Diagnostics (docs/contact_solve_framework.md §12 S12): the device scalar a fused main loop writes its...
Kokkos::View< const float *[3], CpMem > coarseVertexInvInertia(Particles &P, int nBodies, bool velM)
The coarse vertices' inverse inertias for the multilevel pass (the same fraction).
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).
void buildCoarseBuckets(const ContactHierarchy &H, MlScratch &S, int numManifolds, Kokkos::View< int *, CpMem > colorScratch, Kokkos::View< int *, CpMem > perm, Kokkos::View< int *, CpMem > cursor, std::vector< std::vector< int > > &offs)
One multilevel stabilization cycle over an already-built hierarchy: fine colored smoothing is the cal...
void solveVelocityPhase(Particles &P, int nc, int nm, const Hooks &hooks, CpExec &space, const VelocitySolveContext &ctx, ColoringInvariant &inv)
The main velocity phase (docs/contact_solve_framework.md §4.4, §4.5, §13.3): the warm-started PGS ite...
void buildColorBuckets(Kokkos::View< const int *, CpMem > colorOf, int n, int numColors, Kokkos::View< int *, CpMem > perm, Kokkos::View< int *, CpMem > cursor, std::vector< int > &offs)
Dense colour buckets (numColors <= 64): perm[offs[c] .
void closeVelocityPhase(Particles &P, int nm, const Hooks &hooks, const VelocitySolveContext &ctx)
The close of the velocity phase (§13.3 step 8): the orphan accounts back to balances,...
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...
void countFrictionContacts(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, Kokkos::View< const int *, CpMem > realIdx, FrManifoldCounts planeFriction)
Per-body active-contact count into planeFriction(:,1).
bool demFusedWanted(bool graphReplayAvailable, int mode)
Fused-sweep policy.
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.
void activityHitPosition(Kokkos::View< const ContactC *, CpMem > contacts, const PosUnits &units, int nu, Kokkos::View< const int *, CpMem > color, SlotOverride ov, Kokkos::View< unsigned char *, CpMem > hit, int nSlots)
The same over the position phase's units (raw slots of the leader contact, through the overrides).
void reseedCopies(CpExec space, const PhaseCopies &H, Kokkos::View< float *[3], CpMem > x, Kokkos::View< float *[3], CpMem > w)
Re-seed every member from its base, sigma unchanged (the multilevel pass, after the coarse cycle has ...
int colorContactsIncremental(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, int numBodies, const CarriedColors &carried, Kokkos::View< int *, CpMem > cColor, Kokkos::View< unsigned long long *, CpMem > keysOut, const ColorScratch &scratch, int &leftover, bool forceFull, Kokkos::View< const unsigned char *, CpMem > sleepMask={}, PosUnits units={})
Incremental (warm-started) contact colouring for the single-GPU PGS position solve.
VelocitySolveViews openVelocityCopies(Particles &P, int slotBase, bool velM, bool velCopiesOn, const PoissonBankViews &pv)
void stabilizeOneSided(Particles &P, int nm, const Hooks &hooks, CpExec &space, const VelocitySolveContext &ctx, const float vRestS)
The ONE-SIDED grounded stabilization pass (stabilization mode 1, the default): held-lower-side impuls...
void buildHubCopies(Kokkos::View< const int *, CpMem > eA, Kokkos::View< const int *, CpMem > eB, int nE, int nV, int slotBase, Kokkos::View< const int *, CpMem > deg, PhaseCopies &H)
Build one phase's hub copies (§4.4 steps 2, 3 and 5): every vertex with d > kHubEdgeBudget active edg...
int readInt(Kokkos::View< int, CpMem > v)
float readFloat(Kokkos::View< float, CpMem > v)
void openVelocityWarmStart(Particles &P, int nm, int nBodies, const Hooks &hooks, CpExec &space, const WarmStartContext &ws)
The velocity phase's warm start and opening (docs/contact_solve_framework.md §13.3 step 5): on the PG...
void buildInvInertiaCoarse(Kokkos::View< const float *[3], CpMem > invInertia, Kokkos::View< const int *, CpMem > k, Kokkos::View< const int *, CpMem > a, int n, Kokkos::View< float *[3], CpMem > out)
The multilevel coarse vertex's inverse inertia (docs/contact_physics_followups.md §2....
void countRankLevelActivity(Particles &P, int nm, bool usePersistPre, const PosUnits &posUnits, int numPosUnits)
Rank-level M's activity pass (docs/contact_solve_framework.md §13.3) on a rank that exchanges: size t...
void computePlaneLoad(Kokkos::View< ContactC *, CpMem > contacts, int numContacts, const BodyState &bodies, const BodyPred &pred, FrManifoldCounts planeFriction)
Plane (idB<0) one-shot loads.
void buildSolveViews(Particles &P, const PhaseCopies &H, int nSlots, Kokkos::View< const float *, CpMem > invMass, Kokkos::View< const float *[3], CpMem > invInertia)
Solve views of a phase (§4.5): invMassSolve / invInertiaSolve = the phase's masses on every slot in [...
float withConsensus(Particles &P, float res, bool cons)
§12 S14: a stop vote's residual with the largest consensus correction since the previous vote folded ...
void commitContactColor(Kokkos::View< const unsigned long long *, CpMem > keys, Kokkos::View< const int *, CpMem > color, Kokkos::View< unsigned long long *, CpMem > prevKeys, Kokkos::View< int *, CpMem > prevColor, Kokkos::View< int *, CpMem > perm, int numContacts)
Commit this substep's per-contact (key, colour) sorted by key, for next substep's warm gather.
void stabilizeEscalation(Particles &P, int nm, const Hooks &hooks, CpExec &space, const VelocitySolveContext &ctx, const float vRestS)
The ESCALATION stabilization pass (stabilization mode 3, diagnostic/fallback): plain symmetric colour...
void seedCopySlotState(Particles &P, const PhaseCopies &H)
Seed the copy slots' read-only state from their hub vertex (§4.4 step 6): orientation,...
Kokkos::DefaultExecutionSpace CpExec
void growCopySlots(Particles &P, int slotBase, int nCopies)
Room for nCopies copy slots appended at slotBase (the colour phases' hub copies).
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...
int demReadIterCount(const Particles &P, int slot)
The count a fused main loop wrote (one small readback, only with P.iterCounters on); -1 with the coun...
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 commitPairKeysLambda(const PairLedger &cur, const PairLedger &prev, Kokkos::View< int *, CpMem > perm, int numManifolds, Kokkos::View< const int *, CpMem > color={}, Kokkos::View< int *, CpMem > prevColor={})
Save this substep's keys + converged impulses (normal AND tangential) and key-sort them for next subs...
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...
int findCollisionsGrow(Particles &P, float margin)
Broad phase with an automatically-grown pair buffer.
int buildPositionUnits(Kokkos::View< const ContactC *, CpMem > contacts, int n, Kokkos::View< int *, CpMem > unitStart, Kokkos::View< int *, CpMem > unitContacts, int numManifolds=-1)
Build the position units of contacts [0, n) (docs/contact_solve_framework.md §4.3,...
void fillGidBase(Vi gid, int n, int base)
gid(i) = base + i over [0, n) — the per-rank global-id re-base of the distributed step (namespace sco...
constexpr float kSplitOmegaVelocity
Split relaxation (§4.5, §13.1): the PGS normal step on an edge touching a mass-split slot is scaled b...
void stabilizeMultilevel(Particles &P, int nm, int nBodies, const Hooks &hooks, CpExec &space, const VelocitySolveContext &ctx, const float vRestS)
void syncVelocityPhase(Particles &P, const Hooks &hooks, const VelocitySolveContext &ctx)
A rank sync inside the velocity phase: orphan accounts back to balances, the raw reverse + forward,...
void massSplitVelocityIteration(Particles &P, int nm, const Hooks &hooks, float vRest)
Mass-split Jacobi (velocityUseGS off, a global setting; docs/contact_solve_framework....
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...
bool launchFusedVelocityLoop(Particles &P, int nm, float vRest, const VelocitySolveContext &ctx)
The main velocity phase's device-side iteration loop (CUDA, single-rank PGS with a fused schedule and...
void oneShotVelocityIteration(Particles &P, int nm, int it, float vRest, CpExec &space, const VelocitySolveContext &ctx)
One iteration of the g = 0 one-shot coloured GS velocity solve (velocityUseGS on, PGS off): the resid...
void foldVelocityCopies(CpExec &space, Particles &P, const VelocitySolveContext &ctx)
The velocity-phase copies' fold, run in every iteration after the sweep (none without copies).
void fillWorldRadii(Vf scale, Vf rad, float gs, float bR, int n)
World radii rad(i) = scale(i) * globalScale * baseRadius over [0, n): the owned span before a step,...
void markPersistentManifolds(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const int *, CpMem > keyIdx, Kokkos::View< const unsigned long long *, CpMem > prevKeys, int prevCount, Kokkos::View< unsigned long long *, CpMem > outKeys, Kokkos::View< unsigned char *, CpMem > outFlags)
keyIdx maps a body slot to the identity the pair key is built from: the REAL index map on the single-...
void updateGroundedLevels(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const float *[3], CpMem > posPred, F3 gHat, Kokkos::View< unsigned char *, CpMem > grounded, int numReal, int sweeps, int decay)
Guendelman support levels, warm-started: decay every body's level by decay, re-seed 255 at wall/plane...
void gatherWarmLambda(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const int *, CpMem > keyIdx, const PairLedger &prev, Kokkos::View< const float *, CpMem > prevPosImpulse, int prevCount, const PairLedger &out, Kokkos::View< float *, CpMem > outPosImpulse, Kokkos::View< unsigned char *, CpMem > outMatched={}, bool dedupTwins=true)
Warm-start gather for the PGS velocity solve: per manifold, write its pair key and look up the previo...
int countSplitBodies(const PhaseCopies &H)
Count the bodies whose group has k > 1 (split_stats).
int countSplitAggregated(Kokkos::View< const int *, CpMem > parent, int off, int nV, int nGroups1, Kokkos::View< const unsigned char *, CpMem > split)
split_stats.mlHubAggregated (§13.2's positive control): the vertices v in [0, nV) with split(v) !...
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.
int findCollisionsVerlet(Particles &P, float margin, float maxRad)
Verlet-cached impulse broadphase (single-GPU, non-periodic).
void recordMultilevelHierarchy(Particles &P, int nm, int nBodies, const ContactHierarchy &H, const MlScratch &S, bool velM, bool velCopiesOn)
The multilevel hierarchy's diagnostics: the debug-build inactive-vertex check, the hub aggregation co...
long long countUnfired(Kokkos::View< const unsigned char *, CpMem > gate, int nm)
Diagnostics (iterCounters): the number of gated-off manifolds of one sweep.
void computeHeightLevels(Kokkos::View< const ManifoldC *, CpMem > manifolds, int numManifolds, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const float *[3], CpMem > posPred, F3 gHat, Kokkos::View< int *, CpMem > heights, int numReal)
int colorPositionPhase(Particles &P, int nc, int nm, bool usePersistPre, bool incrColorOff, const Kokkos::View< const unsigned char *, CpMem > cSleep, PhaseCopies &pcs, int slotBase, ColoringInvariant &inv, int &numPosUnits, PosUnits &posUnits)
Position-phase colouring (docs/contact_solve_framework.md §4.2 item 3, §4.3, §4.4),...
void multilevelCoarseCycle(const MlManifoldViews &mv, int numManifolds, Kokkos::View< const float *, CpMem > invMass, Kokkos::View< float *[3], CpMem > velPred, int numReal, const ContactHierarchy &H, MlScratch &S, int coarseSweeps, const MlBodyViews &body, const std::vector< std::vector< int > > *bkOffs=nullptr, Kokkos::View< const int *, CpMem > bkPerm={}, const MlFusedCtx *fused=nullptr)
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...
void solvePosition(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, const BodyState &bodies, const BodyPred &pred, const BodyDelta &delta, Kokkos::View< float, CpMem > maxOverlap, Kokkos::View< const int *, CpMem > onlyColor={}, int colorFilter=0, bool massSplit=false)
Accumulate XPBD position corrections for numContacts contacts.
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),...
PoissonBankViews poissonBankViews(Particles &P, bool on)
The solve's Poisson views: the banks and the orphan accounts when the model is on,...
MlFusedCtx demMakeMlFusedCtx(CpExec &space, const ContactHierarchy &H, const std::vector< std::vector< int > > &bkOffs, int numManifolds, int numReal, int coarseSweeps, Kokkos::View< int *, CpMem > offsDev, Kokkos::View< unsigned *, CpMem > bar)
Build the fused-coarse-cycle context from an already-built hierarchy + its dense buckets: flatten the...
void growCopyView(V &v, std::size_t n, const char *label)
Grow-only (re)allocation of a copy-machinery view to at least n entries.
void countPositionJacobi(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, Kokkos::View< int *, CpMem > counts)
Mass-split Jacobi count pass (docs/contact_solve_framework.md §3.1, D3): per body slot,...
void runOverlapProjection(Particles &P, int nc, const Hooks &hooks, CpExec &space, const PositionSolveContext &ctx, EmitPosIter &&emitPosIter, SyncPos &&syncPos, ColoringInvariant &inv)
The overlap projection's iterations to their adaptive stop (WO-12): the fused device loop (CUDA,...
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 ...
void buildCopyGroups(Kokkos::View< const int *, CpMem > realIdx, int span, int numReal, Kokkos::View< const int *, CpMem > deg, Kokkos::View< const float *[3], CpMem > imageShift, PhaseCopies &H, bool identityBodies=false)
Build the fold groups of a phase (§4.4 "local fold", §WO-4 item 2): every body with more than one slo...
void allocateMultilevelPools(Particles &P, int nBodies)
The multilevel pass's rigid-aggregate pools and coarse accumulator, sized for nBodies.
void expandUnitColors(const PosUnits &units, int numUnits, Kokkos::View< const int *, CpMem > unitColor, Kokkos::View< int *, CpMem > contactColor)
Copy each position unit's colour onto its contacts (contactColor(i) = unitColor(unit of i)).
void foldCopies(CpExec space, const PhaseCopies &H, Kokkos::View< float *[3], CpMem > x, Kokkos::View< float *[3], CpMem > w, Kokkos::View< float *, CpMem > orphan, Kokkos::View< float *, CpMem > orphanPeak, Kokkos::View< float, CpMem > consensus={})
The local fold (§4.4), once per iteration after the sweep: per group T = sum over the ACTIVE members ...
int findCollisionsArborX(PosV pos, RadV rad, int numParticles, int numReal, float margin, PairsV outPairs, CountV outCount, float boxCap=0.0f)
Emit candidate collision pairs (i<j) for real particles into outPairs/outCount.
void accumulateNormalImpulse(Kokkos::View< ContactC *, CpMem > contacts, int numContacts, const BodyState &bodies, const BodyPred &pred, Kokkos::View< const int *, CpMem > realIdx, float growthRate, bool dedupTwins=true)
Force-chain normal load, accumulated over the velocity iterations: contacts(idx).friction_lambda_n +=...
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...
bool islandSleepingOn(const Particles &P, bool gravity)
Island sleeping: single-GPU statics, gravity on, no external drag.
int countInactiveAggregated(Kokkos::View< const int *, CpMem > parent, int off, int nV, int nGroups1, Kokkos::View< const int *, CpMem > a)
Debug-build check (§13.2, §13.5 WO-5 item 4): the vertices with a = 0 that sit in a level-1 multileve...
FusedSweepCtx demMakeFusedCtx(CpExec &space, const std::vector< int > &offs, Kokkos::View< int *, CpMem > offsDev, Kokkos::View< unsigned *, CpMem > bar)
Fill a FusedSweepCtx from buildColorBuckets's host offsets: async-upload them into the pooled device ...
void buildInvMassCoarse(Kokkos::View< const float *, CpMem > invMass, Kokkos::View< const int *, CpMem > k, Kokkos::View< const int *, CpMem > a, int n, Kokkos::View< float *, CpMem > out)
The multilevel coarse vertex's inverse mass (§13.2): invMass(q) (k(q) / max(1, a(q))),...
VelocitySweepBodies velocitySweepBodies(Particles &P, Kokkos::View< const float *, CpMem > invMass, Kokkos::View< const float *[3], CpMem > invInertia, SlotOverride ov={})
The velocity sweep's bodies: the masses invMass/invInertia (true masses or the solve copies'),...
Kokkos::View< const float *, CpMem > coarseVertexInvMass(Particles &P, int nBodies, bool velM)
The MULTILEVEL (GraphMG) stabilization pass (stabilization mode 2): fine sweeps plus a coarse cycle o...
ContactHierarchy buildContactHierarchy(const MlEligibility &elig, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const float *, CpMem > invMass, int numReal, MlScratch &S, const ColorScratch &scratch, bool excludeImmovable=false, Kokkos::View< const unsigned char *, CpMem > asleep={}, const MlBodyViews &body={})
Build the aggregation hierarchy + per-level crossing-manifold colorings.
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") ...
void unfoldOrphan(const PhaseCopies &H, Kokkos::View< float *, CpMem > orphan)
Orphan accounts back from share form (before a rank sync and at the end of the velocity phase): the b...
dem — portable (Kokkos) particle SoA container: the storage the dem flip pivots on.
dem — body copies of the contact solve (docs/contact_solve_framework.md §4.4, §4.5,...
#define PECLET_DEM_GRAPH_LOOP(useVar, graphVar, emitVar, slotVar)
dem — portable (Kokkos) Coulomb friction cluster (the single dissipative friction path).
dem — multilevel (GraphMG-style) momentum-conserving contact stabilization.
dem — portable (Kokkos) XPBD position solve (pure overlap removal).
dem — portable (Kokkos) manifold velocity solve (normal restitution impulse).
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
The colour classes one coloured sweep visits: manifolds [0, numManifolds), labelled by mColor in [0,...
The colouring invariant (§4.2 item 4, §12 S3): the failing phase's edges, the accumulated message,...
float vote(const Hooks &hooks, float res)
Kokkos::View< int *, CpMem > edgeA
Kokkos::View< int *, CpMem > edgeB
void note(const char *phase, Kokkos::View< const int *, CpMem > color, int n, Kokkos::View< const int *, CpMem > vertexDegree)
Host-side description of one built hierarchy (offsets into the packed group pools).
bool capture(CpExec &, F &&, void *&)
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...
The per-body inputs of the rigid coarse space (§2.3-§2.5): the predicted positions (the member offset...
The manifolds of a hierarchy build and the inputs of mldetail::eligible (constant over the build): th...
Fused-coarse-cycle context: flat per-level colour offsets on device + barrier + meta.
The manifold side of a coarse sweep: the manifolds, their real-body map, the shared impulse accumulat...
Device scratch for the multilevel pass, sized once (see Particles::allocate).
Kokkos::View< int *, CpMem > parent
One full colored PGS sweep.
std::vector< int > parentOff
std::vector< int > numGroups
Kokkos::View< float, CpMem > posResidual
Kokkos::View< int *, CpMem > commitPerm
Kokkos::View< unsigned *, CpMem > fusedBar
Kokkos::View< unsigned char *, CpMem > asleep
Kokkos::View< int *, CpMem > bucketCursor
Kokkos::View< unsigned char *, CpMem > sideFlags
Kokkos::View< unsigned long long *, CpMem > prevContactKeys
Kokkos::View< int *, CpMem > mlGrp
Kokkos::View< unsigned char *, CpMem > xGate
Kokkos::View< unsigned char *, CpMem > manifoldPersistent
Kokkos::View< int *, CpMem > aPos
Kokkos::View< float *[3], CpMem > impRefPos
Kokkos::View< int *, CpMem > posOffsDev
Kokkos::View< float *, CpMem > bodyOrphanVPeak
Kokkos::View< int *, CpMem > velPerm
PairLedger pairLedger() const
Kokkos::View< unsigned char *, CpMem > contactSleep
void ensureCapacity(int newCap)
Kokkos::View< int *, CpMem > unitStart
Kokkos::View< ManifoldC *, CpMem > manifolds
Kokkos::View< float *[3], CpMem > mlOriginG
Kokkos::View< float *, CpMem > vn0
Kokkos::View< float *, CpMem > mlMassG
Kokkos::View< int *, CpMem > levelKey
Kokkos::View< int *[2], CpMem > pairs
Kokkos::View< float *[3], CpMem > invInertiaSolve
Kokkos::View< float *[3], CpMem > imageShift
BodyPred bodyPred() const
Kokkos::View< float *[3], CpMem > mlAngG0
Kokkos::View< float *[3], CpMem > vt0
Kokkos::View< int *, CpMem > vertexDegree
Kokkos::View< float *, CpMem > restRel
Kokkos::View< int *, CpMem > levelPerm
Kokkos::View< int *, CpMem > prevManifoldColor
Kokkos::View< float *[3], CpMem > mlAngG
Kokkos::View< unsigned char *, CpMem > splitSlot
Kokkos::View< int *, CpMem > kVel
Kokkos::View< float *[3], CpMem > mlComOffG
Kokkos::View< unsigned long long *, CpMem > contactKeys
Kokkos::View< int *, CpMem > prevContactColor
Kokkos::View< unsigned char *, CpMem > prevMatched
Kokkos::View< unsigned char *, CpMem > activityHit
Kokkos::View< float, CpMem > maxApproach
Kokkos::View< float *, CpMem > restVPeak
Kokkos::View< float *, CpMem > restBank
CarriedColors prevManifoldColors() const
Kokkos::View< int *, CpMem > posCommitPerm
Kokkos::View< int *, CpMem > velOffsDev
Kokkos::View< int *, CpMem > mlOffsDev
Kokkos::View< unsigned long long *, CpMem > pairKeys
BodyState bodyState() const
struct peclet::dem::Particles::MlLast mlLast
Kokkos::View< int *, CpMem > aVel
Kokkos::View< float, CpMem > maxConsensus
Kokkos::View< float *, CpMem > bodyOrphan
Kokkos::View< unsigned long long *, CpMem > prevPairKeys
Kokkos::View< int *, CpMem > posPerm
Kokkos::View< float *, CpMem > prevPosImpulse
ColorScratch colorScratch() const
Kokkos::View< int *, CpMem > contactColor
Kokkos::View< float *[3], CpMem > mlVelG
Kokkos::View< float *, CpMem > invMassSolve
Kokkos::View< float *[3], CpMem > mlVelG0
Kokkos::View< int *, CpMem > mlBucketPerm
Kokkos::View< float *[3], CpMem > invInertiaCoarse
Kokkos::View< int *, CpMem > mlParent
Kokkos::View< float *[3], CpMem > lambdaT
CarriedColors prevContactColors() const
Kokkos::View< int *, CpMem > unitColor
Kokkos::View< int *, CpMem > kPos
Kokkos::View< float, CpMem > maxOverlap
Kokkos::View< float *, CpMem > posLambdaContact
Kokkos::View< unsigned long long *, CpMem > velMask
Kokkos::View< float *, CpMem > posImpulse
Kokkos::View< int *, CpMem > contactSlot
PairLedger prevPairLedger() const
Kokkos::View< float *, CpMem > mlInvMassG
Kokkos::View< int *, CpMem > heightLevel
BodyDelta bodyDelta() const
Kokkos::View< float *, CpMem > lambdaAcc
Kokkos::View< double *[7], CpMem > mlAccD
Kokkos::View< long long *, CpMem > mlColorPacked
Kokkos::View< float *, CpMem > invMassCoarse
Kokkos::View< int *, CpMem > iterCountDev
Kokkos::View< float, CpMem > maxApproachQS
Kokkos::View< unsigned char *, CpMem > manifoldSleep
Kokkos::View< const float *, CpMem > crad() const
Kokkos::View< float *[2], CpMem > planeFriction
Definition particles.hpp:98
Kokkos::View< int *, CpMem > mlMate
Kokkos::View< ContactC *, CpMem > contacts
Kokkos::View< int, CpMem > pairCount
Kokkos::View< unsigned char *, CpMem > groundedLevel
Kokkos::View< int *, CpMem > unitContacts
Kokkos::View< int *, CpMem > manifoldColor
Kokkos::View< float *[6], CpMem > mlInvIG
One solve phase's body copies (docs/contact_solve_framework.md §4.4, §4.5, §WO-4 item 2): the hub cop...
Definition particles.hpp:44
Kokkos::View< int *, CpMem > slotB
Definition particles.hpp:47
Kokkos::View< int *, CpMem > slotA
Definition particles.hpp:47
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 position units of a contact list as a CSR (§4.3): unit u owns the contacts list(start(u)) .
The overlap projection's loop context: what its iterations read that solvePositionPhase settles befor...
Rank-level M (docs/contact_solve_framework.md §13.3) as the hooks expose it to the driver: whether th...
Shock propagation for persistent loaded contacts (see solveVelocity): the persistence flags,...
Per-edge slot overrides of a phase's hub copies (docs/contact_solve_framework.md §4....
Single-GPU hooks: no ghost refresh, residuals are already global. Everything inlines away.
float allMaxAny(float v, bool &) const
static constexpr bool distributed
void beginSolve(Particles &) const
void restoreOrphanBalance(Particles &) const
void publishPositions(Particles &) const
void syncContactCounts(Particles &) const
int visibleManifolds(int nm) const
float allMax(float v) const
void openPositionCounts(Particles &, bool) const
void syncVelocities(Particles &) const
void syncFrictionCounts(Particles &) const
void syncPositions(Particles &) const
void openVelocityPhase(Particles &, bool) const
diagnostics.split_stats() (docs/contact_solve_framework.md §WO-4 item 4, §13.5 WO-4b): the last subst...
Definition particles.hpp:66
long long unfiredSplitContacts
Definition particles.hpp:68
One coloured phase's sweep plan: owns the dense-bucket offsets and the fused context that its ColorSc...
std::vector< int > offs
SweepPlan & operator=(const SweepPlan &)=delete
SweepPlan(const SweepPlan &)=delete
The velocity phase's solve context: everything the velocity-phase loops read that demSolveContacts se...
Kokkos::View< const float *, CpMem > invMassVel
Kokkos::View< const int *, CpMem > velPermC
Kokkos::View< const float *[3], CpMem > invInertiaVel
The velocity phase's solve views and slot override: true masses; the hub copies' split masses; or eac...
Kokkos::View< const float *, CpMem > invMass
Kokkos::View< const float *[3], CpMem > invInertia
The bodies a velocity sweep reads and updates in place: mass data and orientation,...
The warm start's inputs that demSolveContacts settles before it: the pair-key map,...
Kokkos::View< const int *, CpMem > keyIdx
Rank-level X evaluated inline in the one-shot sweep (only for the manifolds of the colour being swept...