Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,9 @@ every angle is in radians, with `90f.degrees` and `toDegrees()` in `klyph.math`
step allocates nothing (`AllocationTest` checks that with the GC's statistics); the old `Int`-slot
functions stay `internal` for the solver and its tests; `SolidGrid` is the level, `Events` what the
last step did, `addPhysics` and `PhysicsBody` the bridge to `App` and the entity world, and
`DebugDraw` draws it; collision filters are `klyph.collision.CollisionLayers`, with the level on
`PhysicsLayers.SOLIDS`, layer 30; `docs/physics.md` is its guide page and `docs/physics/` the
explainers, read on GitHub),
`DebugDraw` draws it; collision filters are `klyph.collision.CollisionLayers`, read with a
both-sides rule, and each thing's `SolidCollision` (`setSolidCollision`), not a layer, keeps it in the
level; `docs/physics.md` is its guide page and `docs/physics/` the explainers, read on GitHub),
`sandbox` (executable; a smoke test that opens a window and clears it each frame), `games:shooter`
(executable in `games/shooter`; the reference game sample, keyboard with mouse aim or gamepad, its art and sounds in
`games/shooter/assets/` synced next to the binary after every link; enemies come in waves kept in a
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package klyph.benchmarks

import klyph.physics.ParticleCollision
import klyph.physics.BodyCollision
import klyph.physics.PhysicsConfig
import klyph.physics.PhysicsWorld
import klyph.physics.Shape
Expand Down Expand Up @@ -100,7 +100,7 @@ private fun stressWorld(boxes: Int, grains: Int, blobs: Int): PhysicsWorld {
while (world.particles.size < grains) {
var x = left + if (row % 2 == 1) gap / 2f else 0f
while (x <= right && world.particles.size < grains) {
world.particles.add(x, y, radius = GRAIN_RADIUS, collision = ParticleCollision.EVERYTHING)
world.particles.add(x, y, radius = GRAIN_RADIUS, bodyCollision = BodyCollision.COLLIDE)
x += gap
}
y -= gap * 0.87f
Expand Down
16 changes: 9 additions & 7 deletions docs/physics.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,21 +212,23 @@ addSystem(Phase.FIXED_UPDATE) { _ ->

## Layers and fast things

Physics filters collisions with klyph's `CollisionLayers`, as a `Collider` does: everything is
on some layers and has a mask of the layers it collides with. The level is on
`PhysicsLayers.SOLIDS`, layer 30, so layers 0 to 29 are the game's own. A particle collides
only with the level unless it is added with `ParticleCollision.EVERYTHING`, which sand needs.
Physics filters collisions with klyph's `CollisionLayers`: everything is on some layers (any of
the 32) and has a mask of the layers it collides with. Two things collide only when each one's mask
holds a layer of the other, so either can refuse. The level has no layer: a mask covers only other
bodies and particles, and `setSolidCollision(thing, SolidCollision.PASS)` lets one thing fall
through the level. A particle meets only the level unless it is added with
`BodyCollision.COLLIDE`, which sand needs.
`Motion.BULLET` sweeps a fast body or particle every substep, so it never passes through a
wall, however thin.

<!-- snippet: layers -->
```kotlin
val world = physics.world
val ghost = world.rigidBody(Shape.circle(8f), x = 100f, y = 100f)
// On layer 3, colliding with the level and nothing else.
world.rigidBodies.setLayers(ghost, layers = CollisionLayers.of(3), mask = PhysicsLayers.SOLIDS)
// On layer 3, colliding with no other body. The level still holds it up.
world.rigidBodies.setLayers(ghost, layers = CollisionLayers.of(3), mask = CollisionLayers.NONE)
// Sand that falls through other sand would be no sand; grains collide with everything.
world.particles.add(x = 120f, y = 100f, radius = 2f, collision = ParticleCollision.EVERYTHING)
world.particles.add(x = 120f, y = 100f, radius = 2f, bodyCollision = BodyCollision.COLLIDE)
val shot = world.rigidBody(Shape.circle(2f), x = 0f, y = 100f)
world.rigidBodies.setMotion(shot, Motion.BULLET)
world.rigidBodies.setVelocity(shot, vx = 6_000f, vy = 0f)
Expand Down
6 changes: 3 additions & 3 deletions docs/physics/bodies.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ a second. The core is the goo inside, so now it can't leave.
**A thin skin** 🧴: a dot keeps 0.5 units from other bodies. Two blobs pressed onto the same floor
would otherwise line their dots up exactly on each other's edges, where "inside" is a coin toss.

**Grains** ⏳: `particles.add(x, y, radius = 2f, collision = ParticleCollision.EVERYTHING)`. Two grains closer than
**Grains** ⏳: `particles.add(x, y, radius = 2f, bodyCollision = BodyCollision.COLLIDE)`. Two grains closer than
`ra + rb` are pushed apart along the line between them, by inverse mass. They also stay out of soft
bodies. A particle that doesn't collide (the default) only meets the solids, like the fountain's.
bodies. A particle that doesn't collide (the default) only meets the level, like the fountain's.

**Standing on each other** 🦶: a push that lifts a particle counts as a floor in
[🦶 Contacts](contacts.md), so a blob on top of another can still jump. No tags: only solids have those.
Expand All @@ -60,7 +60,7 @@ half an edge away from the body's own other edges, for things that fold.

| knob | default | turn it up 🔼 | turn it down 🔽 |
|---|---|---|---|
| `collision` on `particles.add` | `SOLIDS` | `EVERYTHING`: a grain, hits bodies and other grains | `SOLIDS`: a ghost, only hits solids 👻 |
| `bodyCollision` on `particles.add` | `PASS` | `COLLIDE`: a grain, hits bodies and other grains | `PASS`: a ghost, only hits the level 👻 |
| `radius` | `0` | a bigger grain, a wider gap | a point |
| `setSelfCollision(body, SelfCollision.COLLIDE)` | `PASS` | a folding skin can't pass through itself | cheaper: no check of every dot against every edge |
| `PhysicsConfig.cellSize` | `AUTO`: the average body | for big bodies | for small ones. about one body wide is best |
Expand Down
4 changes: 2 additions & 2 deletions docs/physics/coupling.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
val world = PhysicsWorld()
val blob = world.softBody(dome, 320f, 448f)
val crate = world.rigidBody(Shape.box(28f, 28f), 320f, 400f) // rests on the blob, squashing it
val grain = world.particles.add(100f, 300f, radius = 2f, collision = ParticleCollision.EVERYTHING) // bounces off crates
val grain = world.particles.add(100f, 300f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) // bounces off crates

val rope = world.rope(500f, 20f, 500f, 300f, segments = 14)
val tie = world.attach(rope.last, crate) // the rope's end, held to the crate
Expand All @@ -39,7 +39,7 @@ push = depth / (wₚ + w_body)
The particle moves `wₚ·push` out, the body `push` back at `r`, moving and turning. A ball that hits a
crate square on its middle pushes it straight; one that hits it high turns it.

**Which particles?** Every particle of a soft body, and every particle made with `collision = ParticleCollision.EVERYTHING`:
**Which particles?** Every particle of a soft body, and every particle made with `bodyCollision = BodyCollision.COLLIDE`:
the same ones that bump into each other. A plain rope or cloth passes through crates, as it passes
through blobs.

Expand Down
18 changes: 10 additions & 8 deletions docs/physics/filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
val RED = CollisionLayers.of(1)
val RED_GATE = CollisionLayers.of(3)
val notRedGate = CollisionLayers(CollisionLayers.ALL.bits and RED_GATE.bits.inv())
val notSolids = CollisionLayers(CollisionLayers.ALL.bits and PhysicsLayers.SOLIDS.bits.inv())

world.rigidBodies.setLayers(gate, RED_GATE, CollisionLayers.ALL)
world.rigidBodies.setLayers(ball, RED, notRedGate) // passes the red gate
world.softBodies.setLayers(blob, RED, notRedGate)
world.particles.setLayers(grain, RED, notSolids) // falls through the level
world.particles.setLayers(grain, RED, CollisionLayers.ALL)
world.particles.setSolidCollision(grain, SolidCollision.PASS) // falls through the level

world.rigidBodies.setResponse(zone, ContactResponse.SENSE)

Expand All @@ -38,11 +38,13 @@ e.contactsBegun.has(TouchSide.of(ball), TouchSide.SOLIDS) // did the ball land
for (i in 0 until e.brokenJointCount) e.brokenJointAt(i)
```

**Filters.** Layers are klyph's `CollisionLayers`, as on a `Collider`: a thing's layers are 0 to 29,
a mask any of them. A pair collides when `layersA and maskB != 0 && layersB and maskA != 0`, so
either one can refuse the other. Everything starts on `CollisionLayers.DEFAULT` with the mask
`CollisionLayers.ALL`. The level has its own layer, `PhysicsLayers.SOLIDS`, layer 30: take it out of
a mask and the thing falls through the floor. A soft body's filter is
**Filters.** Layers are klyph's `CollisionLayers`: a thing's layers and mask can use any of the 32.
Physics collides a pair only when `layersA and maskB != 0 && layersB and maskA != 0`, so each one
can refuse the other; a klyph `Collider` is looser, and `app.collisions` reports a pair when either
mask holds a layer of the other. Everything starts on `CollisionLayers.DEFAULT` with the mask
`CollisionLayers.ALL`. The level has no layer, so no mask touches it: to let a thing fall through the
floor, call `setSolidCollision(thing, SolidCollision.PASS)`. A wall that stops only some layers is a
static rigid body on a layer, not the level. A soft body's filter is
all its particles'. Every place two things meet asks: rigid against rigid, against particles and soft
bodies, soft against soft, particles against the solids, and a bullet's sweep. A filtered pair never
gets a contact, so it never pushes, never wakes the other and never joins its island.
Expand Down Expand Up @@ -73,7 +75,7 @@ nothing. A body that's removed ends its touches in the next step.
| knob | default | what it does |
|---|---|---|
| `setLayers(handle, layers, mask)` | `CollisionLayers.DEFAULT`, `CollisionLayers.ALL` | on rigid bodies, soft bodies and particles: who collides with whom |
| `PhysicsLayers.SOLIDS` in a mask | in | out, and it passes through the level |
| `setSolidCollision(handle, SolidCollision.PASS)` | `SolidCollision.COLLIDE` | it passes through the level |
| `setResponse(body, ContactResponse.SENSE)` | `ContactResponse.PUSH` | notices, never pushes |
| `breakForce` on a weld | never | how hard it can be pulled before it breaks, and says so |

Expand Down
4 changes: 2 additions & 2 deletions docs/physics/ropes.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ sheet.particleAt(3, 5)
```

A `Strand` (rope or chain) and a `Cloth` are just **lists of handles**. The particles and constraints
live in the world like any others, so everything else works on them: collisions (`collision = ParticleCollision.EVERYTHING`),
live in the world like any others, so everything else works on them: collisions (`bodyCollision = BodyCollision.COLLIDE`),
friction, pins, `particles.remove`.

**The three kinds of cloth link.** 🧵
Expand Down Expand Up @@ -71,7 +71,7 @@ is dragged, and how the bridge's far end is moved onto its ledge so it sags.
- 💥 **In 2D a ball can't hit a sheet's face.** It always meets an edge first, and a pinned edge
is a wall. To tear a net, hold it by its sides and let the weight drag its free edge down.
- 💥 **Too many particles to collide.** Every colliding cloth particle goes in the broadphase. A
20 × 20 sheet is 400 more particles; use `ParticleCollision.EVERYTHING` only where something needs to hit it.
20 × 20 sheet is 400 more particles; use `BodyCollision.COLLIDE` only where something needs to hit it.

## 🧪 Try it

Expand Down
12 changes: 6 additions & 6 deletions games/physics/detekt-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
<ID>MaxLineLength:Bench.kt:Bench.Result$class</ID>
<ID>MaxLineLength:BulletsScene.kt:BulletsScene.Run$world.rigidBody(Shape.box(THIN, PANE), x, PANE_Y + PANE / 2f, density = PANE_DENSITY).also { b -> world.joints.hinge(b, JointEnd.WORLD, x, PANE_Y) }</ID>
<ID>MaxLineLength:ClothScene.kt:ClothScene.Run$440f</ID>
<ID>MaxLineLength:ClothScene.kt:ClothScene.Run$heavyBall = w.particles.add(440f + (NET_COLS - 1) * SPACING / 2f, 40f, mass = BALL_MASS, radius = BALL_RADIUS, collision = ParticleCollision.EVERYTHING)</ID>
<ID>MaxLineLength:ClothScene.kt:ClothScene.Run$heavyBall = w.particles.add(440f + (NET_COLS - 1) * SPACING / 2f, 40f, mass = BALL_MASS, radius = BALL_RADIUS, bodyCollision = BodyCollision.COLLIDE)</ID>
<ID>MaxLineLength:CratesAndBlobsScene.kt:CratesAndBlobsScene.Run$swinger = world.rigidBody(Shape.box(SWINGER, SWINGER), endX + dx * SWINGER / 2f, endY + dy * SWINGER / 2f, angle = PULLED_BACK, density = SWINGER_DENSITY)</ID>
<ID>MaxLineLength:CratesAndBlobsScene.kt:CratesAndBlobsScene.Run$val cushion = world.softBody(SoftBodyShape.semiDisc(CUSHION_RADIUS, arcSegments = 22, baseSegments = 12, coreMass = 34f), CUSHION_X, floor)</ID>
<ID>MaxLineLength:CratesAndBlobsScene.kt:CratesAndBlobsScene.Run$val tower = List(TOWER) { world.rigidBody(Shape.box(TOWER_CRATE, TOWER_CRATE), TOWER_X, floor - TOWER_CRATE / 2f - it * TOWER_CRATE) }</ID>
<ID>MaxLineLength:DrumScene.kt:DrumScene.Run$for (i in 0 until CRATES) add(world.rigidBody(Shape.box(CRATE, CRATE), CENTER_X + (i - 2f) * 34f, CENTER_Y + 40f, angle = i * 0.4f))</ID>
<ID>MaxLineLength:GripAndBounceScene.kt:GripAndBounceScene.Run$ps.add((26 + i * 5) * t, DROP_ROW * t, radius = BALL_RADIUS, collision = ParticleCollision.EVERYTHING, material = Material(restitution = RESTITUTIONS[i]))</ID>
<ID>MaxLineLength:GripAndBounceScene.kt:GripAndBounceScene.Run$spawned += ps.add(x, y, radius = BALL_RADIUS, collision = ParticleCollision.EVERYTHING, material = Material(restitution = RESTITUTIONS[i]))</ID>
<ID>MaxLineLength:GripAndBounceScene.kt:GripAndBounceScene.Run$ps.add((26 + i * 5) * t, DROP_ROW * t, radius = BALL_RADIUS, bodyCollision = BodyCollision.COLLIDE, material = Material(restitution = RESTITUTIONS[i]))</ID>
<ID>MaxLineLength:GripAndBounceScene.kt:GripAndBounceScene.Run$spawned += ps.add(x, y, radius = BALL_RADIUS, bodyCollision = BodyCollision.COLLIDE, material = Material(restitution = RESTITUTIONS[i]))</ID>
<ID>MaxLineLength:HeadlessTest.kt:HeadlessTest$assertEquals(0, run.world.queryPoint(mx, my, found), "step $step: the beam's part $i passes through something at ($mx, $my)")</ID>
<ID>MaxLineLength:HeadlessTest.kt:HeadlessTest$assertTrue(bodies.xOf(b) > Scenes.TILE &amp;&amp; bodies.xOf(b) &lt; BulletsScene.PLATE_X, "bullet $b went through, to ${bodies.xOf(b)}")</ID>
<ID>MaxLineLength:HeadlessTest.kt:HeadlessTest$assertTrue(bodies.xOf(torso) in JointsScene.BRIDGE_LEFT..JointsScene.BRIDGE_RIGHT, "the ragdoll is on the bridge: ${bodies.xOf(torso)}")</ID>
Expand All @@ -38,9 +38,9 @@
<ID>MaxLineLength:MouseTest.kt:MouseTest$val grabbed = if (p != null) sandbox.grab(ps.xOf(p), ps.yOf(p)) else sandbox.grab(world.rigidBodies.xOf(b!!), world.rigidBodies.yOf(b))</ID>
<ID>MaxLineLength:PileScene.kt:PileScene$/** The funnel: its walls slope in from [FUNNEL_LEFT] and [FUNNEL_RIGHT] on row [FUNNEL_TOP], over [FUNNEL_ROWS] rows, to a neck 10 tiles wide. */</ID>
<ID>MaxLineLength:PileScene.kt:PileScene.Run$blobs += bodies.add(SHAPES[i % SHAPES.size], x, FUNNEL_TOP * t, SoftBodyTuning(spokeCompliance = 0.001f, areaCompliance = 0.0006f))</ID>
<ID>MaxLineLength:RopeSwingScene.kt:RopeSwingScene.Run$bridge = world.chain(left, y, left + length, y, segments = BRIDGE_SEGMENTS, pinned = PinnedEnds.BOTH, radius = length / BRIDGE_SEGMENTS / 2f, collision = ParticleCollision.EVERYTHING)</ID>
<ID>MaxLineLength:RopeSwingScene.kt:RopeSwingScene.Run$bridge = world.chain(left, y, left + length, y, segments = BRIDGE_SEGMENTS, pinned = PinnedEnds.BOTH, radius = length / BRIDGE_SEGMENTS / 2f, bodyCollision = BodyCollision.COLLIDE)</ID>
<ID>MaxLineLength:RopeSwingScene.kt:RopeSwingScene.Run$debug.square(canvas, ps.xOf(p), ps.yOf(p), if (pinned) 6f else maxOf(2f, ps.radiusOf(p) * 2f), if (pinned) ANCHOR else color)</ID>
<ID>MaxLineLength:SandScene.kt:SandScene.Run$world.particles.add(x + (i % 5 - 2) * GAP + (row % 2) * GAP / 2f, y - row * GAP * 0.87f, radius = GRAIN_RADIUS, collision = ParticleCollision.EVERYTHING)</ID>
<ID>MaxLineLength:SandScene.kt:SandScene.Run$world.particles.add(x + (i % 5 - 2) * GAP + (row % 2) * GAP / 2f, y - row * GAP * 0.87f, radius = GRAIN_RADIUS, bodyCollision = BodyCollision.COLLIDE)</ID>
<ID>MaxLineLength:SandboxApp.kt:canvas.drawText(font, text, width - MARGIN, MARGIN + line++ * LINE, scale = 2f, align = TextAlign.RIGHT, layer = HUD_LAYER, shadow = shadow)</ID>
<ID>MaxLineLength:SandboxApp.kt:if (badge != null) canvas.drawText(font, badge, width / 2f, MARGIN, color = BADGE, scale = 3f, align = TextAlign.CENTER, layer = HUD_LAYER, shadow = shadow)</ID>
<ID>MaxLineLength:SceneTest.kt:SceneTest$for</ID>
Expand All @@ -58,7 +58,7 @@
<ID>MaxLineLength:SpringsScene.kt:SpringsScene.Run$if (k &lt; 2) for (i in 2 until CHAIN_LINKS) cs.bend(chain[i - 2], chain[i - 1], chain[i], compliance = if (k == 0) 0f else SOFT_BEND)</ID>
<ID>MaxLineLength:SpringsScene.kt:SpringsScene.Run$val chain = List(CHAIN_LINKS) { i -> ps.add(chainX[k] + i * CHAIN_GAP, CHAIN_TOP, mass = if (i &lt; 2) Particles.STATIC else 1f) }</ID>
<ID>MaxLineLength:StacksScene.kt:StacksScene.Run$world.rigidBody(Shape.box(DOMINO_WIDTH, DOMINO_HEIGHT), FIRST_DOMINO + it * DOMINO_GAP, floor - DOMINO_HEIGHT / 2f, material = Material.RUBBER)</ID>
<ID>MaxLineLength:StressScene.kt:StressScene.Run$world.particles.add(x + (i % 25 - 12) * gap + (row % 2) * gap / 2f, y - row * gap * 0.87f, radius = StressWorld.GRAIN_RADIUS, collision = ParticleCollision.EVERYTHING)</ID>
<ID>MaxLineLength:StressScene.kt:StressScene.Run$world.particles.add(x + (i % 25 - 12) * gap + (row % 2) * gap / 2f, y - row * gap * 0.87f, radius = StressWorld.GRAIN_RADIUS, bodyCollision = BodyCollision.COLLIDE)</ID>
<ID>ReturnCount:Recording.kt:Recording.Companion$fun parse: Recording?</ID>
<ID>ReturnCount:Sandbox.kt:Sandbox$fun beginStep: Boolean</ID>
<ID>ReturnCount:Scenes.kt:Scenes$fun isOpen: Boolean</ID>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package klyph.physics.demo
import klyph.math.Rect
import klyph.physics.Cloth
import klyph.physics.Particle
import klyph.physics.ParticleCollision
import klyph.physics.BodyCollision
import klyph.physics.PhysicsWorld
import klyph.physics.DebugDraw
import klyph.physics.cloth
Expand Down Expand Up @@ -67,14 +67,14 @@ object ClothScene : Scene {
// a flag held along its left edge, on a pole
flag = w.cloth(56f, 100f, columns = 16, rows = 10, spacing = SPACING, bendCompliance = 0.001f, pinned = { col, _ -> col == 0 })
// a curtain held along its top
curtain = w.cloth(230f, 100f, columns = 14, rows = 18, spacing = SPACING, radius = 2f, collision = ParticleCollision.EVERYTHING)
curtain = w.cloth(230f, 100f, columns = 14, rows = 18, spacing = SPACING, radius = 2f, bodyCollision = BodyCollision.COLLIDE)
// a net held at its two sides, and a heavy ball above it: it lands on the net's top edge, drags
// it down into a V, and tears through
sheet = w.cloth(
440f, 180f, columns = NET_COLS, rows = 8, spacing = SPACING, tearAt = 1.35f, radius = 2f, collision = ParticleCollision.EVERYTHING,
440f, 180f, columns = NET_COLS, rows = 8, spacing = SPACING, tearAt = 1.35f, radius = 2f, bodyCollision = BodyCollision.COLLIDE,
pinned = { col, _ -> col == 0 || col == NET_COLS - 1 },
)
heavyBall = w.particles.add(440f + (NET_COLS - 1) * SPACING / 2f, 40f, mass = BALL_MASS, radius = BALL_RADIUS, collision = ParticleCollision.EVERYTHING)
heavyBall = w.particles.add(440f + (NET_COLS - 1) * SPACING / 2f, 40f, mass = BALL_MASS, radius = BALL_RADIUS, bodyCollision = BodyCollision.COLLIDE)
}

override fun beforeStep(dt: Float) {
Expand All @@ -92,7 +92,7 @@ object ClothScene : Scene {

override fun spawn(x: Float, y: Float) {
if (spawned.size >= Scenes.MAX_SPAWNED || !Scenes.isOpen(world, x, y)) return
spawned += world.particles.add(x, y, mass = BALL_MASS, radius = BALL_RADIUS, collision = ParticleCollision.EVERYTHING)
spawned += world.particles.add(x, y, mass = BALL_MASS, radius = BALL_RADIUS, bodyCollision = BodyCollision.COLLIDE)
}

override fun draw(canvas: Canvas, debug: DebugDraw, view: Rect) {
Expand Down
Loading
Loading