Skip to content

ByteTerrace/Puck / .claude/skills/maths-usage

maths-usage

Verified

Picks Puck.Maths primitives and determinism rules: FixedQ4816, FixedVector3, rate accumulators, Pcg32XshRr, AliasTable, Fnv1aHash, rounding, saturation, primes. Law cases: maths-laws.

FileKindSize
SKILL.mdskill md18.8 KB
evals/mu01-velocity-rate-accumulator/graders/fixed-point-vector.mdmarkdown73 B
evals/mu01-velocity-rate-accumulator/graders/list-element-copy-hazard.mdmarkdown826 B
evals/mu01-velocity-rate-accumulator/graders/one-way-presentation-seams.mdmarkdown672 B
evals/mu01-velocity-rate-accumulator/graders/rate-accumulator.mdmarkdown84 B
evals/mu01-velocity-rate-accumulator/graders/remainder-is-snapshot-state.mdmarkdown642 B
evals/mu01-velocity-rate-accumulator/graders/restores-with-from-remainders.mdmarkdown72 B
evals/mu01-velocity-rate-accumulator/graders/skill-fired.mdmarkdown36 B
evals/mu01-velocity-rate-accumulator/graders/snapshot-round-trip-check.mdmarkdown660 B
evals/mu01-velocity-rate-accumulator/prompt.mdmarkdown551 B
evals/mu02-weighted-loot/graders/alias-table.mdmarkdown67 B
evals/mu02-weighted-loot/graders/builds-the-table-at-load.mdmarkdown403 B
evals/mu02-weighted-loot/graders/entry-order-is-identity.mdmarkdown667 B
evals/mu02-weighted-loot/graders/own-stream-from-master-seed.mdmarkdown674 B
evals/mu02-weighted-loot/graders/pcg32-generator.mdmarkdown67 B
evals/mu02-weighted-loot/graders/persists-increment-and-multiplier.mdmarkdown124 B
evals/mu02-weighted-loot/graders/restores-with-from-raw-bits.mdmarkdown157 B
evals/mu02-weighted-loot/graders/skill-fired.mdmarkdown36 B
evals/mu02-weighted-loot/prompt.mdmarkdown421 B
evals/mu03-rounding-change-governance/graders/changed-hashes-are-expected.mdmarkdown749 B
evals/mu03-rounding-change-governance/graders/classifies-the-new-member.mdmarkdown518 B
evals/mu03-rounding-change-governance/graders/no-node-reuse-on-test.mdmarkdown92 B
evals/mu03-rounding-change-governance/graders/no-recorded-register.mdmarkdown605 B
evals/mu03-rounding-change-governance/graders/node-reuse-on-the-build.mdmarkdown95 B
evals/mu03-rounding-change-governance/graders/release-configuration.mdmarkdown100 B
evals/mu03-rounding-change-governance/graders/routes-to-maths-laws.mdmarkdown67 B
evals/mu03-rounding-change-governance/graders/skill-fired.mdmarkdown36 B
evals/mu03-rounding-change-governance/prompt.mdmarkdown322 B
evals/mu04-seek-by-advance/graders/advance-counts-advances.mdmarkdown463 B
evals/mu04-seek-by-advance/graders/alias-sample-reports-advances.mdmarkdown687 B
evals/mu04-seek-by-advance/graders/bounded-and-shuffle-vary.mdmarkdown631 B
evals/mu04-seek-by-advance/graders/persist-state-instead.mdmarkdown157 B
evals/mu04-seek-by-advance/graders/skill-fired.mdmarkdown36 B
evals/mu04-seek-by-advance/prompt.mdmarkdown459 B
evals/mu05-hand-rolled-helpers/graders/bitwise-pair.mdmarkdown68 B
evals/mu05-hand-rolled-helpers/graders/fast-parallel-bits-gate.mdmarkdown76 B
evals/mu05-hand-rolled-helpers/graders/floor-division.mdmarkdown68 B
evals/mu05-hand-rolled-helpers/graders/fnv1a-hash.mdmarkdown66 B
evals/mu05-hand-rolled-helpers/graders/skill-fired.mdmarkdown36 B
evals/mu05-hand-rolled-helpers/graders/why-not-bmi2-is-supported.mdmarkdown658 B
evals/mu05-hand-rolled-helpers/prompt.mdmarkdown522 B
references/complete-reference.mdmarkdown26.7 KB
references/prime-kernels.mdmarkdown1.8 KB
---
name: maths-usage
description: "Picks Puck.Maths primitives and determinism rules: FixedQ4816, FixedVector3, rate accumulators, Pcg32XshRr, AliasTable, Fnv1aHash, rounding, saturation, primes. Law cases: maths-laws."
---

# Puck.Maths: choose, obey, verify

During the refactoring campaign, AGENTS.md suspends this skill's blanket test,
coverage and gate requirements. An explicit brief's verification still applies;
exact rejection and continuation laws are useful where a running world cannot
reliably reach the inputs.

Puck.Maths is the deterministic numerics library for values a simulation
advances, compares, hashes, snapshots or replays: the same inputs give the same
bits on every machine, backend and run. Presentation-only floats, shaders,
renderer or UI math and explicit presentation conversions are outside this
contract. Each wing has a README that owns its contracts; when one disagrees
with this file, the wing wins.

## Choose

Search the library and the relevant wing README before hand-rolling numeric
behavior ([`content-search`](../content-search/SKILL.md) finds candidates). A
second implementation of a lerp, clamp, GCD, floor division, bit mixer or rate
carrier can diverge in rounding, overflow or floor and ceiling convention.

| The value is | Use | Not |
|---|---|---|
| A signed quantity with an integer part: position, velocity, accumulated advance | `FixedQ4816` (Q48.16 on a `long`) | `float`/`double`; a bare `long` scaled by hand |
| The same, never negative | `UFixedQ4816` | `FixedQ4816` plus an assertion |
| A fraction in `[0, 1)` | `UnitFraction16` or `UnitFraction32` | A Q48.16 promised to stay under one |
| A weight or probability that must reach 1 | `UnitInterval32` (closed `[0, 1]`) | `UnitFraction32`, which has no `One` |
| A 2D or 3D displacement | `FixedVector2` / `FixedVector3` | Three scalars |
| A rotation | `FixedComplex` (2D), `FixedQuaternion` (3D), `FixedRigidTransform` (rotation plus translation) | Hand-built matrices |
| A world-axis box: bounds, a broadphase envelope, a read region, a cache key | `FixedAabb` (exact corners; `Intersects`, `Contains`, `Enclose` from `Empty`, saturating `Grow`; `Everywhere` for no bounds); a turned box's world extent is `FixedAabb.OrientedHalfExtent` | A centre/extent tuple, a hand min/max accumulator, a negated-maximum minimum, a centre rounded by `/ 2` |
| A hex colour (`#RGB`, `#RGBA`, `#RRGGBB`, `#RRGGBBAA`) | `HexColor` (`TryParse` for opaque, `TryParseRgba`, `TryCanonicalize` for the long uppercase form a compiled document holds) | `int.TryParse(..., NumberStyles.HexNumber)`, which admits whitespace; a second length check |
| A world position beyond a small scene | `FixedPosition` (cell indices plus a local offset) | A bare `FixedVector3`, which is a displacement |
| A rate integrated over ticks | `FixedRateAccumulator` / `FixedVector3RateAccumulator` | A per-second velocity pre-rounded into one per-tick delta |
| A target that eases or overshoots | `SecondOrderDynamics` | `SecondOrderFollower3` and `SecondOrderFollower4`, the presentation-only float twins |
| Lerp or clamp | `FixedQ4816.Lerp` / `.Clamp`, `FixedVector3.Lerp`, `FixedQuaternion.Slerp` | A hand-rolled `a + (b - a) * t` |
| Sequential random draws | `Pcg32XshRr` | `System.Random`, `Random.Shared` |
| A bounded index over a fallible or budgeted raw-word source | `BoundedRandomSampling.TrySampleRange` (or `TrySampleWide` past 32 bits) over an `IRawWordSource`, with a caller-set attempt budget; it counts every raw word and refuses on exhaustion. `TryMap` is the per-word step | A multiply-high map without rejection; a second Lemire implementation |
| A weighted pick | `WeightedSampler.Create` once at load, then `AliasTable<T>.Sample` | A per-call cumulative scan over floats |
| A shuffle | `Pcg32XshRr.Shuffle` | `OrderBy(_ => random)` |
| Spatial noise, per-cell randomness or a scattered point | `Pcg3dLatticeNoise` (`ValueNoise01`, `ScatterPoint`) | A per-call RNG; a second copy of the block formula |
| Fractal (fBm) value noise over a 2D cell index: a noise fill, a patchy placement region | `Pcg3dLatticeNoise.Fbm01(cellX, cellZ, frequency, octaves, seed)`: halved edge and amplitude per octave, a `HashStreamA` seed step, the world seed folded into `seed` with `PackedIntPair.FoldXor` | A per-caller octave loop over `ValueNoise01`, which can drift from the other callers' |
| A one-shot weighted pick | `WeightedSampler.SampleOnce` | A cumulative scan; a table built to be thrown away |
| A 64-bit mix with an inverse | `InvertibleBitMix.Mix64` (SplitMix64's finalizer) | A hand-rolled multiply-xorshift |
| A fixed 64-bit table or a few seed-expanded words from one seed (not a simulation's draws) | `SplitMix64` (`GoldenGamma` increment, `Mix64` output) | A hand-written `state += 0x9E37…; Mix64(state)` loop |
| A little-endian base-128 unsigned integer: an AV1 size, a WebAssembly integer, a canonical length, a baked delta stream | `Leb128.TryRead` (`maxBits`, `requireMinimal`) and `Leb128.Write` (minimal spelling) | A per-format reader or writer |
| A sequence as a dictionary or set key (an array, a read-only list, or a span through an alternate lookup) | `SequenceEqualityComparer<T>.Instance` | A private `IEqualityComparer<int[]>` per caller |
| The first element of a sorted run a monotone test rejects (a lower or upper bound over an index table, a tuple list or a key array) | `PartitionPoint.Of`; for an exact-match search `MemoryExtensions.BinarySearch` | A hand-written `while (low < high)` loop |
| Two 32-bit words packed into one `long` or `ulong` (a pair key, a LUID, a handle's generation over its index, a 64-bit value split into GPU words) | `PackedIntPair.Pack(high, low)`, `High`, `Low`: ints into a `long`, uints into a `ulong`, the low word zero-extended | `(((long)a) << 32) \| ((uint)b)` and `(int)(x >> 32)` written by hand: the signed high half and the zero-extended low half are each a place to differ |
| A 64-bit seed or hash narrowed to 32 bits (a `GetHashCode`, a digest, a seed folded with a world seed) | `PackedIntPair.FoldXor(ulong)`: low word xor high word, as a `uint` | `(uint)x ^ (uint)(x >> 32)` written by hand, or `(uint)x` alone, which drops the high word |
| A Windows adapter `LUID` packed into the 64-bit identity `IGpuDeviceContext.AdapterLuid` reports | `GpuAdapterLuid.Pack(highPart, lowPart)` in `Puck.Abstractions` (each CsWin32 binding generates its own `LUID`, so it takes the two parts) | `PackedIntPair.Pack` re-spelled with the `LowPart` cast at each DXGI or Direct3D reader |
| Hashing two 32-bit words packed into a `long` dictionary or set key | `PackedIntPairComparer.Instance` beside `InvertibleBitMix`: full-word equality and a Fibonacci multiply's upper word. A custom comparer costs an interface call per probe that the default comparer's path does not ([collections](../dotnet-performance/references/collections-and-linq.md#value-type-keys-the-default-comparer-takes-a-path-with-no-comparer-call)); measure before reshaping a hot map's key | Long's default hash folds the halves; a private comparer per caller |
| Dividing many `uint` values by one nonzero `uint` divisor | `ReciprocalDivisor32`: ceil(2^64/d), high multiply, exact across both uint ranges; default divides by one | A private reciprocal copy; applying the uncorrected formula to a 64-bit dividend |
| An angle in degrees entering the sim | `FixedQ4816.FromDegrees` (one rounding against `PiQ189`) | `FromDouble(degrees * (Math.PI / 180))`, a rounded radians-per-degree factor |
| π, π/2, 2π, or an angle reduced to one turn | `FixedQ4816.Pi`/`HalfPi`/`Tau`, `FixedQ4816.WrapAngle` | `FromDouble(Math.PI)`, `Pi + Pi` (one raw short of `Tau`), a floor-and-correct wrap |
| A vector shortened to a length, or rejected from an axis | `FixedVector3.ClampLength`/`WithLength` (toward zero, never above), `RejectFrom`/`TryRejectNormalized`; a one-sided limit (a contact removing approach velocity) is `LimitAlong` | `(v / v.Length) * limit`, which can land above the limit |
| A product over a divisor (`x·y/z`), a projection's segment parameter (`clamp(dot(p, s)/dot(s, s), 0, 1)`), or the nearer of two offsets | `FusedArithmetic.MultiplyDivide`; `FixedVector2.SegmentParameter` / `FixedVector3.SegmentParameter` (or `FusedArithmetic.ClampedUnitQuotient` over sums already formed); `FixedVector3.CompareLengthTo`. Each rounds once or not at all | `(x * y) / z`, `Dot(p, s) / Dot(s, s)`, `a.LengthSquared < b.LengthSquared`: each rounds a product of lengths to `2⁻¹⁶`, which at centimetre sizes keeps a few bits and puts a millimetre of noise in a field |
| A sphere or cone test | `FixedVector3.IsWithin` (exact `\|d\|² ≤ r²`), `IsWithinCone` (apex inside, normalized forward) | `LengthSquared > r * r` (rounded twice), a cone that rejects its apex |
| Spread points, or stratification that must be a theorem | `LowDiscrepancy` (R1, R2), `DigitalNetSampler` | Plain random scatter |
| A per-tick state hash for a replay probe | `Fnv1aHash` | `string.GetHashCode` or `HashCode.Combine` (randomly seeded per process) |
| A change key whose equality stands for "unchanged" (a lighting key, a wake version, a rig read revision) | A 64-bit `Fnv1aHash` digest of every input bit (`AddBits` for a presentation float, vector, quaternion or matrix), or a revision counter where one exists | `HashCode`, a 32-bit per-process digest that collides silently; `HashCode` is for in-memory hash tables only |
| An order-independent digest of a multiset that elements join and leave (a board fingerprint, a scene's static draws, an intern ledger) | `MultisetDigest` beside `InvertibleBitMix`: `Add`, `Remove`, `Union`; a composite element is folded to one word first | A hand sum of hashes, an XOR fold (pairs cancel), a sum of 32-bit `HashCode` values |
| An object's reference identity as a word a digest folds (in-memory change keys only) | `ReferenceSerial.Of` (`Puck.Abstractions`) | `RuntimeHelpers.GetHashCode`, 32 bits and shared by distinct objects |
| Hex cells, tile or chunk order, rings | `HexagonalCoordinate`, `HilbertCurve`, `LayerSequence` | Hand-rolled axial math |
| Floor or ceiling division, low masks, alignment, PDEP/PEXT, Morton codes | `BinaryIntegerFunctions` (`FloorDivide`, `CeilingDivide`, `LowMask`, `AlignUp`, `ParallelBitDeposit`, `BitwisePair`) | `/` on a negative dividend, `(1 << n) - 1`, a `Bmi2` call |
| Exact GF(2^k), mod p, a primality decision | `BinaryField<T>`, `PrimeField64`, `PrimeExtensions.IsPrime` | Floats; a rounded product |
| The Nth prime or a prime count within `uint` | `PrimeExtensions.NthPrime(uint)` / `PrimeCountingFunction(uint)` | A second sieve or counting implementation |
| A median, percentile or quantile of a measured sample (frame times, bench samples, mesh audit shares; outside the determinism contract) | `OrderStatistics.Quantile` (linear interpolation, the rule that describes a sample) or `OrderStatistics.NearestRank` (an observed sample by integer rank, such as an expected peak) | `samples[count / 2]`, `(int)((n - 1) * 0.99)` or a private percentile helper: each is a third rule |
| A graph, lattice, language or finite structure | The `Oracle/` presented algebra | A bespoke solver |

`FixedQ3232`, `FixedInterval`, `FixedMassProperties`,
`FixedSymmetricSolve`, `CurvatureSpline`, the transforms (NTT, Walsh-Hadamard,
fixed FFT and DCT) and the `Research/` wing are in the wing READMEs' "At a
glance" tables. [references/complete-reference.md](references/complete-reference.md)
maps each question to its wing and README section.

## Contracts that bite

- **Rate accumulators carry authoritative state.** The sub-unit remainder and
  `TicksPerSecond` ride snapshots and state hashes, restored together with
  `FromRemainder` / `FromRemainders`. Call `Reset` when the integrated quantity
  is assigned, clamped or teleported outside the accumulator. Both are mutable
  structs: keep one in a field, an array slot or a `ref` local. A `readonly`
  field, a get-only property or a `List<T>` element hands `Integrate` a copy,
  and every advance is silently lost.
- **RNG state is simulation state.** One `Pcg32XshRr` stream per system,
  derived from the master seed with a small consecutive id
  (`Create(state: masterSeed, stream: id)`); persist `State`, `Increment` and
  `Multiplier` and restore through `FromRawBits`. Never share a generator
  across systems, never reseed to "resume", and keep draw order stable.
- **Alias tables are order-sensitive.** Build once at load from
  deterministically ordered entries; entry order is part of the table's
  identity. A sample is exact and reports the advances it consumed (two, plus
  an exact wide draw on the one word in 2^32 that equals a column's threshold).
- **Seeking counts advances, not calls.** `Advance`-based seeking is exact only
  against fixed-cost draws (`NextUInt32()`, the fraction draws, the Gaussian
  pair) or a draw's reported advance count (an alias sample's `advances`). A
  bounded `NextUInt32(min, max)` and `Shuffle` can reject and consume extra
  advances.
- **Wrap is the default.** Bare operators are unchecked, `checked` forms throw
  after rounding, and `AddSaturating` / `SubtractSaturating` (unsigned and unit
  types) or `FixedSaturate` (`FixedQ4816` and vectors) clamp. Some saturators
  have no `Try...` sibling. State the rounding and overflow policy at each
  narrowing boundary.
- **Ties go to even** everywhere except `Exp2`, `Log2` and `Atan2`, which
  narrow half up. Do not add a fourth exception or "correct" one of the three.
- **Do not reassociate a rounded product.** `(a * b) * c` and `a * (b * c)`
  differ over `FixedQ4816`; the fused kernels round a whole expression once.
  Finite-field products are exact and may be reassociated.
- **Projection bounds use the point kernel too.** `FixedInterval.SegmentParameter`
  encloses a fixed segment's parameter over a 2D or 3D box through its two
  extreme corners. Dividing carrier-rounded dot-product intervals can turn
  a tiny squared length into a divisor containing zero, or overflow a large
  one, and leave an otherwise valid SDF program with no query frame.
- **Float presentation helpers live in `VectorFunctions`.** The angle wraps,
  easings, shortest arc, the rotation of a right/up/forward basis (`FromBasis`),
  a turned box's world half-extent, −Z-forward attitude readbacks and unorm packers every
  presentation seam shares are in `Puck.Maths.VectorFunctions`, outside the
  determinism contract and in every project's closure; a second float copy in
  a client or shader-side file is a defect.
- **Floats stay out of state.** Authoring in (`FromDouble`, a document weight)
  and presentation out (`ToVector3`, `ToQuaternion`,
  `FixedPosition.ToRenderRelative`) are the two boundaries; presentation seams
  are one-way, and nothing they return flows back into state.
- **Outbound precision needs an exact oracle.** The `FixedQ4816` float cast rounds
  its raw directly to single precision before exact binary scaling; routing it
  through double can manufacture a tie. The decimal-backed `Half` conversion
  is correctly rounded at the current Q16/Q32 scales, pinned at every Half
  midpoint by `scalar.half-midpoints-vs-exact-oracle`; do not assume that proof covers
  a future finer carrier. Generic `FixedQ3232`/`UFixedQ4816` peers round to the
  target grid before applying checked, saturating or width-truncating policy.
- **Generic peers support both hooks.** Verify `TryConvertFrom*` and
  `TryConvertTo*` directly through the derived-interface adapter in the Maths
  suite. `Create*` falls back to the other operand's hook and can conceal a
  missing half of the conversion contract.
- **Gate `PDEP`/`PEXT` on `BitManipulation.HasFastParallelBits`**, never
  `Bmi2.IsSupported`: AMD before Zen 3 (the Steam Deck's Zen 2 included) and
  Hygon's licensed Zen 1 run them in microcode at up to hundreds of cycles.
- **Do not infer a contract from a name.** Read the member's XML documentation,
  its wing README section and the tests that pin it.
- **A deliberate correction moves values.** A rounding or logic fix is expected
  to change state hashes: make it, and re-record the persisted replay or
  baseline it invalidates (`AGENTS.md` rule 4). Never keep a path that
  reproduces the old wrong result.

## Prime kernels

Work on `PrimeExtensions.IsPrime`, `NthPrime(uint)`, `PrimeKernels` and
`ScaledResidueRing64` follows
[references/prime-kernels.md](references/prime-kernels.md). Preserve the fast
single-value decision and its SIMD fallbacks. Wide prime counting, selection and
interval exploration are out of scope (the owner's ruling,
[prime exploration](../../../docs/reference/prime-exploration.md));
`Research/`, `Algebra/` and `Oracle/` are unaffected.

## Verify

Build the test project (`dotnet build tests/Puck.Maths.Tests/Puck.Maths.Tests.csproj
-c Release -nodeReuse:false`). Running the suite is optional while the campaign
lifts test requirements; where a change needs the evidence, it takes about half a
minute:

```text
dotnet test tests/Puck.Maths.Tests/Puck.Maths.Tests.csproj -c Release --no-build
```

Pass `-nodeReuse:false` to the build step only
([verification](../verification/SKILL.md#build-before-you-test)). The run is
the Default tier. A rounding change or a new value
kernel can also use Deep (`--explicit on --filter-trait tier=Deep`). Exhaustive
takes tens of minutes: run it only when the member's waiver or the coverage
law declaration names it as the gate of record, and narrow it to one law with
`--explicit on --filter-display-name '<law-id>*'`. No tier measures time;
`puck bench` does. Report the exact commands you ran and where any failure came
from.

A new public Maths member carries its classification (a law case or a
precise waiver) in the same change; the 100% line-coverage target is suspended
for the campaign. Authoring the case and waiver belongs to
[`maths-laws`](../maths-laws/SKILL.md). The owner rules out recorded Maths
registers and coverage ratchets; completeness is checked from the current declarations.

## Route adjacent work

| Skill | Use when |
|---|---|
| [`maths-laws`](../maths-laws/SKILL.md) | Authoring or changing a Maths law, subject, oracle, leg, waiver or public-member classification. |
| [`dotnet-performance`](../dotnet-performance/SKILL.md) | SIMD, allocation and throughput questions on code that is not a simulation value path. |
| [`rendering`](../rendering/SKILL.md) | Shaders, renderer or UI math and presentation-only floats, which sit outside the determinism contract. |
| [`content-search`](../content-search/SKILL.md) | Finding textual occurrences, candidate hand-rollings, tokens or patterns across the tree. |
| [`symbol-analysis`](../symbol-analysis/SKILL.md) | Semantic C# questions about references, implementers, dead code, renames or deletion safety. |
| [`gaming-bricks`](../gaming-bricks/SKILL.md) | Verifying a Maths change that reaches emulator code and its dedicated batteries. |
| [`physics`](../physics/SKILL.md) | Contact, sweep, rigid, gravity and navigation kernels that consume these primitives. |
| [`state`](../state/SKILL.md) | The rule engine's expression arithmetic, draw sites and arena hashing. |

slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall