A cloth solver that never leaves the GPU
BorrowedTorch.FabricSimulator is a MonoGame package. A compute shader integrates the particles, relaxes the threads between them and computes the normals. Then it stops. Your own vertex shader reads the same buffer and draws the sheet.
- Verlet integration on a fixed 120 Hz step, Jacobi relaxation
- Structural, shear and plastic bending threads, long-range pin attachments
- Sphere and ground colliders, self-collision through a spatial hash
- Live cuts and tears, wind as an air velocity
- A rest deadband and a hold, so settled cloth, even a crumpled pile, stays exactly still
What is in the solution
Three projects. The library sits at the repository root; Demo/ is a MonoGame game that
references it and compiles the shaders exactly as a package host would; Tests/ is an
xUnit project for the maths that needs no GPU.
The bars are drawn to scale by line count. The clean-lip cut mesh alone is almost a third of the
library; the kernels, Fabric and FabricEffect are each 1,700 to 1,900
lines.
Three classes and one boundary
FabricSettingsis a plain object of knobs. It is checked and uploaded every frame, so changes apply live; the sheet fields (the grid,RestLength,SeedRipple) wait forRebuild(), whichAutoRebuildcalls for you.Fabricis the CPU model of the grid: placement, pins, pin distances, tears, triangle indices.FabricEffectowns its own copy of the solver effect, the GPU buffers, the fixed-step clock and the dispatches.
The dashed boxes are GPU work. Nothing returns to the CPU in a normal frame. Cuts and pin changes
re-measure the anchors on the CPU and upload them; only picking (CaptureSurface) and
the diagnostics read back.
new FabricEffect(device, Content) loads FabricCompute.xnb,
clones it, checks passes and header contract
new Fabric(effect, settings) builds nothing;
set the layout, then Rebuild()BuildParticles() → SetParticles()
+ Apply() → Rebuiltfabric.Update(dt)Rebuild() if AutoRebuild sees a
changed layout, FlushAnchors() if pins changed, Effect.Apply(Settings),
Effect.Update(dt)Step() × 0…MaxStepsPerFrame
solver.ParticleBuffer to your shader,
every frame
FabricParticles[SV_VertexID] →
position, normal, UV
One simulation step
FabricEffect.Step() is a fixed sequence of compute dispatches. Change the knobs and the
list below rebuilds itself with the same logic as the C# code.
Self-collision fills the hash and then gathers each particle's contact candidates, once a step. Every
round that solves bending is preceded by a Bend pass. At RelaxationIterations =
0 one round still runs, without threads, so the colliders and the pins' reach hold.
The fixed-step clock
The solver always steps at SolverFrequencyHz (120 by default), whatever the frame rate.
Update adds the frame time to an accumulator and runs whole steps while it can.
- At 60 fps every frame runs exactly two steps.
- At 144 fps some frames run none and redraw the same pose. That is what
InterpolationFractionfixes (slide 1.5). - A slow frame catches up at most
MaxStepsPerFramesteps; the rest of the backlog is dropped (IsSaturated), so one hitch cannot snowball. - A frame time that is NaN counts as none. It used to pass the clamp and stop the clock for good.
The shaders ship as source
A compiled effect carries an MGFX version the runtime rejects outright, so a precompiled blob would
be tied to one build of one fork. The package ships HLSL instead, and its targets file, under buildTransitive/,
feeds it to the host's own content build.
The targets flow to transitive references too, and the switch is on by default only for an executable, so a library between the package and the game copies nothing and the game gets the shaders. Flip the switches to see which MSBuild target fires.
contentSource/: BorrowedTorch.FabricSimulator.mgcb
+ Effects/Fabric/*.fx(h)packed by the .csproj None Update …
PackagePath itemsBorrowedTorchFabricCopyShaderSource, before CollectContentReferencescopies
into Content/, keeping folders so #include resolves
**/*.mgcb and compiles FabricCompute.fxtwo
response files in one folder do not collideContent/Effects/Fabric/FabricCompute.xnb = FabricEffect.DefaultEffectPath
One particle, sixty-four bytes
Every grid point is one FabricParticle. It is declared twice, in C# and in HLSL, field
for field. Every pass streams the whole grid, so anything derivable is left out: no velocity, no
texture coordinates.
The three pin fields are a copy. The solver keeps its pins in an 8-byte anchor buffer of its own (slide 2.4) and writes them into the record every step, so a readback shows the pins in force as of the last step, and an upload's values set them.
Why there is no velocity field
Verlet integration keeps two positions instead of a position and a velocity. Velocity is simply the
gap between them, so anything that moves Position (a constraint, a collision) changes
the velocity too, for free.
PrevPosition ← Position · Position ← next
The gap was measured over the last step, so when SolverFrequencyHz changes the solver
scales it by DisplacementScale (this step's length over the last one's), and Damping
is stated per 1/120 s and rescaled to the step (slide 4.7).
The hollow dot is PrevPosition, the filled one Position; the arrow is the
implied velocity.
Three guards against drift
Because the HLSL is copied into the host's tree, the headers and the assembly can come from different releases. Nothing in the toolchain checks that the C# and HLSL agree, so the library checks three ways.
- Passes: the constructor looks up the technique and all eight passes by name. A solver
compiled from an older release lacks
BendPassandGatherCandidatesPass, and throws naming the pass, not on the first dispatch. - Size:
Marshal.SizeOfmust be 64. Catches a field added or resized. - Defines: the constructor regex-reads
#define FabricShaderContractVersion(now 3) from the header on disk, andGroupSizeandContactCandidateCapacity(32) beside it. Catches a reorder, which keeps the size at 64.
Grid convention
The buffer is row-major: index = row × width + column. Row 0 is the free edge of
a hanging sheet, so the top row is height − 1 and V is flipped to put row 0 at the
bottom of the texture.
Texture coordinates come from the index alone, so rotating or reorienting the sheet never changes them. Click a point.
LeftEdgeThe renderer's view of the buffer
FabricParticleBuffer.fxh is what your draw shader includes. Binding FabricParticles
read-only is the correct, intended use.
ParticleBuffer,
but your MonoGame fork unbinds every compute UAV right after each dispatch, so at draw time nothing
holds it for writing (slide 3.3). What breaks: declaring RWStructuredBuffer in a vertex
shader (the fork throws) or caching the buffer across frames.
FabricEvaluateVertex(vertexId, …) takes two kinds of id:
- below
ParticleCount: a particle, interpolated between the last two steps - at or above it: a seam vertex of a cut mesh, a weighted blend of three particles, or on a strip one particle wide, of two plus an offset across them (chapter 5)
Position, so a pin the host moves between steps moves
at once. The solver also sets a pin's PrevPosition to its Position every
step: a pin carries no motion, into friction against it or into its first step once released.
Between steps
Seam vertex blend
FabricSettings: every knob, two lifetimes
Fabric.Update calls FabricEffect.Apply(Settings) every frame, which checks
every value, clamps it and uploads it, so live knobs take effect on
the next step. A value that is not a finite number throws, naming the setting, before anything is
uploaded, as does a SolverFrequencyHz that is not positive. The sheet fields, the grid,
RestLength and SeedRipple, apply only at Rebuild() rebuild: until then the live sheet keeps the ones it was built with,
which Fabric.WidthInParticles, HeightInParticles and
RestLength report. With AutoRebuild on, Update and
Step rebuild by themselves when any of them, or Fabric's own layout, has
changed; a rebuild starts over, so that suits editing a setup, not animating one.
Rebuild throws for a grid under 2 × 2 or a RestLength that is not finite
and positive; it defaults to 0 on purpose. Damping, BendingPlasticRate and
both frictions are fractions per 1/120 s, rescaled to the step (slide 4.7); read as
coefficients, the two frictions are also the rest hold's static friction (slide 4.8).
Resolution independence
Mass and drag are set per area, not per particle. Each point carries the mass of its own cell and catches the air over its own cell:
ProjectedArea = RestLength²
Refine the same 3 m × 2 m sheet and the totals stay put. Only the particle count, and the cost, change.
Iteration budgets
Contacts and bending are the costly parts of a round, so they run on only some of the RelaxationIterations
rounds. A budget of k is spread evenly: round i solves when ⌊(i+1)k/N⌋ steps past
⌊ik/N⌋.
RelaxationIterations = 0 solves no threads (one pass still
runs, so the colliders and the pins' reach hold), but ContactIterations = 0 and BendingIterations
= 0 mean every round. FabricSettings.EveryRound names that 0, so a
call site can say which it means.
Gold marks the round where contacts are recorded for the next step's friction and rest test: the last one that solves them.
Compression slack and thickness
A thread fully resists stretching but may shrink down to CompressionSlack × RestLength
before it pushes back. That is what lets cloth crumple.
It couples to self-collision. Crush two threads in a row and points two apart sit only 2 ×
slack × RestLength apart. If that is under the collision thickness, threads and contacts
fight forever and a pile never settles:
The default, 0.375, is exactly that minimum at the default thickness. It used to be 0.1, below it: a hanging sheet drapes the same, but a pressed pile now settles to 98–100% resting where it reached 91–95%.
Correction a thread applies, by its length
Wind is a velocity, not a force
Wind is the air's velocity. Drag acts on the cloth's motion relative to it,
scaled by how squarely the panel faces the flow: edge-on catches nothing. That one term is what
makes cloth flutter.
Divide drag by the particle mass and RestLength² cancels, so the acceleration depends
only on the material and the speed. That is why the demo calls 2.5 m/s enough to stream a light
sheet out flat.
Review notes for this layer
Lean, explicit record
Sixty-four bytes, no derivable fields, uint instead of bool, anchor
stored as an index so moving pins need no refresh. A structured buffer has no 16-byte
padding rule, so Pack = 4 with a 64-byte stride is valid.
Independent drift guards
The pass lookup, the size check and the contract version catch different failures, and the error messages say exactly what to do.
Settings were not validated: one NaN poisoned the sheet
Apply checks every setting the solver multiplies by before uploading any: a
non-finite value throws naming it, SolverFrequencyHz must be positive, and
AirDensity and DragCoefficient are clamped at 0.
RestLength was half-live
Rebuild captures it with the grid and Apply runs on the built
value, so the threads, the pins' reach, the rest angles and the cut strokes always share one
spacing.
RestLength "typical" range disagreed with the examples
The XML doc and the Rebuild exception now say 0.03–0.06, as the README and the
demo do.
"0" meant opposite things across iteration knobs
FabricSettings.EveryRound = 0 names the "every round" budget, and the docs use
it.
Rebuild mutated the settings it read
It throws for a grid under 2 × 2, as for a bad RestLength, and no longer writes
the settings.
The contract check is best effort
It walks up six folders from the executable. A shipped game holding only the
.xnb skips it, which is intended and documented. The pass lookup runs
regardless.
Normals were not interpolated between steps
The last round computes the normal of the pose the step ends in, the record keeps the one it
began in packed into four bytes (64-byte record), and FabricEvaluateVertex
blends them by the fraction. The drawn normal no longer trails the drawn position by a step
either.
The default CompressionSlack fought self-collision
It was 0.1, below MinimumCompressionSlackForContacts (0.375 at the default
thickness), so two crushed threads held layers closer than the cloth is thick. It is 0.375
now: a hanging sheet drapes the same, and a pressed pile settles to 98–100% resting instead
of 91–95%.
Every sheet field in the settings, and AutoRebuild
SeedRipple moved from Fabric into FabricSettings,
beside the grid and RestLength. AutoRebuild (off by default)
rebuilds at the next Update or Step when anything
Rebuild reads has changed, and every rebuild raises Fabric.Rebuilt.
TimeStep reports the step the solver really takes, held to 0.0001–0.25 s.
Two kinds of property
Fabric is the CPU model of the sheet. It never draws and never steps on its own; it
builds the particle array, uploads it, and forwards Update to the effect.
Its layout properties (Origin, Orientation, Rotation, PinMode,
PinnedIndices), like the sheet fields in the settings (the grid,
RestLength, SeedRipple), are read only inside Rebuild(). The
constructor builds nothing: Rebuild() does, or the first Update, Step,
Cut or CaptureSurface, so the layout can go in an object initializer. With
FabricSettings.AutoRebuild on, Update and Step also rebuild
whenever any of those inputs has changed.
Rebuild() always starts from whole cloth: it clears every tear and cut
stroke and restarts the solver clock. It checks everything first, so a bad setting throws and leaves
the live sheet running. Every rebuild, however it came, raises Rebuilt, the place to
size a host's buffers; it is raised even if the final Apply fails, since the sheet has
been replaced either way.
RestLength that is not finite and positive, more than 65,535 × 256 particles, a
non-finite SeedRipple or Origin, a Rotation of no
length, a bad setting, a pressure pyramid that cannot fit: each throws_tearState = null, cut strokes, cached meshes and
the tear scratch cleared, torn-triangle count 0; what the sheet was built from, for AutoRebuild
to comparefinallyPlacement: origin, plane, attitude
Originis the middle of the sheet on both axes, so changing resolution or spacing leaves it where you put it.Orientationpicks the plane:Verticalspans X and Y,Horizontalspans X and Z.Rotationrotates the offset from the origin, so the sheet pivots in place.Rebuildnormalizes it, and throws for one of zero length.
Rotation is a starting attitude only. Gravity, wind and colliders stay in world space, so only the pins (brass) hold a tilt. Any angle is safe: a rigid rotation keeps every rest length and fold angle, so the first step has nothing to correct.
SeedRipple: a wave that costs no stretch
A perfectly flat sheet has no preferred side to buckle to, so the build adds a small wave sin(0.7·w)·cos(0.5·h)
out of the plane, sized as a fraction of the spacing: FabricSettings.SeedRipple, 0.05
by default and clamped to MaxSeedRipple (0.5). Raise it for a sheet dropped flat.
A wave makes every thread longer than the flat gap it spans. Instead of starting stretched, the
in-plane spacing shrinks by Pythagoras until the steepest thread is exactly one rest length.
Every other thread starts slightly short, and threads only resist shortening past CompressionSlack,
so that is free.
spacing = √(RestLength² − rise²)
One row, seen edge-on, true scale
Pins and their anchors
At build the pinned set is the union of the PinMode preset and
PinnedIndices; on the live sheet SetPinned(index, bool) changes it.
Interior points are fine.
Every free point then gets its nearest pin and the shortest path to it through the
weave, by a multi-source Dijkstra over the surviving threads. Those go up as the solver's own 8-byte
anchors (Index, MaxDistance), which it copies into
AnchorIndex and MaxAnchorDistance.
- Colour = which pin a point hangs from; number = path length in rest lengths.
- Diagonals count only while shear threads exist (
UseShearingConstraints), or the limit comes out too short and holds the cloth taut. - A piece cut off from every pin gets
−1and falls; a pin gets 0. - A pin change, a cut or a change of
UseShearingConstraintsmarks the anchors stale.FlushAnchorsre-measures them once before the next step, on the CPU, with no readback.
SetPinned does on the live sheet.
Why long-range attachments exist
In a Jacobi round each point only sees its neighbours, so a pin's pull travels one point per round. With 10 rounds a step, a long sheet never fully feels its pin, and it sags like rubber under its own weight.
But no point can ever be further from its pin than the path through the weave. So after the thread corrections, the solver simply clamps each point onto that sphere around its anchor, in one go. It reads the 8-byte anchor, not the 64-byte record, and is switched off while nothing is pinned.
Both chains below run the solver's rules: averaged Jacobi, stiffness 0.9, 10 rounds, 120 Hz. Only the right one clamps.
Folds and who owns them
Bending is measured as the dihedral angle across a hinge: the angle between the two triangles
that share it. Each grid square is split along one diagonal, giving three folds per point, all owned
by the point at the square's lower-left corner. That is why RestAngles is a float3:
X across, Y down, Z diagonal.
The across and down folds reach into the neighbouring square, so they need a row below or a column to the left. Edge points own fewer folds.
The angle is signed: π is flat, one way of closing runs to 0 and the other to 2π, so a crease can't pop through flat and be held on the wrong side.
Rest angles and plasticity
The build measures every fold of the starting shape and stores it as the rest angle, so the seed wave
holds instead of flattening. The C# DihedralAngle must match the shader's exactly, or
the sheet twitches on its first frame.
Once a step, each point re-measures its folds. A fold bent more than
BendingPlasticYieldDegrees away from its rest angle drags the rest angle towards itself
at BendingPlasticRate, a fraction per 1/120 s rescaled to the step. Release it and
it springs back only to the new rest: a crease.
Changing things on a live sheet
Because a particle stores its anchor's index and a path length through the weave, moving pins invalidates nothing. Only changing which points are pinned, or which threads exist, does, and the sheet then re-measures by itself, on the CPU.
| You change… | Call | Cost | Keeps the drape? |
|---|---|---|---|
| a pinned point's position (animated edge) | Effect.UpdateParticles only |
one upload | yes |
any FabricSettings knob except the grid and RestLength
|
nothing, uploaded every frame | free | yes |
UseShearingConstraints mid-run |
nothing: the sheet notices | CPU Dijkstra + 8-byte anchor upload | yes |
| which points are pinned, mid-run | SetPinned(index, bool), any number of times |
one CPU Dijkstra before the next step + anchor upload | yes, released pins drop at rest |
| cuts and tears | Cut / Tear re-measure anchors themselves |
CPU Dijkstra + anchor upload if anything is pinned; no readback | yes |
grid, RestLength, Origin,
Orientation, Rotation, PinMode,
PinnedIndices, SeedRipple |
Rebuild(), or nothing with AutoRebuild on |
full rebuild, then Rebuilt |
no, and mends tears |
PinMode and PinnedIndices still describe only the
next Rebuild(); SetPinned is the live switch. A host that uploads its own
records with UpdateParticles may change pins behind Fabric's back: it notices
by an upload generation, and reads the pins back once, the next time it needs them.
Review notes for this layer
Long-range attachments done properly
Multi-source Dijkstra with a PriorityQueue and stale-entry skipping, distances
through the surviving weave, diagonals only when shear threads exist, and unanchored
points indexing themselves so nothing reads out of bounds. The anchor-as-index design makes
moving pins free.
Seed ripple costs nothing
Shrinking the spacing by the wave's steepest rise is a neat way to start wavy without starting stretched, and rest angles seeded from the built shape keep the wave stable.
No public way to change pins on a live sheet
SetPinned(index, bool) and IsPinned(index) act on the live sheet;
the anchors are re-measured once before the next step, on the CPU, and uploaded alone, with
no readback.
Releasing a moved pin kicked it
CS_Integrate sets a pin's PrevPosition to its Position
every step, so a released pin starts at rest wherever it was moved.
The constructor built and uploaded once for nothing
It builds nothing; Rebuild() or the first Update, Step,
Cut or CaptureSurface does, so the layout can go in an object
initializer.
Apply checked only W × H, so reshaping without Rebuild sheared
the sheet
A 96 × 64 grid set to 64 × 96 passed the check and read every row at the wrong stride. Fabric
now captures the grid at Rebuild, and the solver never reads the settings'
grid, so a new shape waits for the next Rebuild.
Rebuild and SetParticles cleared state before validating
Rebuild checks everything before touching the live sheet, and
SetParticles makes the new buffers before releasing the old, so a bad value
throws and leaves the sheet running.
RefreshAnchors moved the whole sheet twice
Anchors live in their own 8-byte buffer and are re-measured on the CPU: a pin change or a cut uploads 8 bytes a particle and reads nothing back.
"Top" means the last row, in any orientation
On a Horizontal sheet, TopEdge pins the +Z edge, and after a Rotation
it pins whichever edge row height − 1 ended up at. Correct by the grid
convention, and now said in the FabricPinMode docs.
A failed Apply after a rebuild skipped Rebuilt
The live sheet had been replaced, but a host waiting on the event never heard and kept
buffers sized for the old one. Rebuilt is raised in a finally.
SyncPins compared only the particle count
A sheet of another shape with as many particles, given to the effect through SetParticles,
passed for this one. It compares the width and height too.
AutoRebuild rebuilt for a SeedRipple change the clamp ignores
It compares the clamped value, as BuildParticles takes it.
The anchor test without diagonals could not fail
It pins one point, at the top row's middle, and asserts both path lengths: two diagonal steps and one straight against five straight.
What FabricEffect owns
FabricEffect is the GPU side: it loads the compiled solver and takes its own copy of it
(Clone), allocates the sheet's buffers in SetParticles, runs the
fixed-step clock and dispatches the passes. Fabric never touches a buffer directly.
- Records are the full 64-byte particles, twice, for double buffering.
- Position state is a slim
float4copy (xyz; w 0 free, 1 pinned, 2 held), twice. Constraint rounds read eight or more neighbours each, so 16 bytes instead of 64 is most of their bandwidth. - Anchors (8 bytes) and the tear mask (4 bytes) per particle are written only from the CPU; the hold state (4 bytes) and the rest test's running average of the velocity (12 bytes) only by the passes.
- Feature buffers follow their switches. Self-collision brings the spatial hash (a power-of-two table, at least one bucket per particle, min 1,024, max 2²³, 32 slots each), the candidate lists (up to 32 partners) and the contact state; bending brings twelve 8-byte fold shares per particle; pressure brings its pyramid. Each is made when its feature is turned on and released when it is turned off, with a one-element placeholder bound meanwhile.
Two pairs of buffers, two kinds of swap
Every pass reads neighbours, so writing in place would race: a thread could read a neighbour another thread has already moved. Each pass therefore reads one buffer and writes the other.
SwapBuffers()swaps both pairs: after integrate and after the final round, so the records swap exactly twice a step.SwapPositionStateBuffers()swaps only the slim pair: after pressure, which corrects positions only, and between constraint rounds, which move nothing but positions. The records stay bound read-only from integrate to the final round.- The
GatherCandidatesandBendpasses only read positions; they write buffers of their own (candidate lists, fold shares) and swap nothing.
Step through a whole step and watch which physical buffer ends up as ParticleBuffer.
Why drawing the front buffer is safe
It looks like a hazard. The final constraint round writes the new pose into the back buffer
through a UAV, and the swap then promotes that buffer to ParticleBuffer. So the buffer
you draw is the one the last dispatch wrote.
It is safe because your MonoGame fork unbinds every compute UAV right after each dispatch. By the time your vertex shader binds the buffer read-only, nothing holds it for writing.
MonoGame.Framework.dll from your Demo/bin:
GraphicsDevice.PlatformDispatchCompute calls ApplyComputeState → Dispatch
→ UnbindWriteableComputeResources.
The same fork rejects the wrong approach outright. Declaring RWStructuredBuffer in a
vertex shader throws:
Dispatch(_constraintsPass), final round
CSSetUnorderedAccessViews(X) → Dispatch:
X written
UnbindWriteableComputeResources(): X
released
SwapBuffers(): ParticleBuffer =
XFabricParticles = X as an SRV
in the vertex shader ✓
Plumbing: uploads, parameters, dispatch limits
- Uploads write the front buffers only. Every pass writes all of its output before anything
reads it, so the back buffers never show what an upload left there. Scratch arrays are reused,
with no LINQ, and
SetParticlesmakes the new buffers before releasing the old. - An upload stalls far longer than a frame.
SetParticles, and building the pressure pyramid, set_skipNextFrameTime, so the nextUpdateruns exactly one step instead of trying to catch up on the stall. One rather than none, so normals exist before the first draw.UpdateParticlesleaves the clock alone: a host animating its pins uploads every frame. - Each sheet has its own effect.
ContentManager.Loadhands every caller one shared instance, so the constructor takes a copy withClone().Disposereleases the copy with every buffer, and any call after it throwsObjectDisposedException. - Parameters are looked up once and cached, including absent ones: the compiler strips
uniforms the shader never reads, and setting one of those becomes a no-op rather than a crash.
Passes are looked up once too, in the constructor, since
Stepdispatches up to ~100 times a frame. - There is no unsigned setter, so
SetUIntpasses the same bits as anint. - A dispatch over 65,535 groups throws. On the GPU it would fail silently, as cloth frozen from some row down.
- Time is summed in
double: a float adding 1/120 s steps drifts by percents after a few hours.
Drawing between steps
The solver steps at 120 Hz; the screen may not. Drawn at the latest step, motion jerks: some frames
advance two steps, some none. InterpolationFraction draws a blend of the last two poses
instead.
The trick is a constant lag. The fraction is chosen so the drawn pose is always
drawLag behind the wall clock:
⇒ drawn time = wall time − drawLag
drawLag follows the accumulator's peak over the last 0.5–1 s: it rises at once, sheds at
1% of real time, and never exceeds one step. In step with the solver (60 fps) the peak is 0, so it
costs nothing.
Normals blend by the same fraction. The last round of each step writes the normal of the pose the step ends in, and keeps the one it began in, packed into four bytes, so shading turns as smoothly as the cloth moves.
Readbacks and diagnostics
Reading GPU memory on the CPU makes the CPU wait until the GPU has finished everything queued before it, then the GPU sits idle while the CPU prepares the next frame. That bubble is the cost, not the bytes copied.
- Counters are 64-bit running totals, never reset: a low and a high word, with the carry added by a second atomic only when the low word wraps. The CPU differences two samples. A 32-bit tally of resting particle-steps wrapped in about 34 s on a 1024² sheet.
- The resting and held fractions divide by the unpinned count, so their windows restart when the pin count changes, and only then: a host uploading every frame with the same pins keeps its window, which used to restart at every upload and never close.
- Each compute group tallies in
groupsharedmemory and adds once per group, not one global atomic per particle. - One fetch per step serves every sampler:
ReadCounterscaches byTotalStepCount.
| Call | Reads | Tells you |
|---|---|---|
ReadBack() |
all records | the particle array, for the Diagnostics checks |
SampleRestingFraction() |
15 counter words | share of unpinned cloth inside the rest deadband |
SampleHeldFraction() |
same fetch | share held exactly still by the rest hold: the stricter figure, 1 for a pile at rest |
SampleSpatialHashOverflow() |
same fetch | contacts never seen because a bucket was full, or a candidate list (DroppedCandidatesPerStep,
PeakCandidates)
|
SampleWorstStepMotion() |
same fetch | fastest step in thicknesses: past 1, layers can cross unseen |
SampleCoincidentContacts() |
same fetch | contacts with no history to orient them either, split by index;
needs FABRIC_COUNT_COINCIDENT |
Review notes for this layer
Two sheets from one ContentManager shared one solver Effect
Each FabricEffect now takes its own copy of the loaded Effect with
Clone(); Shader is that copy, disposed with it, so no sheet can
dispatch against another's buffers.
"Swaps on every pass… about half the time" was not quite what happens
The README and the ParticleBuffer docs say to bind it every frame: SetParticles
replaces the buffers, and which of the two holds the latest step is the solver's own
business. Since ApplyPressure writes positions only, the records in fact swap
exactly twice a step, pressure or not.
Cumulative counters were 32-bit but exposed as long
The totals are 64-bit on the GPU, a low and a high word with a carry, in 15 counter slots.
The resting counter wrapped in about 34 s on a 1024² sheet
It is one of those 64-bit totals now, so SampleRestingFraction stays right
however long the window.
The pressure pyramid was never released
Every feature buffer is made when its feature is turned on and released when it is turned off, with a placeholder bound meanwhile.
A failed pyramid build left Apply half done
Apply makes every buffer it needs before it changes any state, so an
out-of-memory failure leaves the last settings in force.
NaN elapsed time froze the clock and the draw lag
Update counts a NaN frame time as none, and SetParticles resets the
draw lag with the clock.
Contact state went stale on toggles, zero iterations and unpinning
It is zeroed when recording resumes, UseContactFriction stays off while no round
records, and a pin writes zero contact state, so a released pin starts clean.
RelaxationIterations = 0 disabled the colliders and the pins' reach
One pass still runs without threads, so the colliders and the long-range attachments hold.
SampleRestingFraction froze for a host uploading every frame
Every UpdateParticles restarted its window, so a host animating its pins never
saw a new figure. The window restarts only when the pin count changes, which is when its
divisor does.
SampleHeldFraction
How much of the unpinned cloth the rest hold keeps exactly still: a 64-bit total in slots 13–14, sharing the resting fraction's fetch. The demo shows it in its title, four times a second.
Careful clock and diagnostics engineering
Double-precision time, step tolerance against float rounding, skipping a stalled frame's time, a draw lag that rises at once and sheds slowly, per-group counter reduction, one counter fetch per step, sampling windows that restart when their source was switched off.
Slim position state
Running the constraint rounds on 16-byte positions and writing the full record only on the last round is the right bandwidth trade.
Eight kernels, one thread per particle
FabricSimulation.fxh holds every compute kernel; FabricCompute.fx only
lists them as eight passes. Each is dispatched one-dimensionally in groups of 256 threads, and
thread i owns particle i.
The rule that shapes everything: gather, never scatter. A thread computes a correction only for its own particle, by reading its neighbours. Nothing writes another particle's position, so there are no atomics on positions and no races. The price is that a shared quantity is evaluated by each of its particles separately. Threads and contacts still are; folds, the costliest, are solved once by their owner in a pass of their own, which writes every particle's share for the round to gather.
CS_Integrate |
per particle | pins from the anchors, normal, plasticity, friction, forces, rest test and hold, Verlet |
CS_ReducePressure |
per pyramid cell | average 4 cells below |
CS_ApplyPressure |
per particle | added-mass correction along the normal, to the positions only |
CS_ClearSpatialHash |
per bucket | zero the counts |
CS_BuildSpatialHash |
per particle | file itself under its cell |
CS_GatherCandidates |
per particle | its contact partners, once a step, from the cells its radius reaches |
CS_Bend |
per particle | its three folds, solved once; twelve shares written |
CS_Constraints |
per particle | threads, fold shares, candidate contacts, anchor, colliders; on the last round, the hold's snap-back |
What one thread group touches
Group g covers particles 256g … 256g+255 in row-major order (red). Its threads read neighbours one row up and down (blue), which sit a whole row away in memory.
Inside CS_Integrate
One step of one particle, in the order the kernel runs it. Click a stage to highlight its lines.
The whole group shares four groupshared
tallies for the diagnostics (resting, held, the peak step, fast steps) and adds them to the global
counters once, after a barrier. That is also why the kernel has no early return: every thread must
reach the barrier.
The rest deadband
Verlet turns every correction into velocity. Constraints that never quite agree leave a little noise each step, Verlet carries it into the next, and settled cloth twitches forever.
Below RestSpeedThreshold the carried motion is discarded: not damped, which would
slow everything, and not frozen into a pin, which would make frozen points fight their neighbours.
(The rest hold, slide 4.8, keeps settled cloth still another way.)
But a point gently starting to move is slow too. The drive test spares it: if its velocity points
along its acceleration by more than RestDriveFraction of one step's worth, it is being
driven, not resting. Points touching a collider or other cloth skip the drive test: friction acts on
carried motion, not on the force, so cloth creeping down a sphere would otherwise never come to
rest.
A slow swing is slow too, and it moves across the force, so the drive test cannot tell it from noise: a sheet settling to a new lean as a gust died hung a metre short for tens of seconds. Noise is as likely one way as the other and averages away; a swing does not. So each particle keeps a running average of its velocity over about 1/15 s, capped at twice the threshold, and motion averaging above a quarter of the threshold is kept, however slow, on a point touching nothing. One that touches something is stopped all the same, as friction stops slow sliding: a pile's compaction creep is exactly that, unless a push past what friction and the hold take is driving it along its support (slide 4.8), when it slides instead.
The deadband only works while solver noise stays under the threshold: push the noise past RestSpeedThreshold
and the wander comes back.
One round: gather, then average
In a Jacobi round every correction a point gathers was computed against the same stale positions. Add up eight thread corrections and the point overshoots up to eightfold, its neighbours do the same, and the sheet shakes itself apart. Averaging keeps each round a safe partial step.
The solver averages three groups separately: threads, folds and contacts. Averaged together, twelve soft fold corrections would drown the few strong thread ones, and one contact would average away among eight threads exactly when it matters.
Twelve folds per particle, each solved once
Bending is the Position Based Dynamics dihedral constraint (Müller et al.). Its correction for each of a fold's four particles is the angle's gradient, scaled by the angle error. The gradients blow up as a fold flattens, so they are pre-multiplied by sin θ, and the sign flips past π because the angle is signed.
A particle is the hinge of six folds and a far corner of six more, owned by up to six different
cells. Each particle solving all twelve itself, as the rounds used to, solved every fold four times
over. Now CS_Bend runs before each bending round: each owner solves its three folds
once (SolveDihedral, all four corrections at a time), reading the six positions they
share once rather than twelve, and writes them as twelve half-precision shares. The round gathers
the particle's twelve through BendingStencil's (owner offset, kind, role) entries.
Click a particle.
cs_5_0, the constraint kernel went from about 2,135 instruction slots to about 680,
and is about 673 now, some 150 of them the end-of-step normal that only the last round runs; CS_Bend
is about 486, dispatched only on bending rounds. Those are instruction counts. Timed since on a GPU,
the latest round of kernel changes, these six reads among them, ran equal at 96 × 64 and 15–20%
faster per step at 192 × 128 and 384 × 256.
Self-collision through a spatial hash
- Space is cut into cubes 1.5 thicknesses wide, the candidate radius, so anything within that radius of a point lies in the 27 cubes around it.
- Cubes are hashed (Teschner et al. primes) into a fixed power-of-two table: no world bounds, no resizing. Unrelated cubes may share a bucket; the gather re-checks each entry's own cube, so an aliased bucket costs a rejected test and never lists anyone twice.
- Each bucket holds 32 entries. An overflowing particle is dropped for that step and counted, so
SampleSpatialHashOverflowcan report contacts never seen. It held 16, but a crushed pile wants 29–40: its contact set then changed from step to step, which kept it from ever coming to rest. - Once a step,
CS_GatherCandidateskeeps each free or held particle's partners within the candidate radius, up to 32. It skips the cells its radius cannot reach, about a quarter of the 27, and every contact round then tests only that list, instead of searching again. A full list is counted too. - The lists are laid out by rank: a count per particle, then every particle's first partner, then every second, so a wave reading its particles' k-th partners reads consecutive words.
- The 8 weave neighbours are skipped, since threads handle them, unless the thread between them is torn: then they are two lips of a tear and must collide. The test is an index offset and one mask word, with no division.
This 2D version uses 9 cells instead of 27, and a thickness of two thirds of a cell. Click a point to gather its candidates.
Colliders, friction and the step rate
Colliders are projected every round: a point inside the sphere or under the floor is moved to
the surface. Projection is idempotent, so repeating it is safe. Friction runs once a step, in
CS_Integrate, by removing a fraction of the tangential carried motion; applied per
round it would compound and fight the solver. Self-friction uses the previous step's recorded
contacts and removes sliding relative to the partner, so a heap moving as one piece is not
braked.
The same pass reports what carries the point, for the rest hold's static friction (slide 4.8): the summed normals of the sphere or floor where they face against gravity, and of the cloth it rests on, counted per partner by the recording round; pinched between layers, straight against gravity. With it comes the strongest of their static grips: the friction settings themselves, not the per-step rates the sliding friction above uses.
Damping, ColliderFriction, SelfCollisionFriction and BendingPlasticRate
are stated per 1/120 s, and Apply rescales them to the step, so the same numbers
mean the same at any SolverFrequencyHz. The carried motion is rescaled too, and with it
the partner motion friction compares against, so even a live change of rate changes cost and
stability, not how the cloth moves.
DisplacementScale = dt / previous dt
A point sliding on the floor at 2 m/s
Holding settled cloth still
The deadband discards carried motion, but a resting point still gets gravity's push every step, 0.68 mm at 120 Hz, and an approximate push back from what it rests on. The residuals creep. A sheet dropped on the floor twitched at about 170 µm a step, with single-step pops of 100–460 mm, and its heap spread flat over a minute.
UseRestHold adds what friction adds. A point that has rested for
RestHoldDelay (0.05 s, and never under two steps, so a bounce's apex never counts)
and is supported, touching the floor, a collider or other cloth, or joined by a whole thread
to a held point, is held. It still runs every round with every force, except that a push it
can ignore is not applied to it. At the end of the step a net move within its wake was noise,
or a pull it can ignore, and snaps back to where the step began; a larger pull, by a thread or a
contact, frees it, and so does a larger push that actually moved it: braced by its neighbours, it
stays held.
- Wake distance =
RestHoldWakeFraction×RestSpeedThreshold/ 120 Hz = 0.5 × 0.06 m/s / 120 Hz = 0.25 mm, the same at any rate. The push the hold ignores is the same fraction ofRestSpeedThresholdper 1/120 s: 3.6 m/s², at any rate. A point hanging on held cloth, whose only push is gravity braced by its threads, takes that push limit as its wake instead, never under an eighth of the wake distance. - Neighbours treat a held point like any other, never as a pin: full corrections against a frozen point overshoot, and wake the pile.
- A resting point that something carries gets no push into its carrier, which would only project it back, approximately, while the pile sank into itself. Of the rest, static friction holds what lies within its cone; what is left past the limit drives the point, which slides under the kinetic friction rather than creeping by one push a step.
- A hanging sheet touches nothing and is never held, so it swings and settles exactly as before.
Static friction reads the carrier's friction setting as a coefficient, μ = f / (1 − f): 0 holds nothing, 1 anything, and 0.35 holds about 28°. It reads the setting itself, uploaded beside the per-step rate the sliding friction uses, because a cone is an angle and must not change with the step; it used to read the per-step rate, which held 13.5° at 240 Hz and 54° at 60 Hz. The step rate below changes the push per step, not the cone, the limit or the wake.
Measured on the 96 × 64 sheet dropped on the floor: 99.7–99.9% of the pile bitwise still, with no drift; a pressed sheet, a sphere pushed through the pile and gravity turned sideways all re-freeze, and the cost is within noise of the hold being off. The price is that cloth lying on something ignores pushes under 3.6 m/s², a breeze under about 1 m/s, and a collider sinks 0.25 mm into it before it yields, at any step rate. Past about 300 Hz a step's own residual meets those distances and the hold errs toward holding (slide 4.10).
Static friction on a slope
Aerodynamic pressure as added mass
Per-particle drag treats every point as alone in the air, so a falling sheet stays flat. Real air under the middle of a sheet has further to escape than air at the rim, so the middle is held back more and the sheet domes, like a parachute.
The solver models that as added mass: air dragged along with the cloth. Broad motions drag more air than fine wrinkles. So each particle's normal acceleration is split into bands with a pyramid (each level averages 2×2 cells of the one below, inside zero padding), and each band is divided by its own effective mass:
Dividing can only shrink a term, so the model cannot blow up however heavy the air. Near the rim, coarse cells average in the still-air padding, so the rim keeps more of its acceleration than the middle. This 1D slice through a falling sheet shows it.
The pyramid is fed the push each particle actually got. It used to be fed the raw acceleration,
gravity included, even where the rest hold had taken gravity's push away, so the air refunded a push
never applied: a pile under pressure hovered, 86% held after 20 s, where it is 99% now. CS_ApplyPressure
corrects the positions only; the records keep CS_Integrate's for the rounds to read.
That needs padding. The base is the next power of two at least twice the sheet's longer side, where that fits in 4,096, so every edge keeps a wide margin of still air. It used to be the smallest square that held the sheet: a 64-wide sheet filled it, the coarse levels saw no rim, and it never domed. Try 64 points with the old base.
Review notes for this layer
Per-step rates made behaviour depend on SolverFrequencyHz
Apply rescales Damping, ColliderFriction, SelfCollisionFriction
and BendingPlasticRate per step, 1 − (1 − rate)^(120 · dt), so the
documented values mean "per 1/120 s" at any rate. Stiffness is per round and
rightly left alone.
A live SolverFrequencyHz change rescaled velocities
Verlet's gap was measured over the old step. DisplacementScale = dt / previous
dt rescales it, and the partner motion friction compares it with, so the cloth keeps
its speed.
Degenerate normals fell back to a fixed world −Z
When no two surviving threads meet at a right angle, ComputeNormal keeps last
step's normal, turned square to the strand; built particles start with the flat sheet's
facing, so −Z is left only for a host's own particles with no normal at all.
Coincident contacts picked a side by index
They are pushed apart along the difference of their PrevPositions first; the
index rule runs only when that coincides too, and only that case is counted.
Needle tests used <, so coincident points gave NaN
DihedralAngle (C# and HLSL) and SolveDihedral test with
≤: a fold with two corners at one point is flat, not 0 / 0.
The pressure pyramid had no still-air margin on power-of-two sheets
Its base is the next power of two at least twice the longer side where that fits, so a 64 × 64 sheet domes; up to 4,096 per side, checked before the sheet goes live.
Phantom friction against moved pins
A moved pin's motion read as sliding to the cloth touching it. A pin's
PrevPosition is now set to its Position every step, so it carries
none.
Piles never came to rest
The deadband drops carried motion, not the push: every resting point still got gravity's and an approximate push back, and the residuals crept. The 16-entry buckets overflowed in the pile too (it wanted 29–40), so its contact set changed every step. A dropped sheet twitched at about 170 µm a step and its heap spread flat over a minute. With the rest hold and room for 32: 99.7–99.9% of the pile bitwise still, 1–6 deep penetrations against 1–25, at a cost within noise (slide 4.8).
A slow swing froze a metre short
A sheet settling to a new lean as a gust died moves across the force, so the drive test read it as noise. The running average keeps slow motion that persists, on cloth touching nothing: the breeze test settles 7 cm from the no-deadband truth instead of a metre (slide 4.3).
Resting cloth ignored the wind and slopes
A carried resting point first lost its whole push, so it could neither slide nor blow away whatever the friction. Now it loses only the part into its support, and static friction holds the rest within its cone: a sheet dropped off-centre on a ball slides off at friction 0 and stays at 0.35, and a held pile in a 6 m/s gale blows along like free cloth, then re-freezes.
The air refunded a push never applied
The pressure pyramid was fed gravity even where the carrier had taken it, so a pile under aerodynamic pressure hovered, 86% held after 20 s. It is fed the push actually applied, and the pile is 99% held (slide 4.9).
Faster passes, timed on a GPU
CS_Bend reads the six positions its folds share once instead of twelve; the
integrate and constraint passes read each weave neighbour once and hand it to the normal;
ApplyPressure writes positions only; the candidate lists are laid out by rank,
and the gather skips cells beyond its radius. Equal at 96 × 64, 15–20% faster per step at
192 × 128 and 384 × 256. Bit-identical for 2,400 steps with bending off; with it, fxc
contracts the bend pass's multiply-adds another way, so it rounds differently.
The static-friction cone followed the step rate
holdable = −into · grip / (1 − grip) took grip from the per-step
ColliderFriction and SelfCollisionFriction, which
Apply rescales with SolverFrequencyHz, so 0.35 held about 28° at
120 Hz but 54° at 60 Hz and 13.5° at 240 Hz. ColliderStaticGrip
and SelfCollisionStaticGrip now carry the settings themselves. On a GPU, with
the wake distance off so the cone alone decides, a sheet on a 20° slope used to creep at 240 Hz
and one on 35° to hold at 60 Hz; now 20° holds and 35° gives at every rate. At 120 Hz
the old per-step value was the setting to within one float ulp (0.35000002 against 0.35), so
a run is bit-identical until the cone first engages, parts by microns, and settles the same:
no change in behaviour at the default rate.
Memory locality of the 1D dispatch
Not changed. Groups cover runs of a row-major grid, so up/down neighbours are a full row away. If profiling ever shows the constraint pass memory-bound on wide sheets, 2D thread groups (16×16 tiles) or a tiled particle order would improve cache reuse. That needs a GPU to measure on first; this is an option, not a defect.
The rest rules' push thresholds followed the step rate
Two tests weighed a push, an acceleration × dt², against a distance made from a speed, RestSpeedThreshold
× dt, so what resting cloth ignored went as 1 / dt: a sheet on a 50° slope crept at 120 Hz
and held at 240, and the sheet dropped off-centre on a ball slid off in 5 s at 120 Hz,
15 s at 240 and never at 480. Now pushes are accelerations and pulls distances, each
stated at the reference rate: the hold ignores a push under 3.6 m/s² and does not apply
it; a larger push frees a held point only if it moved it (the push's length rides in the
hold word for the last round to weigh), so a point braced by its neighbours stays held; a
touching point moving with the push left to it is driven, not resting, so it slides rather
than creeps; the wake is a fixed 0.25 mm for a touching point and the push limit for
one hanging on held cloth, whose gravity residual follows the push. Measured: the 50° slope
slides at every rate, the ball slides off in 5.0–5.5 s from 60 to 240 Hz, the
dropped and released piles hold as before at 120 Hz (over ten runs each, 80–99.5% held
under the old rules and 84.5–99.5% under the new, 93% on average for both), the pressed,
plowed, tilted and draped sheets at 98.6–99.9% with the same re-freeze times, and every
scenario at 99.2–99.8% at 240 Hz; the swing is bit-identical, and the cost is within a
few percent (the two kernels grew 30 and 13 instruction slots).
Where the step rate still shows
A step's own residual, some 60 µm in a pile, does not shrink with the step. Past about 300 Hz the push limit and the per-step motion of sliding cloth fall under it, and the hold errs toward holding: the ball sheet stays put at 480 Hz, and the dropped pile holds 95–97% there against 99% at 240. A wake that shrank with the step instead lost the pile at 240 Hz (still 50–72%). Below 120 Hz the drop tunnels (hundreds of deep penetrations at 60 Hz), the documented limit of the contact tests. The kinetic friction is viscous, with a first-order error in the step: a sheet sliding down a 50° slope goes 211 / 173 / 155 / 147 mm/s at 60 / 120 / 240 / 480 Hz. And the constraints' stiffness is per round, so cloth is stiffer per second at a higher rate: a hanging sheet with its foot on the floor settles at 120 Hz but is still moving at 240 (80–94% held under the old rules, 85–91% under the new), the rest rules playing no part.
Numerics written by someone who has been bitten
Separate averages for threads, folds and contacts; gradients pre-multiplied by sin θ;
degeneracy guards relative to the shapes' own size; the finite check done on exponent bits
because fxc folds isfinite away; [branch] discipline so whole
cloth never pays for tear masks; added mass applied by division so it cannot diverge;
colliders idempotent per round, friction once per step.
The rest deadband
Discarding sub-threshold carried motion, with a drive test that keeps gently falling points awake and a contact exception, is a clean answer to Verlet's twitching that avoids both global damping and sleeping. The hold on top adds static friction without making any point a pin to its neighbours, and a hanging sheet never meets it.
One owner per thread
The weave is implicit in the grid, so damage is a set of flags. Each particle carries one
uint of FabricTearFlags, and every thread has exactly one owner, so
both of its ends agree whether it is torn. A point owns the threads to its right and above it, and
both diagonals of the square to its upper right.
Three more bits mark dead folds: a fold whose two triangles lost any of their five threads. The CPU precomputes them after every cut, so bending checks one bit instead of five.
The GPU never sees the ownership. FabricEffect.BuildTearMask expands the flags on the
CPU into one word per particle: its eight links, torn or not, in bits 0–7, and the dead bits of the
three folds it owns in bits 8–10. A pass reads that one word instead of up to nine.
Click threads to tear them. Click a point to read both of its words.
A stroke severs threads
Cut(start, end) takes metres on the flat sheet, because damage belongs to the
weave, not to wherever the cloth hangs now. It checks every point first, converts to grid units in
double precision and clips each segment (Liang–Barsky) to two cells past the sheet. Then it visits
only the squares along the segment, row by row: a thread is severed when the stroke properly crosses
it. That finds exactly the threads the old bounding-box scan found, as a test checks against brute
force, at the cost of the segment's length rather than its box's area.
- The endpoints are ordered first, so a stroke drawn either way severs the same threads.
- A point exactly on the stroke's line counts as left of it. A stroke running exactly along a row of points therefore severs the threads on one side, deterministically, and never a thread lying on the line itself.
- Whole cloth severs into a scratch array, made once and kept, so a miss allocates nothing after the first; the first hit adopts it as the tear state.
- Severing, recording and applying sit in a
finally, so a throw part way can never leave the GPU mask, the dead folds orTriangleCountstale.
Drag the two handles. The holes are what the plain triangle list draws: jagged at grid scale.
What one cut sets off
A cut acts on the live sheet the moment it is called; the drape is kept. ApplyTears is
everything downstream of changed damage, run once per call, so a polyline of a hundred strokes pays
for it once.
On the GPU the tear mask is off until the first tear (UseTearing), so whole cloth never
pays for it. Once on:
- a torn thread pulls on nobody: that absence is the tear;
- normals skip torn links, so each lip lights from its own cloth;
- the two lips are no longer weave neighbours, so they collide as ordinary cloth;
- dead folds stop bending, and stop yielding plastically;
- anchors are re-measured through what remains, so a piece cut free of every pin falls.
Rebuild() always starts from whole cloth. To open a scene pre-torn, cut
right after building. ClearTears() mends in place: dead folds revive at the angles they
died with, so drifted lips snap together with a visible twitch.
finally, if anything severed, every segment of the cut is recorded,
consecutive collinear ones mergedTriangleCount is a cached
number, not a per-frame scanBuildTearMask expands the
flags into one word per particle; one upload of N words; switches UseTearing on
CreateTriangleIndices()
(jagged) or CreateCutMesh() (clean lips), then draw the new count. ApplyTears
dropped the cached ones, so each is built once for this damage, and
CaptureSurface picks against the very mesh the host drew.Clean lips: the cut mesh
The simulation can only sever whole threads, so a hole drawn from the plain list is a staircase.
CreateCutMesh() keeps the whole triangles and replaces each damaged one with the faces
of its cut graph: every stroke near it, with any number of joints, crossings, T-junctions and
overlapping re-cuts, split into pieces that are then ear-clipped. This is flat 2D geometry,
computed once per change of damage, never per frame: the same instance comes back until the next
cut, tear, mend or Rebuild, so treat it as read-only.
A piece's corner that lies on the lip is not a particle. It becomes a seam vertex: a weighted blend of three nearby particles on its own side of the cut (its carriers), chosen so none is reached across the stroke and all hang together through the surviving weave. As the rip opens, each lip rides its own cloth. On a strip one particle wide, where no three span any area, two carriers along it and an offset across it, along the cloth's normal, keep its full width.
Open the rip. Click a seam vertex to see its carriers.
The awkward cases
FabricCutMesh.cs is nearly 3,000 lines because a cut is rarely one clean line through
one triangle. Each dead triangle builds a cut graph from every stroke near it and draws its faces. A
seam vertex is identified by its exact flat position plus a signature hashing which side of
every stroke through it its piece lies on, so copies of one lip point weld into one vertex exactly
when they belong to the same cloth. Fuzzed over 26,000 random sheets, it drew no bridging, cracks,
winding or weight errors; the only holes left are scraps holding fewer than two particles.
Cutting what the player sees
Crumpled cloth no longer lies where it was built, so a knife cuts against the sheet itself. CaptureSurface
reads the pose back once, at the press. A FabricStroke over it records each ray's nearest
layer, or its miss, as the drag goes, and the preview is drawn from those hits. On release, Cut(stroke)
joins the samples in flat-sheet coordinates without picking again; Cut(rays) does the
same from a list.
When the knife slides off one layer onto another, two hits can be close in space but far apart across the cloth. Joining them would cut a straight line through cloth the knife never touched, so the stroke breaks when
A miss is different. Across one, two samples join only if the flat path between them crosses a recorded cut or a torn thread: the knife passed over an open rip. A run that ends or starts at a miss reaches on to a recorded cut, or half a cell past the sheet's edge, when that lies within its last sample spacing plus a cell, so no threads are left holding the piece on.
The side view below is a Z-folded sheet. The strip underneath is the same sheet unfolded: what Cut
receives.
Review notes for this layer
The README's scissors example cut between layers
It now keeps one polyline per layer, matched from ray to ray by depth order, and cuts each (slide 5.6, third mode, shows the old way).
Cut(ReadOnlySpan<Vector2>) was not exception-safe
Every point is checked before anything is cut, and severing, recording and
ApplyTears sit in a finally.
Seam identity held at most three strokes per point
The region signature hashes every (stroke, side) pair through the point, with no limit.
Slow knife drags drew bridging triangles
Every segment of a cut that severed anything is recorded, joints and all, so a drag sampled far finer than the grid draws one lip.
Ray cuts could not cross or reach an existing cut
Across a miss, samples join when the flat path crosses a cut or a torn thread; a run ending or starting at a miss reaches on to a cut, or past the sheet's edge, within its last spacing plus a cell.
Strokes stored unclipped broke the mesh far off the sheet
Segments are clipped (Liang–Barsky, in double) to two cells past the sheet before they are severed or stored.
Cuts through lattice points left cracks, and one-cell strips vanished
A particle on a cut belongs to the side its surviving threads hold, and shares that side's lip; a one-particle strip is drawn full width with two-carrier seam vertices.
No check that a surface matched the sheet
A FabricSurface carries its owner and build generation, and Cut
throws for one from another sheet or from before the last Rebuild.
A ray through a shared edge hit both triangles
Picking now decides edges in double precision and keeps one hit per layer, through shared edges, corners and the closed lips of a cut.
Strokes accumulate for the life of the damage
Consecutive collinear segments now merge, so a straight drag stays one stroke however finely
it was sampled, and strokes are filed along their path; overlapping re-cuts regroup in one
pass rather than a pass per group. A wandering drag still adds a stroke per sample until
Rebuild or ClearTears.
One mesh per change of damage
CreateCutMesh and CreateTriangleIndices keep their result until the
damage changes, so CaptureSurface reuses what the host drew instead of building
it again. Index lists are allocated at their size, a sheet torn without strokes skips the
stroke grid, and a surface is checked before any ray is picked.
Damage model and its mirrors
One owner per thread, kept on the CPU (DirectLink) and expanded into each
particle's mask by BuildTearMask, which a test checks against
DirectLink on every link; dead folds precomputed on the CPU. I checked all
fifteen dead-fold rules against the bending stencil: each lists exactly the hinge and the
four outer threads of its two triangles.
A cut mesh that fails safe
Every uncertain case falls back to something honest: a tip inside draws closed, damage with no stroke stays a jagged hole, a piece whose supports no longer hang together is not drawn rather than stretched, and carriers are found by walking the surviving weave rather than trusting side tests alone.
Which point of the weave is under the cursor?
Once cloth has crumpled, only its current triangles can answer that. CaptureSurface()
reads the sheet back once and picks against the cut mesh, seam vertices included: the very
one CreateCutMesh returns, cached until the damage changes, so what can be picked is
exactly what is drawn. FabricSurface.Raycast then answers any number of rays against
that pose, for the whole gesture.
- A box test first, so a ray nowhere near the cloth costs one check, the common case while previewing.
- Then a uniform grid, walked cell by cell along the ray (a 3D DDA, in double precision), testing only the triangles filed in the cells the ray crosses. Under 64 triangles it tests them one by one.
- Each test is two-sided Möller–Trumbore, because a crumpled sheet shows back faces everywhere: floats to reject, doubles to decide, so a ray down a shared edge reports its layer once.
- Hits are insertion-sorted nearest first into a span the caller provides: no allocation per ray.
- The answer the host cannot compute itself: the hit's barycentric weights blend the three
corners' flat-sheet coordinates into a flat-sheet point, ready for
Cut.
On a 512² sheet, 520,000 triangles, a nearest-layer ray takes about 1–8 µs, against 3.4–6.5 ms before; filing the grid takes about 35 ms per capture. Move over the crumpled patch on the left; the right shows where that point lives on the flat sheet.
Two measurements a screenshot can't give you
Both take the array from one ReadBack(), re-derive everything from positions, and
allocate freely: they are for debugging, not frame work. Pass CopyTearState() on a torn
sheet so a rip's lips count as touching cloth, and dead folds are skipped. Both check that the grid
and the tear state fit the array, and throw if not.
PenetrationCheck counts pairs of non-neighbouring points closer than the cloth is thick, and
separately those overlapping by more than a quarter of it: one layer through another. It
deliberately builds its own exact hash with unbounded buckets. A check that read the solver's
buckets would miss exactly the pairs the solver missed when a bucket overflowed. Give it the
thickness the solver runs with, SelfCollisionThicknessRatio (at least 0.05) × Fabric.RestLength,
the spacing as built; a thickness that is not a positive number counts nothing.
CreaseCheck compares each fold's current angle with its rest angle. That separates cloth folded because something presses on it (rest flat) from cloth folded because it has creased (rest bent).
DemoGame: a reference host
Demo/ is a hanging 96 × 64 sheet you can slash. It uses every public path a host needs,
so it doubles as an integration test beside the unit tests: a custom solver effect, the cut mesh,
ray cutting with a live preview, random rips, mending, rebuilding, letting the top edge go and
pinning it again (P, SetPinned), and gusting wind.
- One
CaptureSurfaceper drag, at the press, held by aFabricStroke. Each frame's ray is picked once, for the preview, and the cut on release is made from those same samples, so it lands where the line was drawn. RefreshTopology()is the single path after any damage: it drops a drag in progress, takes the cut mesh and grows the index, vertex and seam buffers only when they are too small. Every rebuild, R's or one a setting causes, reaches it throughFabric.Rebuilt.- The seam buffer is never empty, because the shader declares it and a real resource must sit behind the binding.
- It binds the particle buffer and the grid as built (
Fabric.WidthInParticles,HeightInParticles) every frame, and draws the cut mesh's triangle count, notFabric.TriangleCount. - The window title shows
SampleHeldFractionfour times a second, as a GPU stall should be sampled. W cycles a breeze, a gale and still air;--calmon the command line starts in still air.
BeginStroke()new FabricStroke(CaptureSurface()): one
readback of the pose
CursorRay(): unproject near and far_stroke.Add(ray, out hit): picked once →
preview line
Cut(_stroke): joins the samples, breaks at
folds, severs
ApplyTears: upload the mask; CPU Dijkstra +
upload for anchors
RefreshTopology() →
CreateCutMesh(), resize buffers
FabricEvaluateVertex over particles +
seams
The demo's two shaders
Cloth.fx draws. It fetches every vertex, particle or seam, through
FabricEvaluateVertex, flips the solver's normal towards the camera because culling is
off, and paints a 24 × 16 check pattern in flat-sheet texture coordinates, so a rip visibly parts
the cloth's face and not only its outline.
ClothSolver.fx simulates. It wraps the package's solver with a wind function: it declares
GustBands, defines FABRIC_WIND_AT, includes FabricCompute.fx,
then defines the function where Wind and FabricTime are in scope. Bands of
stronger wind about 4 m apart drift across the sheet, scaled by Wind, so still air
stays still. A non-finite answer would fall back to Wind.
Wind speed across the sheet, live
Where every file ends up
The library project sits at the repository root and excludes Demo/** and
Tests/** from its globs. Packing maps each source to a package path; the package's
.targets then maps it into the host. The demo, which references the project rather than
the package, stands in for the targets with its own copy step.
| Repository | In the .nupkg | In the host project | Compiled to |
|---|---|---|---|
Effects/FabricCompute.fx |
contentSource/Effects/Fabric/ |
Content/Effects/Fabric/ |
FabricCompute.xnb |
Effects/*.fxh (3) |
contentSource/Effects/Fabric/ |
Content/Effects/Fabric/ |
included by your shader and the solver |
contentSource/…Simulator.mgcb |
contentSource/ |
Content/BorrowedTorch.FabricSimulator.mgcb |
globbed by the builder task |
buildTransitive/…Simulator.targets |
buildTransitive/ |
imported for direct and transitive references | BTFS0001, copy, BTFS0002, removal target |
build/…Simulator.targets |
build/ |
imported by clients that predate buildTransitive |
imports the one above |
Simulation/*.cs, Diagnostics/*.cs |
lib/ + XML docs + .snupkg |
referenced | Source Link for stepping in |
README.md, logo.png |
package root | nuget.org page | |
Demo/ |
not packed (IsPackable=false) |
DemoCopyFabricShaderSource copies
Effects/* to its Content/Effects/Fabric (git-ignored)
|
Cloth, FabricCompute, ClothSolver |
Tests/ |
not packed; outside the library's globs | in the solution; sees the internals through
InternalsVisibleTo |
81 xUnit tests, no GPU needed |
buildTransitive/, which NuGet applies to direct and
transitive references alike, so a game that gets the package through its own engine library (say, a
Borrowed Torch Engine runtime assembly) still gets the shader copy. BorrowedTorchFabricProvideShaderSource
is on by default only for an executable (Exe or WinExe), so the library in
between copies nothing and the game, which owns the Content folder, does. BorrowedTorchFabricContentDir
works with or without a trailing separator; set it in the project file or
Directory.Build.props, so the targets see it when they are imported. For a host that turned
off the builder's **/*.mgcb globbing, the targets declare the copied response file
themselves, without forcing its output folder to Content, so another content root keeps its
name.
What changed
Every finding in the tour, in order of importance, as the code now stands at 1.0.0. The C# builds, 81
unit tests pass and every HLSL kernel compiles with Microsoft's d3dcompiler_47 at
cs_5_0. The kernel figures in item 12 are instruction counts; the rest hold and the
passes after it were measured on a GPU, stepping the real library. Chapters in brackets.
Two sheets from one ContentManager shared one solver Effect [3]
Each FabricEffect clones the loaded effect and disposes its copy. A missing
technique or pass throws naming it, and Dispose ends the instance.
One non-finite setting poisoned the sheet [1, 3]
Apply checks every setting before uploading any and names the bad one; SolverFrequencyHz
must be positive; AirDensity and DragCoefficient clamp at 0. A NaN
frame time counts as none.
Rates and carried motion depended on SolverFrequencyHz [4]
Damping, both frictions and BendingPlasticRate are per 1/120 s,
rescaled per step, and DisplacementScale rescales the carried motion, so even a
live change keeps how the cloth moves.
The grid and RestLength were half-live, and Rebuild cleared state
before checking [1, 2]
Both are captured at Rebuild, which checks everything before touching the live
sheet; SetParticles makes the new buffers before releasing the old; the
constructor builds nothing.
No live API for pins, and moved pins kicked and rubbed [2, 4]
SetPinned and IsPinned. Anchors live in their own 8-byte buffer,
re-measured on the CPU once before the next step with no readback, and a pin carries no
motion.
Cutting: half-applied throws, bridging slow drags, rays that could not cross or reach a cut, unclipped strokes, no surface check [5]
Points checked first, the rest in a finally; every segment of a cut recorded,
collinear ones merged; FabricStroke and AssembleRayStroke;
Liang–Barsky clipping in double; surfaces stamped with their owner and build.
The cut mesh: a three-stroke seam limit, cracks through lattice points, vanishing one-cell strips [5]
Rewritten as a cut graph per damaged triangle, ear-clipped, with rim points worked out once per thread, region signatures over every (stroke, side) pair, and two-carrier seam vertices. Fuzzed over 26,000 random sheets with no bridging, cracks, winding or weight errors; the only holes left are scraps of fewer than two particles.
Solver edge cases [3, 4]
RelaxationIterations = 0 keeps the colliders and the pins' reach; contact state
no longer goes stale; a failed pyramid build no longer half-applies Apply, and
the pyramid is released when pressure is off; a still-air margin, so 64² sheets dome; needle
tests with ≤, so no NaN; no fixed −Z normal; coincident contacts parted by
history before index.
Diagnostic totals wrapped [3]
64-bit totals with a carry, in 15 counter slots, so the resting fraction no longer wraps in 34 s on a 1024² sheet; full candidate lists are reported with the hash's overflow.
Packaging and docs [1, 2, 3, 5, 6]
Targets under buildTransitive/, with build/ importing them; the
shader copy on by default only for an executable; BorrowedTorchFabricContentDir
with or without a trailing slash. README: scissors as one polyline per layer, the
buffer-swap reasoning, RestLength 0.03–0.06, a stale fps figure gone. FabricSettings.EveryRound,
and FabricPinMode docs saying Top is the last row.
A tests project
Tests/: 81 xUnit tests over the cut mesh, picking, severing, clipping, ray
strokes, anchors, the tear mask and settings, through InternalsVisibleTo, in
the solution and outside the library's globs. The demo uses FabricStroke, the
grid as built, and P to release and re-pin its top edge.
Lighter kernels, by instruction count [4, 5]
CS_Bend solves each fold once: fold solves per round fall from 12 to 3 per
particle, and the constraint kernel from about 2,135 instruction slots to about 680, some
150 of them the end-of-step normal that only the last round runs, with CS_Bend
at about 493 on bending rounds only (673 and 486 today). Contact partners are gathered once
a step, up to 32, rather than searched for in 27 buckets every contact round. A pass reads
one tear-mask word instead of up to nine. Feature buffers exist only while their feature is
on.
Faster on the CPU, measured [5, 6]
Picking: about 1–8 µs per nearest-layer ray on a 512² sheet (520,000 triangles), against 3.4–6.5 ms before; the grid files in about 35 ms. The cut mesh: 256 × 256 with 300 strokes in 353 ms instead of 826 ms. Severing scans only the cells along a segment, and uploads write the front buffers only, with no LINQ.
Normals blend between steps [1, 3]
The last constraint round computes the normal of the pose the step ends in, and keeps the one
it began in, octahedron-packed into four bytes: the record grows from 60 to 64 bytes. FabricEvaluateVertex
and the new FabricInterpolatedNormal blend them by the fraction, so shading
turns as smoothly as the cloth moves, and the drawn normal no longer trails the drawn
position by a step.
Piles never came to rest [4]
UseRestHold: a supported point that has rested for 0.05 s is held, and a
net step move within 0.25 mm snaps back; buckets and candidate lists hold 32. A dropped
pile went from 170 µm a step and 100–460 mm pops to 99.7–99.9% bitwise still, at a
cost within noise. SampleHeldFraction reports it.
The deadband froze a slow swing; resting cloth ignored wind and slopes, and hovered under pressure [4]
A running average keeps slow motion that persists on cloth touching nothing (7 cm short of the truth, not a metre); a carried resting point loses only its push into the support, and static friction holds the rest within its cone; the pressure pyramid is fed the push actually applied (86% held after 20 s, now 99%).
Stale sampling windows and rebuild edges [2, 3, 6]
The resting and held windows restart only when the pin count changes, so a host uploading
every frame sees them move; Rebuilt is raised even when Apply
fails; SyncPins tells a sheet of another shape apart; AutoRebuild
compares the clamped SeedRipple; the diagnostics check their inputs; the anchor
test that could not fail now can.
Faster passes, timed on a GPU [4, 5]
Six position reads in CS_Bend instead of twelve, weave neighbours read once a
pass, positions-only ApplyPressure, candidate lists by rank, cells beyond the
radius skipped: equal at 96 × 64, 15–20% faster per step at 192 × 128 and 384 × 256. On the
CPU, cut meshes and triangle lists are kept until the damage changes.
The settings hold every sheet field, and can rebuild by themselves [1, 2]
SeedRipple in FabricSettings, AutoRebuild and Fabric.Rebuilt,
TimeStep as the solver takes it, and CompressionSlack 0.375, the
least that does not fight self-collision.
The static-friction cone followed the step rate [4]
It read the per-step friction, so 0.35 held about 28° at 120 Hz but 54° at 60 Hz and 13.5° at 240 Hz. The settings themselves now go up as the static grips: the same cone at any rate, and the same results at 120 Hz to within rounding. The contract version stays 3: 1.0.0 is not out yet, so no header in the wild lacks the new inputs.
The rest rules' push thresholds followed the step rate [4]
What a resting point ignored, and what a touching point crept under instead of sliding, went as 1 / dt. Pushes are now judged as accelerations (3.6 m/s² at the defaults) and pulls as distances (0.25 mm), a held point loses its hold only to a push that moves it, and a driven touching point slides. A 50° slope slides at every rate, the ball sheet slides off in 5.0–5.5 s from 60 to 240 Hz, the piles hold as before at 120 and 240 Hz, the swing is bit-identical and the cost within a few percent; past about 300 Hz the solver's own residual takes over and the hold errs toward holding.
The 1D row-major dispatch order [4]
2D tiles might reuse caches better on wide sheets, but whether the constraint pass is memory-bound needs profiling on a GPU first.
A full cut-mesh rebuild per change of damage [5]
It is 2.3 times faster now. An incremental cache would tie correctness to every walk limit in the builder.
A carefully engineered solver
The architecture is unchanged and still clean (CPU model, GPU effect, host-owned rendering), the numerics are defensive in the right places, and the failure modes are measured rather than guessed. The issues were edges, not foundations. It has run on a GPU since: the rest hold, the latest kernel pass and the rate-independent friction cone were all measured there, and the rest rules were then rebuilt, on the same piles, so the step rate has no hand in what resting cloth ignores.