diff --git a/CLAUDE.md b/CLAUDE.md index b99194e..815382e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/benchmarks/src/nativeMain/kotlin/klyph/benchmarks/PhysicsBenchmark.kt b/benchmarks/src/nativeMain/kotlin/klyph/benchmarks/PhysicsBenchmark.kt index 9b9b0bd..7013a3a 100644 --- a/benchmarks/src/nativeMain/kotlin/klyph/benchmarks/PhysicsBenchmark.kt +++ b/benchmarks/src/nativeMain/kotlin/klyph/benchmarks/PhysicsBenchmark.kt @@ -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 @@ -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 diff --git a/docs/physics.md b/docs/physics.md index 564297d..0278b0f 100644 --- a/docs/physics.md +++ b/docs/physics.md @@ -212,10 +212,12 @@ 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. @@ -223,10 +225,10 @@ wall, however thin. ```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) diff --git a/docs/physics/bodies.md b/docs/physics/bodies.md index b540b28..7b4aee8 100644 --- a/docs/physics/bodies.md +++ b/docs/physics/bodies.md @@ -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. @@ -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 | diff --git a/docs/physics/coupling.md b/docs/physics/coupling.md index b51b330..2026fcd 100644 --- a/docs/physics/coupling.md +++ b/docs/physics/coupling.md @@ -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 @@ -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. diff --git a/docs/physics/filters.md b/docs/physics/filters.md index 57b1094..6915463 100644 --- a/docs/physics/filters.md +++ b/docs/physics/filters.md @@ -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) @@ -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. @@ -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 | diff --git a/docs/physics/ropes.md b/docs/physics/ropes.md index 9be8abc..526dead 100644 --- a/docs/physics/ropes.md +++ b/docs/physics/ropes.md @@ -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.** 🧵 @@ -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 diff --git a/games/physics/detekt-baseline.xml b/games/physics/detekt-baseline.xml index 9d4d552..b90a850 100644 --- a/games/physics/detekt-baseline.xml +++ b/games/physics/detekt-baseline.xml @@ -12,13 +12,13 @@ MaxLineLength:Bench.kt:Bench.Result$class 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) } MaxLineLength:ClothScene.kt:ClothScene.Run$440f - 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) + 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) 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) MaxLineLength:CratesAndBlobsScene.kt:CratesAndBlobsScene.Run$val cushion = world.softBody(SoftBodyShape.semiDisc(CUSHION_RADIUS, arcSegments = 22, baseSegments = 12, coreMass = 34f), CUSHION_X, floor) 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) } 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)) - 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])) - MaxLineLength:GripAndBounceScene.kt:GripAndBounceScene.Run$spawned += ps.add(x, y, radius = BALL_RADIUS, collision = ParticleCollision.EVERYTHING, material = Material(restitution = RESTITUTIONS[i])) + 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])) + MaxLineLength:GripAndBounceScene.kt:GripAndBounceScene.Run$spawned += ps.add(x, y, radius = BALL_RADIUS, bodyCollision = BodyCollision.COLLIDE, material = Material(restitution = RESTITUTIONS[i])) 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)") MaxLineLength:HeadlessTest.kt:HeadlessTest$assertTrue(bodies.xOf(b) > Scenes.TILE && bodies.xOf(b) < BulletsScene.PLATE_X, "bullet $b went through, to ${bodies.xOf(b)}") MaxLineLength:HeadlessTest.kt:HeadlessTest$assertTrue(bodies.xOf(torso) in JointsScene.BRIDGE_LEFT..JointsScene.BRIDGE_RIGHT, "the ragdoll is on the bridge: ${bodies.xOf(torso)}") @@ -38,9 +38,9 @@ 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)) 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. */ MaxLineLength:PileScene.kt:PileScene.Run$blobs += bodies.add(SHAPES[i % SHAPES.size], x, FUNNEL_TOP * t, SoftBodyTuning(spokeCompliance = 0.001f, areaCompliance = 0.0006f)) - 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) + 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) 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) - 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) + 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) MaxLineLength:SandboxApp.kt:canvas.drawText(font, text, width - MARGIN, MARGIN + line++ * LINE, scale = 2f, align = TextAlign.RIGHT, layer = HUD_LAYER, shadow = shadow) 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) MaxLineLength:SceneTest.kt:SceneTest$for @@ -58,7 +58,7 @@ MaxLineLength:SpringsScene.kt:SpringsScene.Run$if (k < 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) MaxLineLength:SpringsScene.kt:SpringsScene.Run$val chain = List(CHAIN_LINKS) { i -> ps.add(chainX[k] + i * CHAIN_GAP, CHAIN_TOP, mass = if (i < 2) Particles.STATIC else 1f) } 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) - 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) + 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) ReturnCount:Recording.kt:Recording.Companion$fun parse: Recording? ReturnCount:Sandbox.kt:Sandbox$fun beginStep: Boolean ReturnCount:Scenes.kt:Scenes$fun isOpen: Boolean diff --git a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/ClothScene.kt b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/ClothScene.kt index e45f8ec..0fc51de 100644 --- a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/ClothScene.kt +++ b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/ClothScene.kt @@ -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 @@ -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) { @@ -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) { diff --git a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/CratesAndBlobsScene.kt b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/CratesAndBlobsScene.kt index 68994b5..0fddab4 100644 --- a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/CratesAndBlobsScene.kt +++ b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/CratesAndBlobsScene.kt @@ -2,7 +2,7 @@ package klyph.physics.demo import klyph.math.Rect import klyph.physics.Attachment -import klyph.physics.ParticleCollision +import klyph.physics.BodyCollision import klyph.physics.PhysicsWorld import klyph.physics.PinnedEnds import klyph.physics.RigidBody @@ -117,7 +117,7 @@ object CratesAndBlobsScene : Scene { compliance = STRETCH, pinned = PinnedEnds.BOTH, radius = SPRING_RADIUS, - collision = ParticleCollision.EVERYTHING, + bodyCollision = BodyCollision.COLLIDE, ) /** The crate dropped on the trampoline, once it's been dropped. */ diff --git a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/DrumScene.kt b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/DrumScene.kt index fbf5eb4..ef0160c 100644 --- a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/DrumScene.kt +++ b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/DrumScene.kt @@ -3,7 +3,7 @@ package klyph.physics.demo import klyph.math.Rect import klyph.physics.BodyKind import klyph.physics.Material -import klyph.physics.ParticleCollision +import klyph.physics.BodyCollision import klyph.physics.PhysicsWorld import klyph.physics.RigidBody import klyph.physics.Shape @@ -86,7 +86,7 @@ object DrumScene : Scene { CENTER_X + (it % perRow - perRow / 2f) * gap + (it / perRow % 2) * gap / 2f, CENTER_Y - (it / perRow) * gap, radius = GRAIN_RADIUS, - collision = ParticleCollision.EVERYTHING, + bodyCollision = BodyCollision.COLLIDE, material = Material(friction = 0.6f, staticFriction = 0.8f), ) } diff --git a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/GripAndBounceScene.kt b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/GripAndBounceScene.kt index c5d69cd..5432a17 100644 --- a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/GripAndBounceScene.kt +++ b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/GripAndBounceScene.kt @@ -3,7 +3,7 @@ package klyph.physics.demo import klyph.math.Rect import klyph.physics.Material import klyph.physics.Particle -import klyph.physics.ParticleCollision +import klyph.physics.BodyCollision import klyph.physics.PhysicsWorld import klyph.physics.SoftBody import klyph.physics.SoftBodyShape @@ -69,7 +69,7 @@ object GripAndBounceScene : Scene { override val blobs = List(3) { w -> setDown(bodies.add(shape, 0f, 0f, stiff, material = MATERIALS[w]), w) } val balls = List(3) { i -> - ps.add((26 + i * 5) * t, DROP_ROW * t, radius = BALL_RADIUS, collision = ParticleCollision.EVERYTHING, material = Material(restitution = RESTITUTIONS[i])) + ps.add((26 + i * 5) * t, DROP_ROW * t, radius = BALL_RADIUS, bodyCollision = BodyCollision.COLLIDE, material = Material(restitution = RESTITUTIONS[i])) } /** Balls added with a right click, each bouncing like the next of the three in turn. */ @@ -114,7 +114,7 @@ object GripAndBounceScene : Scene { override fun spawn(x: Float, y: Float) { if (spawned.size >= Scenes.MAX_SPAWNED || !Scenes.isOpen(world, x, y)) return val i = spawned.size % 3 - spawned += ps.add(x, y, radius = BALL_RADIUS, collision = ParticleCollision.EVERYTHING, material = Material(restitution = RESTITUTIONS[i])) + spawned += ps.add(x, y, radius = BALL_RADIUS, bodyCollision = BodyCollision.COLLIDE, material = Material(restitution = RESTITUTIONS[i])) } override fun draw(canvas: Canvas, debug: DebugDraw, view: Rect) { diff --git a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/RopeSwingScene.kt b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/RopeSwingScene.kt index 705e43e..d5df069 100644 --- a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/RopeSwingScene.kt +++ b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/RopeSwingScene.kt @@ -2,7 +2,7 @@ package klyph.physics.demo import klyph.math.Rect import klyph.physics.Particle -import klyph.physics.ParticleCollision +import klyph.physics.BodyCollision import klyph.physics.PhysicsWorld import klyph.physics.PinnedEnds import klyph.physics.SoftBody @@ -83,7 +83,7 @@ object RopeSwingScene : Scene { val right = 36 * t val y = BRIDGE_ROW * t val length = (right - left) * 1.25f - bridge = world.chain(left, y, left + length, y, segments = BRIDGE_SEGMENTS, pinned = PinnedEnds.BOTH, radius = length / BRIDGE_SEGMENTS / 2f, collision = ParticleCollision.EVERYTHING) + bridge = world.chain(left, y, left + length, y, segments = BRIDGE_SEGMENTS, pinned = PinnedEnds.BOTH, radius = length / BRIDGE_SEGMENTS / 2f, bodyCollision = BodyCollision.COLLIDE) ps.moveTo(bridge.last, right, y) blobs = listOf(world.softBody(Scenes.dome(), (left + right) / 2f, (BRIDGE_ROW - 3) * t)) diff --git a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/SandScene.kt b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/SandScene.kt index cdf7b77..cf12f1e 100644 --- a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/SandScene.kt +++ b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/SandScene.kt @@ -1,7 +1,7 @@ package klyph.physics.demo import klyph.math.Rect -import klyph.physics.ParticleCollision +import klyph.physics.BodyCollision import klyph.physics.PhysicsConfig import klyph.physics.PhysicsWorld import klyph.physics.SolidShape @@ -87,7 +87,7 @@ object SandScene : Scene { while (x <= right && ps.size < GRAINS) { if (y < x + leftSlope - clear && y < rightSlope - x - clear) { band[ps.size] = row / 12 % BANDS.size - ps.add(x, y, radius = GRAIN_RADIUS, collision = ParticleCollision.EVERYTHING) + ps.add(x, y, radius = GRAIN_RADIUS, bodyCollision = BodyCollision.COLLIDE) } x += GAP } @@ -104,7 +104,7 @@ object SandScene : Scene { repeat(SCOOP) { i -> // a little hex heap, five grains a row, around the click val row = i / 5 - world.particles.add(x + (i % 5 - 2) * GAP + (row % 2) * GAP / 2f, y - row * GAP * 0.87f, radius = GRAIN_RADIUS, collision = ParticleCollision.EVERYTHING) + world.particles.add(x + (i % 5 - 2) * GAP + (row % 2) * GAP / 2f, y - row * GAP * 0.87f, radius = GRAIN_RADIUS, bodyCollision = BodyCollision.COLLIDE) } } diff --git a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/StressScene.kt b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/StressScene.kt index c8bda85..2dcef42 100644 --- a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/StressScene.kt +++ b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/StressScene.kt @@ -1,7 +1,7 @@ package klyph.physics.demo import klyph.math.Rect -import klyph.physics.ParticleCollision +import klyph.physics.BodyCollision import klyph.physics.PhysicsWorld import klyph.physics.Shape import klyph.physics.DebugDraw @@ -83,7 +83,7 @@ object StressScene : Scene { else -> repeat(SPAWN_GRAINS) { i -> val gap = 2f * StressWorld.GRAIN_RADIUS + 0.1f val row = i / 25 - world.particles.add(x + (i % 25 - 12) * gap + (row % 2) * gap / 2f, y - row * gap * 0.87f, radius = StressWorld.GRAIN_RADIUS, collision = ParticleCollision.EVERYTHING) + world.particles.add(x + (i % 25 - 12) * gap + (row % 2) * gap / 2f, y - row * gap * 0.87f, radius = StressWorld.GRAIN_RADIUS, bodyCollision = BodyCollision.COLLIDE) } } } diff --git a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/StressWorld.kt b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/StressWorld.kt index eb0e953..751617b 100644 --- a/games/physics/src/nativeMain/kotlin/klyph/physics/demo/StressWorld.kt +++ b/games/physics/src/nativeMain/kotlin/klyph/physics/demo/StressWorld.kt @@ -1,6 +1,6 @@ package klyph.physics.demo -import klyph.physics.ParticleCollision +import klyph.physics.BodyCollision import klyph.physics.PhysicsConfig import klyph.physics.PhysicsWorld import klyph.physics.Shape @@ -47,7 +47,7 @@ class StressWorld( while (ps.size < grains) { var x = left + if (row % 2 == 1) gap / 2f else 0f while (x <= right && ps.size < grains) { - ps.add(x, y, radius = GRAIN_RADIUS, collision = ParticleCollision.EVERYTHING) + ps.add(x, y, radius = GRAIN_RADIUS, bodyCollision = BodyCollision.COLLIDE) x += gap } y -= gap * 0.87f diff --git a/klyph-physics/detekt-baseline.xml b/klyph-physics/detekt-baseline.xml index 53a4544..cba8e8f 100644 --- a/klyph-physics/detekt-baseline.xml +++ b/klyph-physics/detekt-baseline.xml @@ -78,8 +78,8 @@ LoopWithTooManyJumpStatements:StackingTest.kt:StackingTest$for MaxLineLength:Bullets.kt:Bullets$if (!bs.alive[other] || bs.bullet[other] || bs.sensor[other] || bs.filtered(b, other) || world.joints.connected(b, other)) continue MaxLineLength:Bullets.kt:Bullets$if (!narrow.collide(sa, poseX, poseY, poseCos, poseSin, sb, bs.x[other], bs.y[other], bs.cos[other], bs.sin[other], manifold)) continue - MaxLineLength:Bullets.kt:Bullets$if (particles.flags[p] and Particles.BULLET == 0 || particles.invMass[p] == 0f || particles.mask[p] and PhysicsLayers.SOLIDS_BIT == 0) continue - MaxLineLength:CollisionTest.kt:CollisionTest$val grains = (0 until 200).map { ps.add(40f + (it % 20) * 6f, 40f + (it / 20) * 6f, radius = 2f, collision = ParticleCollision.EVERYTHING) } + MaxLineLength:Bullets.kt:Bullets$if (particles.flags[p] and Particles.BULLET == 0 || particles.invMass[p] == 0f || particles.flags[p] and Particles.PASSES_SOLIDS != 0) continue + MaxLineLength:CollisionTest.kt:CollisionTest$val grains = (0 until 200).map { ps.add(40f + (it % 20) * 6f, 40f + (it / 20) * 6f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) } MaxLineLength:Collisions.kt:Collisions$bp.addMoving(particleId(p), ps.x[p], ps.y[p], (ps.x[p] - ps.prevX[p]) * ahead, (ps.y[p] - ps.prevY[p]) * ahead, ps.radius[p] + MARGIN) MaxLineLength:Collisions.kt:Collisions$ps.touch(b, nx, ny, reach - distance, Material.mixFriction(friction[b], friction[a]), Material.mixFriction(staticFriction[b], staticFriction[a]), a, -1, 0f) MaxLineLength:Constraints.kt:Constraints$if (ringUsed + ring.size > ringParticles.size) ringParticles = ringParticles.copyOf(maxOf(ringParticles.size * 2, ringUsed + ring.size)) @@ -91,7 +91,7 @@ MaxLineLength:CouplingTest.kt:CouplingTest$assertFalse(bodies.shapesOf(crate)[0].contains(ps.xOf(p) - bodies.xOf(crate), ps.yOf(p) - bodies.yOf(crate)), "particle $i of the blob is inside the crate") MaxLineLength:CouplingTest.kt:CouplingTest$assertTrue(abs(bodies.xOf(top) - 400f) > 20f || abs(bodies.angleOf(top)) > 0.5f, "the top crate was knocked off: at ${bodies.xOf(top)}, turned ${bodies.angleOf(top)}") MaxLineLength:CouplingTest.kt:CouplingTest$assertTrue(ps.yOf(g) < floor - 20f + 0.5f || ps.xOf(g) !in 270f..370f, "grain $g is in the crate at (${ps.xOf(g)}, ${ps.yOf(g)})") - MaxLineLength:CouplingTest.kt:CouplingTest$val grains = List(60) { world.particles.add(300f + (it % 10) * 4f, 300f - (it / 10) * 4f, radius = 2f, collision = ParticleCollision.EVERYTHING) } + MaxLineLength:CouplingTest.kt:CouplingTest$val grains = List(60) { world.particles.add(300f + (it % 10) * 4f, 300f - (it / 10) * 4f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) } MaxLineLength:DebugDraw.kt:DebugDraw$canvas.drawSprite(pixel, x = x, y = y, width = width, height = height, rotation = angle, color = color, layer = layer, space = DrawSpace.WORLD) MaxLineLength:DebugDraw.kt:DebugDraw$canvas.drawText(labelFont, text, x, y, color, scale = 1f, align = TextAlign.CENTER, layer = layer + 5, space = DrawSpace.WORLD, shadow = LABEL_SHADOW) MaxLineLength:Events.kt:Events$val key = TouchPairs.ordered(kindA.ordinal, if (kindA == TouchKind.SOLIDS) 0 else a, kindB.ordinal, if (kindB == TouchKind.SOLIDS) 0 else b) @@ -147,7 +147,7 @@ MaxLineLength:ShapeTest.kt:ShapeTest$assertTrue("in a line" in assertFailsWith<IllegalArgumentException> { Shape.polygon(listOf(Vec2(0f, 0f), Vec2(5f, 0f), Vec2(10f, 0f), Vec2(10f, 10f))) }.message!!) MaxLineLength:ShapeTest.kt:ShapeTest$val error = assertFailsWith<IllegalArgumentException> { Shape.polygon(listOf(Vec2(0f, 0f), Vec2(20f, 0f), Vec2(10f, 5f), Vec2(20f, 10f), Vec2(0f, 10f))) } MaxLineLength:ShapeTest.kt:ShapeTest$val expected = 2f * (handle.inertia + 240f * (10f - centre) * (10f - centre) + head.inertia + 300f * (-15f - centre) * (-15f - centre)) - MaxLineLength:ShortcutsTest.kt:ShortcutsTest$repeat(800) { grains += world.particles.add(150f + random.nextFloat() * 300f, 100f + random.nextFloat() * 300f, radius = 1.25f, collision = ParticleCollision.EVERYTHING) } + MaxLineLength:ShortcutsTest.kt:ShortcutsTest$repeat(800) { grains += world.particles.add(150f + random.nextFloat() * 300f, 100f + random.nextFloat() * 300f, radius = 1.25f, bodyCollision = BodyCollision.COLLIDE) } MaxLineLength:SoftBodies.kt:SoftBodies$if (particleUsed + particles > particlePool.size) particlePool = particlePool.copyOf(max(particlePool.size * 2, particleUsed + particles)) MaxLineLength:SolidEdges.kt:SolidEdges$if (j < 0 || j == i || !sameWay(open[last], open[j]) || open[j].solid.material != open[i].solid.material || steps > open.size) break MaxLineLength:StackingTest.kt:StackingTest$if (!narrow.collide(bodies.shapesOf(a)[0], bodies.xOf(a), bodies.yOf(a), bodies.angleOf(a), bodies.shapesOf(b)[0], bodies.xOf(b), bodies.yOf(b), bodies.angleOf(b), m)) continue diff --git a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Bullets.kt b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Bullets.kt index 22dacda..4dde5f2 100644 --- a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Bullets.kt +++ b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Bullets.kt @@ -115,7 +115,7 @@ internal class Bullets(private val world: PhysicsWorld) { candidates[candidateCount++] = other } val grid = world.solids - if (grid != null && bs.mask[b] and PhysicsLayers.SOLIDS_BIT != 0) { + if (grid != null && !bs.passesSolids[b]) { contacts.updateEdges(grid) val ed = contacts.edges val r = bs.reach[b] + RigidContacts.MARGIN @@ -214,7 +214,7 @@ internal class Bullets(private val world: PhysicsWorld) { val grid = world.solids ?: return val step = grid.tileSize / 4f for (p in 0 until particles.end) { - if (particles.flags[p] and Particles.BULLET == 0 || particles.invMass[p] == 0f || particles.mask[p] and PhysicsLayers.SOLIDS_BIT == 0) continue + if (particles.flags[p] and Particles.BULLET == 0 || particles.invMass[p] == 0f || particles.flags[p] and Particles.PASSES_SOLIDS != 0) continue val x0 = particles.prevX[p] val y0 = particles.prevY[p] val dx = particles.x[p] - x0 diff --git a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Filter.kt b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Filter.kt index 2abffb7..2a66591 100644 --- a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Filter.kt +++ b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Filter.kt @@ -3,35 +3,28 @@ package klyph.physics import klyph.collision.CollisionLayers /** - * The layer the level is on. Physics filters collisions with klyph's [CollisionLayers], as a - * [klyph.collision.Collider] does: everything that collides is on some layers and has a mask of - * the layers it collides with, and two things collide only when each one's mask holds a layer of - * the other. By default everything is on [CollisionLayers.DEFAULT] with the mask - * [CollisionLayers.ALL], so everything collides with everything. + * How physics reads klyph's [CollisionLayers]. Everything that collides is on some layers and has a + * mask of the layers it collides with, and two things collide only when each one's mask holds a + * layer of the other, so either one can refuse the other. By default everything is on + * [CollisionLayers.DEFAULT] with the mask [CollisionLayers.ALL], so everything collides with + * everything. All 32 layers are the game's own. * - * The level, the [SolidGrid], is on [SOLIDS], layer 30: take it out of a mask and the thing passes - * through the solids. Use layers 0 to 29 for your own. + * A klyph [klyph.collision.Collider] reads the same layers with another rule: `Collisions` reports a + * pair when either one's mask holds a layer of the other, as it only says what overlaps. + * + * The layers say nothing about the level: whether a thing is kept out of the [SolidGrid] is its + * [SolidCollision], set with [RigidBodies.setSolidCollision], [SoftBodies.setSolidCollision] and + * [Particles.setSolidCollision]. A wall that stops only some layers is a static rigid body on a layer. * * @sample samples.physics.LayerSamples.layers */ public object PhysicsLayers { - /** Layer 30, the level's: everything whose mask holds it is kept out of the solids. */ - public val SOLIDS: CollisionLayers = CollisionLayers.of(30) - /** Returns `true` if [layersA] with [maskA] and [layersB] with [maskB] collide, as described on [PhysicsLayers]. */ public fun collide(layersA: CollisionLayers, maskA: CollisionLayers, layersB: CollisionLayers, maskB: CollisionLayers): Boolean = collides(layersA.bits, maskA.bits, layersB.bits, maskB.bits) internal fun collides(categoryA: Int, maskA: Int, categoryB: Int, maskB: Int): Boolean = categoryA and maskB != 0 && categoryB and maskA != 0 - - internal const val SOLIDS_BIT: Int = 1 shl 30 - - internal fun checkLayers(layers: CollisionLayers) { - require(layers.bits != 0 && layers.bits and (SOLIDS_BIT or (1 shl 31)) == 0) { - "Layers $layers must hold at least one of layers 0 to 29, as layer 30 is the solids'." - } - } } /** What one side of a [Touch] is. */ diff --git a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Handles.kt b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Handles.kt index b244766..62c514e 100644 --- a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Handles.kt +++ b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Handles.kt @@ -131,13 +131,28 @@ internal object TheWorld : JointEnd { override fun toString(): String = "JointEnd.WORLD" } -/** What a particle collides with: see [Particles.add]. */ -public enum class ParticleCollision { - /** Only the solids of the level, such as a spark or a drop of a fountain. */ - SOLIDS, +/** Whether a particle collides with bodies and other particles: see [Particles.add]. */ +public enum class BodyCollision { + /** + * It passes through rigid bodies, soft bodies and other particles, such as a spark or a drop of a + * fountain: the default, and the cheaper. + */ + PASS, - /** The solids, soft bodies, rigid bodies and every other particle that collides with everything, like a grain of sand. */ - EVERYTHING, + /** It is kept out of rigid bodies, soft bodies and every other particle that collides with bodies, like a grain of sand. */ + COLLIDE, +} + +/** + * Whether a body or a particle is kept out of the level, the [SolidGrid] and its moving solids: see + * [RigidBodies.setSolidCollision], [SoftBodies.setSolidCollision] and [Particles.setSolidCollision]. + */ +public enum class SolidCollision { + /** It is kept out of the solids: the default. */ + COLLIDE, + + /** It passes through the solids, as a ghost does. */ + PASS, } /** How a particle or a rigid body moves each substep: see [Particles.setMotion] and [RigidBodies.setMotion]. */ diff --git a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Particles.kt b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Particles.kt index 1f1f5b1..5392378 100644 --- a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Particles.kt +++ b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Particles.kt @@ -41,6 +41,9 @@ public class Particles internal constructor(initialCapacity: Int = 64) { /** Whether any particle has ever been given a filter: until then, nobody need look. */ internal var anyFiltered = false + /** Whether any particle has ever been set to [SolidCollision.PASS]: until then, nobody need look. */ + internal var anyPassSolids = false + /** Each particle's [Material], spread over three arrays. */ internal var friction = FloatArray(initialCapacity) internal var staticFriction = FloatArray(initialCapacity) @@ -85,10 +88,11 @@ public class Particles internal constructor(initialCapacity: Int = 64) { * Adds a particle at ([x], [y]) at rest and returns its handle. * * [mass] is more than 0, or [STATIC] for a particle nothing moves. [radius] is how far it keeps - * out of things, 0 for a point. With [ParticleCollision.EVERYTHING] it is kept out of soft bodies - * and out of every other such particle, by their radii, like a grain of sand; with - * [ParticleCollision.SOLIDS] it only meets the solids. Its [material] says how it grips and - * bounces. Pass the arguments after [y] by name. + * out of things, 0 for a point. With [BodyCollision.COLLIDE] it is kept out of rigid bodies, soft + * bodies and every other such particle, by their radii, like a grain of sand; with + * [BodyCollision.PASS], the default, it passes through them and only meets the solids. Either way + * it is kept out of the solids until [setSolidCollision] says otherwise. Its [material] says how + * it grips and bounces. Pass the arguments after [y] by name. * * @throws IllegalArgumentException if [mass] is not more than 0 or [radius] is negative. * @@ -99,7 +103,7 @@ public class Particles internal constructor(initialCapacity: Int = 64) { y: Float, mass: Float = 1f, radius: Float = 0f, - collision: ParticleCollision = ParticleCollision.SOLIDS, + bodyCollision: BodyCollision = BodyCollision.PASS, material: Material = Material.DEFAULT, ): Particle { require(mass > 0f) { "Particle mass $mass is not more than 0." } @@ -114,7 +118,7 @@ public class Particles internal constructor(initialCapacity: Int = 64) { prevY[p] = y invMass[p] = if (mass == STATIC) 0f else 1f / mass this.radius[p] = radius - flags[p] = if (collision == ParticleCollision.EVERYTHING) ALIVE or COLLIDES else ALIVE + flags[p] = if (bodyCollision == BodyCollision.COLLIDE) ALIVE or COLLIDES else ALIVE owner[p] = -1 category[p] = CollisionLayers.DEFAULT.bits mask[p] = CollisionLayers.ALL.bits @@ -196,16 +200,13 @@ public class Particles internal constructor(initialCapacity: Int = 64) { internal fun isBulletAt(p: Int): Boolean = flags[p] and BULLET != 0 /** - * Puts [particle] on [layers] and has it collide only with what is on a layer of [mask], as a - * klyph [klyph.collision.Collider] does; see [PhysicsLayers]. For a soft body's particles, set - * the whole body's with [SoftBodies.setLayers]. - * - * @throws IllegalArgumentException if [layers] is empty or holds [PhysicsLayers.SOLIDS]. + * Puts [particle] on [layers] and has it collide with what is on a layer of [mask] and holds a + * layer of [particle]'s in its own mask; see [PhysicsLayers]. The layers say nothing about the solids: see + * [setSolidCollision]. For a soft body's particles, set the whole body's with [SoftBodies.setLayers]. * * @sample samples.physics.ParticleSamples.setLayers */ public fun setLayers(particle: Particle, layers: CollisionLayers, mask: CollisionLayers) { - PhysicsLayers.checkLayers(layers) val p = particle.index category[p] = layers.bits this.mask[p] = mask.bits @@ -218,9 +219,35 @@ public class Particles internal constructor(initialCapacity: Int = 64) { /** Returns the layers [particle] collides with: see [setLayers]. */ public fun maskOf(particle: Particle): CollisionLayers = CollisionLayers(mask[particle.index]) - /** Returns what [particle] collides with besides the solids: see [add]. */ - public fun collisionOf(particle: Particle): ParticleCollision = - if (flags[particle.index] and COLLIDES != 0) ParticleCollision.EVERYTHING else ParticleCollision.SOLIDS + /** Returns whether [particle] collides with bodies and other particles: see [add]. */ + public fun bodyCollisionOf(particle: Particle): BodyCollision = + if (flags[particle.index] and COLLIDES != 0) BodyCollision.COLLIDE else BodyCollision.PASS + + /** + * Sets whether [particle] is kept out of the solids, the [SolidGrid] and its moving solids. It is + * [SolidCollision.COLLIDE] by default; a [SolidCollision.PASS] particle falls through the level. + * For a soft body's particles, set the whole body's with [SoftBodies.setSolidCollision]. + * + * @sample samples.physics.ParticleSamples.setSolidCollision + */ + public fun setSolidCollision(particle: Particle, solidCollision: SolidCollision) { + setPassesSolids(particle.index, solidCollision == SolidCollision.PASS) + } + + /** Returns whether [particle] is kept out of the solids: see [setSolidCollision]. */ + public fun solidCollisionOf(particle: Particle): SolidCollision = + if (passesSolidsAt(particle.index)) SolidCollision.PASS else SolidCollision.COLLIDE + + internal fun setPassesSolids(p: Int, passes: Boolean) { + if (passes) { + flags[p] = flags[p] or PASSES_SOLIDS + anyPassSolids = true + } else { + flags[p] = flags[p] and PASSES_SOLIDS.inv() + } + } + + internal fun passesSolidsAt(p: Int): Boolean = flags[p] and PASSES_SOLIDS != 0 internal fun collidesAt(p: Int): Boolean = flags[p] and COLLIDES != 0 @@ -260,7 +287,7 @@ public class Particles internal constructor(initialCapacity: Int = 64) { // The engine's own ways in, by slot. internal fun addAt(x: Float, y: Float, mass: Float, radius: Float = 0f, collides: Boolean = false): Int = - add(x, y, mass, radius, if (collides) ParticleCollision.EVERYTHING else ParticleCollision.SOLIDS).index + add(x, y, mass, radius, if (collides) BodyCollision.COLLIDE else BodyCollision.PASS).index internal fun remove(p: Int) = removeAt(p) @@ -516,6 +543,7 @@ public class Particles internal constructor(initialCapacity: Int = 64) { internal const val ALIVE = 1 internal const val COLLIDES = 2 internal const val BULLET = 4 + internal const val PASSES_SOLIDS = 8 } } diff --git a/klyph-physics/src/nativeMain/kotlin/klyph/physics/RigidBodies.kt b/klyph-physics/src/nativeMain/kotlin/klyph/physics/RigidBodies.kt index a1496c2..d83006e 100644 --- a/klyph-physics/src/nativeMain/kotlin/klyph/physics/RigidBodies.kt +++ b/klyph-physics/src/nativeMain/kotlin/klyph/physics/RigidBodies.kt @@ -82,6 +82,9 @@ public class RigidBodies internal constructor(initialCapacity: Int = 16) { /** Whether each body is a sensor: see [setResponse]. */ internal var sensor = BooleanArray(initialCapacity) + + /** Whether each body passes through the solids: see [setSolidCollision]. */ + internal var passesSolids = BooleanArray(initialCapacity) internal var thickness = FloatArray(initialCapacity) /** Number of bodies asleep. */ @@ -173,6 +176,7 @@ public class RigidBodies internal constructor(initialCapacity: Int = 16) { category[b] = CollisionLayers.DEFAULT.bits mask[b] = CollisionLayers.ALL.bits sensor[b] = false + passesSolids[b] = false thickness[b] = 0f shapes[b] = NO_SHAPES reach[b] = 0f @@ -255,11 +259,9 @@ public class RigidBodies internal constructor(initialCapacity: Int = 16) { internal fun isBullet(b: Int): Boolean = bullet[b] /** - * Puts [body] on [layers] and has it collide only with what is on a layer of [mask], as a klyph - * [klyph.collision.Collider] does; see [PhysicsLayers]. It wakes, as what it rested on may no longer - * hold it. - * - * @throws IllegalArgumentException if [layers] is empty or holds [PhysicsLayers.SOLIDS]. + * Puts [body] on [layers] and has it collide with what is on a layer of [mask] and holds a layer of + * [body]'s in its own mask; see [PhysicsLayers]. The layers say nothing about the solids: see + * [setSolidCollision]. It wakes, as what it rested on may no longer hold it. * * @sample samples.physics.RigidBodySamples.setLayers */ @@ -274,7 +276,6 @@ public class RigidBodies internal constructor(initialCapacity: Int = 16) { public fun maskOf(body: RigidBody): CollisionLayers = CollisionLayers(mask[body.index]) internal fun setFilter(b: Int, category: Int, mask: Int) { - PhysicsLayers.checkLayers(CollisionLayers(category)) this.category[b] = category this.mask[b] = mask if (category != CollisionLayers.DEFAULT.bits || mask != CollisionLayers.ALL.bits) anyFiltered = true @@ -308,6 +309,28 @@ public class RigidBodies internal constructor(initialCapacity: Int = 16) { internal fun isSensor(b: Int): Boolean = sensor[b] + /** + * Sets whether [body] is kept out of the solids, the [SolidGrid] and its moving solids. It is + * [SolidCollision.COLLIDE] by default; a [SolidCollision.PASS] body falls through the level. A body + * set back to [SolidCollision.COLLIDE] while a little way into a solid is pushed out; one sunk most + * of the way in stays there. A change wakes it; setting the value it already has does nothing. + * + * @sample samples.physics.RigidBodySamples.setSolidCollision + */ + public fun setSolidCollision(body: RigidBody, solidCollision: SolidCollision) { + setPassesSolids(body.index, solidCollision == SolidCollision.PASS) + } + + /** Returns whether [body] is kept out of the solids: see [setSolidCollision]. */ + public fun solidCollisionOf(body: RigidBody): SolidCollision = + if (passesSolids[body.index]) SolidCollision.PASS else SolidCollision.COLLIDE + + internal fun setPassesSolids(b: Int, passes: Boolean) { + if (passesSolids[b] == passes) return + passesSolids[b] = passes + if (alive[b]) wake(b) + } + /** Whether bodies [p] and [q] are let collide by their filters: see [Filter]. */ @Suppress("NOTHING_TO_INLINE") internal inline fun filtered(p: Int, q: Int): Boolean = anyFiltered && !PhysicsLayers.collides(category[p], mask[p], category[q], mask[q]) @@ -793,6 +816,7 @@ public class RigidBodies internal constructor(initialCapacity: Int = 16) { category = category.copyOf(size) mask = mask.copyOf(size) sensor = sensor.copyOf(size) + passesSolids = passesSolids.copyOf(size) thickness = thickness.copyOf(size) stillFor = stillFor.copyOf(size) island = island.copyOf(size) diff --git a/klyph-physics/src/nativeMain/kotlin/klyph/physics/RigidContacts.kt b/klyph-physics/src/nativeMain/kotlin/klyph/physics/RigidContacts.kt index e085e8e..d938596 100644 --- a/klyph-physics/src/nativeMain/kotlin/klyph/physics/RigidContacts.kt +++ b/klyph-physics/src/nativeMain/kotlin/klyph/physics/RigidContacts.kt @@ -398,9 +398,11 @@ internal class RigidContacts(private val world: PhysicsWorld) { // rebuilt, the edges are numbered afresh: an old edge contact's number means nothing now updateEdges(grid) val moving = grid.dynamic + val sensor = bodies.sensor + val passesSolids = bodies.passesSolids for (body in 0 until bodies.end) { if (!bodies.isDynamic(body)) continue - if (bodies.sensor[body] || bodies.mask[body] and PhysicsLayers.SOLIDS_BIT == 0) continue + if (sensor[body] || passesSolids[body]) continue // a sleeping body only wakes if a moving solid reaches it: the still ones it slept on if (bodies.asleep[body] && !touchesMovingSolid(body, moving)) continue val reach = bodies.reach[body] + MARGIN diff --git a/klyph-physics/src/nativeMain/kotlin/klyph/physics/SoftBodies.kt b/klyph-physics/src/nativeMain/kotlin/klyph/physics/SoftBodies.kt index 0822644..56a443f 100644 --- a/klyph-physics/src/nativeMain/kotlin/klyph/physics/SoftBodies.kt +++ b/klyph-physics/src/nativeMain/kotlin/klyph/physics/SoftBodies.kt @@ -176,10 +176,9 @@ public class SoftBodies internal constructor(private val world: PhysicsWorld) { internal fun hasSelfCollision(body: Int): Boolean = selfCollision[body] /** - * Puts every particle of [body] on [layers], colliding only with what is on a layer of [mask]: see - * [PhysicsLayers]. - * - * @throws IllegalArgumentException if [layers] is empty or holds [PhysicsLayers.SOLIDS]. + * Puts every particle of [body] on [layers], colliding with what is on a layer of [mask] and holds a + * layer of [body]'s in its own mask: see [PhysicsLayers]. The layers say nothing about the solids: + * see [setSolidCollision]. */ public fun setLayers(body: SoftBody, layers: CollisionLayers, mask: CollisionLayers) { setFilter(body.index, layers.bits, mask.bits) @@ -197,6 +196,22 @@ public class SoftBodies internal constructor(private val world: PhysicsWorld) { internal fun category(body: Int): Int = world.particles.category[core(body)] + /** + * Sets whether every particle of [body] is kept out of the solids, the [SolidGrid] and its moving + * solids. It is [SolidCollision.COLLIDE] by default; a [SolidCollision.PASS] body falls through the + * level. + * + * @sample samples.physics.SoftBodySamples.setSolidCollision + */ + public fun setSolidCollision(body: SoftBody, solidCollision: SolidCollision) { + val passes = solidCollision == SolidCollision.PASS + for (i in 0..ringCount(body.index)) world.particles.setPassesSolids(particle(body.index, i), passes) + } + + /** Returns whether [body] is kept out of the solids: see [setSolidCollision]. */ + public fun solidCollisionOf(body: SoftBody): SolidCollision = + if (world.particles.passesSolidsAt(core(body.index))) SolidCollision.PASS else SolidCollision.COLLIDE + internal fun mask(body: Int): Int = world.particles.mask[core(body)] /** diff --git a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Solids.kt b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Solids.kt index 171a8da..9e8b3f9 100644 --- a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Solids.kt +++ b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Solids.kt @@ -292,10 +292,10 @@ public class SolidGrid( if (nearVersion != version) refreshNear() val x = particles.x val y = particles.y - val filtered = particles.anyFiltered + val passing = particles.anyPassSolids val hasDynamic = dynamic.isNotEmpty() for (p in 0 until particles.end) { - if (particles.invMass[p] == 0f || filtered && particles.mask[p] and PhysicsLayers.SOLIDS_BIT == 0) continue + if (particles.invMass[p] == 0f || passing && particles.flags[p] and Particles.PASSES_SOLIDS != 0) continue // a soft body's particles look a little further, as near a solid they touch it, for events val r = particles.radius[p] + events.touchReach(particles.owner[p]) if (!isFarFromGrid(x[p], y[p], r)) collideGrid(particles, p, r, events, restingMove) diff --git a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Strands.kt b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Strands.kt index 42dbb51..e109daf 100644 --- a/klyph-physics/src/nativeMain/kotlin/klyph/physics/Strands.kt +++ b/klyph-physics/src/nativeMain/kotlin/klyph/physics/Strands.kt @@ -106,7 +106,7 @@ public enum class PinnedEnds { * pushed. With a [bendCompliance] it also resists folding (see [Constraints.bend]); without, it folds * anywhere. [pinned] says which ends are static, so it hangs from there. A link stretched past * [tearAt] times its rest length breaks (0, the default, never). Its particles are as round as - * [radius], and collide as [collision] says. Pass the arguments after the ends by name. + * [radius], and collide as [bodyCollision] says. Pass the arguments after the ends by name. * * @throws IllegalArgumentException if [segments] is less than 1, either end is not finite, the two * ends are the same point, any segment has length not finite and more than 0, [mass] is not more @@ -127,9 +127,9 @@ public fun PhysicsWorld.rope( pinned: PinnedEnds = PinnedEnds.START, tearAt: Float = 0f, radius: Float = 0f, - collision: ParticleCollision = ParticleCollision.SOLIDS, + bodyCollision: BodyCollision = BodyCollision.PASS, material: Material = Material.DEFAULT, -): Strand = strand(fromX, fromY, toX, toY, segments, mass, compliance, bendCompliance, pinned, tearAt, radius, collision, material, slack = true) +): Strand = strand(fromX, fromY, toX, toY, segments, mass, compliance, bendCompliance, pinned, tearAt, radius, bodyCollision, material, slack = true) /** * Adds a chain from ([fromX], [fromY]) to ([toX], [toY]), cut into [segments] links, and returns it: @@ -152,9 +152,9 @@ public fun PhysicsWorld.chain( pinned: PinnedEnds = PinnedEnds.START, tearAt: Float = 0f, radius: Float = 2f, - collision: ParticleCollision = ParticleCollision.SOLIDS, + bodyCollision: BodyCollision = BodyCollision.PASS, material: Material = Material.DEFAULT, -): Strand = strand(fromX, fromY, toX, toY, segments, mass, compliance, bendCompliance, pinned, tearAt, radius, collision, material, slack = false) +): Strand = strand(fromX, fromY, toX, toY, segments, mass, compliance, bendCompliance, pinned, tearAt, radius, bodyCollision, material, slack = false) private fun PhysicsWorld.strand( fromX: Float, @@ -168,7 +168,7 @@ private fun PhysicsWorld.strand( pinned: PinnedEnds, tearAt: Float, radius: Float, - collision: ParticleCollision, + bodyCollision: BodyCollision, material: Material, slack: Boolean, ): Strand { @@ -191,7 +191,7 @@ private fun PhysicsWorld.strand( fromY + (toY - fromY) * t, mass = if (isPinned) Particles.STATIC else mass, radius = radius, - collision = collision, + bodyCollision = bodyCollision, material = material, ) } @@ -238,7 +238,7 @@ public fun PhysicsWorld.cloth( bendCompliance: Float = 0.0001f, tearAt: Float = 0f, radius: Float = 0f, - collision: ParticleCollision = ParticleCollision.SOLIDS, + bodyCollision: BodyCollision = BodyCollision.PASS, material: Material = Material.DEFAULT, pinned: (column: Int, row: Int) -> Boolean = { _, row -> row == 0 }, ): Cloth { @@ -263,7 +263,7 @@ public fun PhysicsWorld.cloth( top + row * spacing, mass = if (pinned(col, row)) Particles.STATIC else mass, radius = radius, - collision = collision, + bodyCollision = bodyCollision, material = material, ) } diff --git a/klyph-physics/src/nativeTest/kotlin/klyph/physics/AllocationTest.kt b/klyph-physics/src/nativeTest/kotlin/klyph/physics/AllocationTest.kt index 4d20eb1..570e7ca 100644 --- a/klyph-physics/src/nativeTest/kotlin/klyph/physics/AllocationTest.kt +++ b/klyph-physics/src/nativeTest/kotlin/klyph/physics/AllocationTest.kt @@ -73,7 +73,7 @@ class AllocationTest { repeat(50) { ps.add(200f + it, 50f, radius = 2f) } // blobs and colliding grains, so the broadphase and body collisions run too repeat(6) { world.softBody(SoftBodyShape.semiDisc(13f, 14, 8, 34f), 150f + it * 30f, 100f) } - repeat(60) { ps.add(160f + it % 20 * 5f, 20f + it / 20 * 5f, radius = 2f, collision = ParticleCollision.EVERYTHING) } + repeat(60) { ps.add(160f + it % 20 * 5f, 20f + it / 20 * 5f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) } // and a hand dragging one of the blobs about world.grab(150f, 90f) var frame = 0 @@ -107,7 +107,7 @@ class AllocationTest { world.rigidBodies.setAngularVelocity(paddle, 1f) // blobs and grains among them, and a rope tied to a crate, so the soft-rigid coupling runs too repeat(4) { world.softBody(SoftBodyShape.semiDisc(13f, 14, 8, 34f), 200f + it * 60f, 440f) } - repeat(30) { world.particles.add(260f + it % 10 * 5f, 100f + it / 10 * 5f, radius = 2f, collision = ParticleCollision.EVERYTHING) } + repeat(30) { world.particles.add(260f + it % 10 * 5f, 100f + it / 10 * 5f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) } val knot = world.particles.add(100f, 330f) world.attach(knot, stack[0]) // and joints of every kind, with limits, motors and a weld that breaks diff --git a/klyph-physics/src/nativeTest/kotlin/klyph/physics/CollisionTest.kt b/klyph-physics/src/nativeTest/kotlin/klyph/physics/CollisionTest.kt index 8a1f09a..ff81f4e 100644 --- a/klyph-physics/src/nativeTest/kotlin/klyph/physics/CollisionTest.kt +++ b/klyph-physics/src/nativeTest/kotlin/klyph/physics/CollisionTest.kt @@ -111,7 +111,7 @@ class CollisionTest { @Test fun grainsOfSandPileUpInsteadOfPassingThroughEachOther() { world.solids = room(12, 20) - val grains = (0 until 200).map { ps.add(40f + (it % 20) * 6f, 40f + (it / 20) * 6f, radius = 2f, collision = ParticleCollision.EVERYTHING) } + val grains = (0 until 200).map { ps.add(40f + (it % 20) * 6f, 40f + (it / 20) * 6f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) } repeat(400) { world.step(dt) } var closest = Float.MAX_VALUE for (i in grains.indices) for (j in grains.indices) { @@ -134,7 +134,7 @@ class CollisionTest { world.solids = room(20, 12) val floor = 11 * tile val blob = box(160f, floor) - val grain = ps.add(160f, 40f, radius = 2f, collision = ParticleCollision.EVERYTHING) + val grain = ps.add(160f, 40f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) val ghost = ps.add(162f, 40f) repeat(180) { world.step(dt) } val ring = bodies.ringOf(blob) diff --git a/klyph-physics/src/nativeTest/kotlin/klyph/physics/CouplingTest.kt b/klyph-physics/src/nativeTest/kotlin/klyph/physics/CouplingTest.kt index 738dea4..d37a4fa 100644 --- a/klyph-physics/src/nativeTest/kotlin/klyph/physics/CouplingTest.kt +++ b/klyph-physics/src/nativeTest/kotlin/klyph/physics/CouplingTest.kt @@ -115,7 +115,7 @@ class CouplingTest { val bodies = world.rigidBodies val crate = world.rigidBody(Shape.box(20f, 20f), 300f, 200f) val mass = 1f / bodies.inverseMassOf(crate) - val ball = world.particles.add(200f, 200f, mass = mass, radius = 4f, collision = ParticleCollision.EVERYTHING) + val ball = world.particles.add(200f, 200f, mass = mass, radius = 4f, bodyCollision = BodyCollision.COLLIDE) world.setVelocity(ball, 300f, 0f) repeat(60) { world.step(dt) } assertTrue(bodies.velocityXOf(crate) > 100f, "the crate was pushed: ${bodies.velocityXOf(crate)}") @@ -131,7 +131,7 @@ class CouplingTest { val world = PhysicsWorld(PhysicsConfig(gravity = Vec2.ZERO, damping = 0f)) val bodies = world.rigidBodies val crate = world.rigidBody(Shape.box(20f, 40f), 300f, 200f) - val ball = world.particles.add(200f, 185f, mass = 20f, radius = 2f, collision = ParticleCollision.EVERYTHING) + val ball = world.particles.add(200f, 185f, mass = 20f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) world.setVelocity(ball, 300f, 0f) repeat(60) { world.step(dt) } assertTrue(bodies.angularVelocityOf(crate) > 0.2f, "hit above its middle, it turns clockwise: ${bodies.angularVelocityOf(crate)}") @@ -141,7 +141,7 @@ class CouplingTest { fun grainsPouredOnACrateHeapUpOnIt() { val world = room() world.rigidBody(Shape.box(100f, 20f), 320f, floor - 10f, kind = BodyKind.STATIC) - val grains = List(60) { world.particles.add(300f + (it % 10) * 4f, 300f - (it / 10) * 4f, radius = 2f, collision = ParticleCollision.EVERYTHING) } + val grains = List(60) { world.particles.add(300f + (it % 10) * 4f, 300f - (it / 10) * 4f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) } repeat(300) { world.step(dt) } val ps = world.particles var on = 0 @@ -248,9 +248,9 @@ class CouplingTest { 300f, kind = BodyKind.STATIC, ) - val grain = world.particles.add(470f, 250f, radius = 2f, collision = ParticleCollision.EVERYTHING) + val grain = world.particles.add(470f, 250f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) val blob = world.softBody(dome, 170f, 250f) - val missed = world.particles.add(320f, 250f, radius = 2f, collision = ParticleCollision.EVERYTHING) + val missed = world.particles.add(320f, 250f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) repeat(120) { world.step(dt) } assertEquals(300f - 5f - 2f, world.particles.yOf(grain), 0.5f, "the grain rests on the right shelf") assertTrue(topOf(world, blob) < 295f, "the blob rests on the left one: its top is at ${topOf(world, blob)}") @@ -264,10 +264,10 @@ class CouplingTest { world.rigidBody(Shape.circle(10f), 100f, 100f, kind = BodyKind.STATIC) // Rigid box reaches [89, 111] (reach 10 + MARGIN 1). // Distant grain and soft body are far outside it and should not be filed. - world.particles.add(500f, 500f, radius = 2f, collision = ParticleCollision.EVERYTHING) + world.particles.add(500f, 500f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) world.softBody(dome, 500f, 500f) // A grain whose radius + MARGIN reaches into [89, 111] (at x = 113.5, radius 2 -> left = 110.5 <= 111). - world.particles.add(113.5f, 100f, radius = 2f, collision = ParticleCollision.EVERYTHING) + world.particles.add(113.5f, 100f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) val coupling = Coupling(world) coupling.beginStep(dt) assertEquals(2, coupling.broadphase.count, "only the rigid body and the nearby grain are filed") diff --git a/klyph-physics/src/nativeTest/kotlin/klyph/physics/FiltersTest.kt b/klyph-physics/src/nativeTest/kotlin/klyph/physics/FiltersTest.kt index 2589982..a16fa5a 100644 --- a/klyph-physics/src/nativeTest/kotlin/klyph/physics/FiltersTest.kt +++ b/klyph-physics/src/nativeTest/kotlin/klyph/physics/FiltersTest.kt @@ -5,7 +5,6 @@ import klyph.math.Vec2 import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -37,7 +36,6 @@ class FiltersTest { val BLUE = CollisionLayers.of(2) val GATE = CollisionLayers.of(3) val NOT_GATE = allBut(GATE) - val NOT_SOLIDS = allBut(PhysicsLayers.SOLIDS) /** Every layer but [layers]. */ fun allBut(layers: CollisionLayers) = CollisionLayers(CollisionLayers.ALL.bits and layers.bits.inv()) @@ -58,11 +56,11 @@ class FiltersTest { repeat(80) { val shape = if (it % 2 == 0) Shape.box(10f + random.nextFloat() * 20f, 10f + random.nextFloat() * 20f) else Shape.circle(5f + random.nextFloat() * 10f) val b = world.rigidBody(shape, 60f + random.nextFloat() * 520f, 40f + random.nextFloat() * 300f, angle = random.nextFloat() * 6f) - // a mask of any of the three, but never nothing, and always the solids so nothing falls out + // a mask of any of the three, but never nothing; the level holds them whatever the mask var mask = CollisionLayers.NONE for (c in categories) if (random.nextBoolean()) mask = mask + c if (mask == CollisionLayers.NONE) mask = categories[random.nextInt(3)] - bodies.setLayers(b, categories[random.nextInt(3)], mask + PhysicsLayers.SOLIDS) + bodies.setLayers(b, categories[random.nextInt(3)], mask) } var contacts = 0 steps(world, 4f) { @@ -101,7 +99,7 @@ class FiltersTest { world.softBodies.setLayers(through, RED, NOT_GATE) val stopped = world.softBody(TestBodies.dome(), 440f, 250f) val ps = world.particles - val grain = ps.add(320f, 200f, radius = 2f, collision = ParticleCollision.EVERYTHING) + val grain = ps.add(320f, 200f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) ps.setLayers(grain, RED, NOT_GATE) steps(world, 3f) assertTrue(world.softBodies.maxYOf(through) > floor - 3f, "the red blob reached the floor: ${world.softBodies.maxYOf(through)}") @@ -123,20 +121,40 @@ class FiltersTest { } @Test - fun withoutTheSolidsBitThingsFallThroughTheLevel() { + fun passingSolidsThingsFallThroughTheLevel() { val world = room() val box = world.rigidBody(Shape.box(20f, 20f), 200f, 300f) - world.rigidBodies.setLayers(box, CollisionLayers.DEFAULT, NOT_SOLIDS) + world.rigidBodies.setSolidCollision(box, SolidCollision.PASS) val blob = world.softBody(TestBodies.dome(), 320f, 330f) - world.softBodies.setLayers(blob, CollisionLayers.DEFAULT, NOT_SOLIDS) - val grain = world.particles.add(450f, 300f, radius = 2f, collision = ParticleCollision.EVERYTHING) - world.particles.setLayers(grain, CollisionLayers.DEFAULT, NOT_SOLIDS) + world.softBodies.setSolidCollision(blob, SolidCollision.PASS) + val grain = world.particles.add(450f, 300f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) + world.particles.setSolidCollision(grain, SolidCollision.PASS) + assertEquals(SolidCollision.PASS, world.rigidBodies.solidCollisionOf(box)) + assertEquals(SolidCollision.PASS, world.softBodies.solidCollisionOf(blob)) + assertEquals(SolidCollision.PASS, world.particles.solidCollisionOf(grain)) steps(world, 1.5f) assertTrue(world.rigidBodies.yOf(box) > 30 * tile, "the box fell out of the bottom: ${world.rigidBodies.yOf(box)}") assertTrue(world.softBodies.minYOf(blob) > 30 * tile, "the blob fell out of the bottom: ${world.softBodies.minYOf(blob)}") assertTrue(world.particles.yOf(grain) > 30 * tile, "the grain fell out of the bottom: ${world.particles.yOf(grain)}") } + @Test + fun aSoftBodySetBackToCollideLandsOnTheFloor() { + val world = room() + val blobs = world.softBodies + val ghost = world.softBody(TestBodies.dome(), 200f, floor - 120f) + val lander = world.softBody(TestBodies.dome(), 440f, floor - 120f) + blobs.setSolidCollision(ghost, SolidCollision.PASS) + blobs.setSolidCollision(lander, SolidCollision.PASS) + steps(world, 0.2f) + assertTrue(blobs.maxYOf(lander) < floor - 20f, "it is still above the floor: ${blobs.maxYOf(lander)}") + blobs.setSolidCollision(lander, SolidCollision.COLLIDE) + assertEquals(SolidCollision.COLLIDE, blobs.solidCollisionOf(lander)) + steps(world, 2f) + assertEquals(floor, blobs.maxYOf(lander), 3f, "every particle of it is kept out of the floor again") + assertTrue(blobs.minYOf(ghost) > 30 * tile, "the other fell out of the bottom: ${blobs.minYOf(ghost)}") + } + @Test fun aBulletPassesAWallItFiltersOut() { val world = PhysicsWorld(PhysicsConfig(gravity = Vec2(0f, 0f))) @@ -152,13 +170,150 @@ class FiltersTest { } @Test - fun layersAreOneOrMoreOfLayersZeroToTwentyNine() { + fun narrowMasksKeepThingsInTheLevel() { + val world = room() + val box = world.rigidBody(Shape.box(20f, 20f), 200f, 300f) + world.rigidBodies.setLayers(box, RED, RED) + val blob = world.softBody(TestBodies.dome(), 320f, 330f) + world.softBodies.setLayers(blob, RED, CollisionLayers.NONE) + val grain = world.particles.add(450f, 300f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) + world.particles.setLayers(grain, RED, BLUE) + steps(world, 1.5f) + assertEquals(floor - 10f, world.rigidBodies.yOf(box), 1f, "the box landed on the floor") + assertTrue(world.softBodies.maxYOf(blob) < floor + 3f, "the blob landed on the floor: ${world.softBodies.maxYOf(blob)}") + assertTrue(world.particles.yOf(grain) < floor, "the grain landed on the floor: ${world.particles.yOf(grain)}") + } + + @Test + fun layersAreAnyOfAllThirtyTwoOrNone() { val world = room() val b = world.rigidBody(Shape.circle(5f), 100f, 100f) val p = world.particles.add(100f, 100f) - assertFailsWith { world.rigidBodies.setLayers(b, CollisionLayers.NONE, CollisionLayers.ALL) } - assertFailsWith { world.rigidBodies.setLayers(b, PhysicsLayers.SOLIDS, CollisionLayers.ALL) } - assertFailsWith { world.particles.setLayers(p, CollisionLayers.of(31), CollisionLayers.ALL) } + world.rigidBodies.setLayers(b, CollisionLayers.of(30), CollisionLayers.ALL) + world.particles.setLayers(p, CollisionLayers.of(31), CollisionLayers.ALL) + assertEquals(CollisionLayers.of(30), world.rigidBodies.layersOf(b)) + assertEquals(CollisionLayers.of(31), world.particles.layersOf(p)) + world.rigidBodies.setLayers(b, CollisionLayers.NONE, CollisionLayers.ALL) + world.particles.setLayers(p, CollisionLayers.NONE, CollisionLayers.ALL) + assertEquals(CollisionLayers.NONE, world.rigidBodies.layersOf(b)) + assertEquals(CollisionLayers.NONE, world.particles.layersOf(p)) + } + + @Test + fun aBodyOnNoLayerPassesOtherBodiesAndStandsOnTheFloor() { + val world = room() + val bodies = world.rigidBodies + val below = world.rigidBody(Shape.box(40f, 20f), 320f, floor - 10f) + val above = world.rigidBody(Shape.box(20f, 20f), 320f, floor - 60f) + bodies.setLayers(above, CollisionLayers.NONE, CollisionLayers.ALL) + val blob = world.softBody(TestBodies.dome(), 480f, floor - 60f) + world.softBodies.setLayers(blob, CollisionLayers.NONE, CollisionLayers.ALL) + steps(world, 2f) + assertEquals(floor - 10f, bodies.yOf(below), 1f, "the lower box stands on the floor") + assertEquals(floor - 10f, bodies.yOf(above), 1f, "the upper one fell through it to the floor") + assertEquals(floor, world.softBodies.maxYOf(blob), 3f, "the blob stands on the floor") + } + + @Test + fun bodiesOnLayersThirtyAndThirtyOneStandOnTheFloorAndOnEachOther() { + val world = room() + val bodies = world.rigidBodies + val below = world.rigidBody(Shape.box(40f, 20f), 320f, floor - 10f) + bodies.setLayers(below, CollisionLayers.of(30), CollisionLayers.of(31)) + val above = world.rigidBody(Shape.box(20f, 20f), 320f, floor - 60f) + bodies.setLayers(above, CollisionLayers.of(31), CollisionLayers.of(30)) + steps(world, 2f) + assertEquals(floor - 10f, bodies.yOf(below), 1f, "the lower box stands on the floor") + assertEquals(floor - 30f, bodies.yOf(above), 1f, "the upper one stands on it") + } + + // --- the level --- + + @Test + fun settingTheSolidCollisionAgainLeavesABodyAsleep() { + val world = room() + val bodies = world.rigidBodies + val crate = world.rigidBody(Shape.box(20f, 20f), 320f, floor - 10f) + steps(world, 3f) + assertTrue(bodies.isAsleep(crate), "the crate fell asleep on the floor") + bodies.setSolidCollision(crate, SolidCollision.COLLIDE) + assertTrue(bodies.isAsleep(crate), "setting what it already was leaves it asleep") + bodies.setSolidCollision(crate, SolidCollision.PASS) + assertFalse(bodies.isAsleep(crate), "a change wakes it") + steps(world, 1.5f) + assertTrue(bodies.yOf(crate) > 30 * tile, "and it falls out of the level: ${bodies.yOf(crate)}") + } + + @Test + fun aSleepingBodySetBackToCollideInTheFloorIsPushedOut() { + val world = room(PhysicsConfig(gravity = Vec2(0f, 0f))) + val bodies = world.rigidBodies + // sunk 4 units into the floor; one sunk most of the way in stays there, as it would had it never passed + val crate = world.rigidBody(Shape.box(20f, 20f), 320f, floor - 6f) + bodies.setSolidCollision(crate, SolidCollision.PASS) + steps(world, 3f) + assertTrue(bodies.isAsleep(crate), "the crate fell asleep in the floor") + bodies.setSolidCollision(crate, SolidCollision.COLLIDE) + assertFalse(bodies.isAsleep(crate), "a change wakes it") + steps(world, 1f) + assertTrue(bodies.yOf(crate) <= floor - 10f + 1f, "it was pushed out of the floor: ${bodies.yOf(crate)}") + } + + @Test + fun bulletsThatPassSolidsCrossAWallOfThem() { + val world = room(PhysicsConfig(gravity = Vec2(0f, 0f))) + for (r in 0 until 28) world.solids!!.fill(20, r) + val bodies = world.rigidBodies + val stopped = world.rigidBody(Shape.circle(2f), 100f, 200f) + val crossed = world.rigidBody(Shape.circle(2f), 100f, 260f) + bodies.setSolidCollision(crossed, SolidCollision.PASS) + val stoppedGrain = world.particles.add(100f, 320f, radius = 1f) + val crossedGrain = world.particles.add(100f, 380f, radius = 1f) + world.particles.setSolidCollision(crossedGrain, SolidCollision.PASS) + for (b in listOf(stopped, crossed)) { + bodies.setMotion(b, Motion.BULLET) + bodies.setVelocity(b, vx = 6_000f, vy = 0f) + } + for (p in listOf(stoppedGrain, crossedGrain)) { + world.particles.setMotion(p, Motion.BULLET) + world.setVelocity(p, vx = 6_000f, vy = 0f) + } + repeat(3) { world.step(dt) } + val wall = 20 * tile + assertTrue(bodies.xOf(stopped) < wall, "the bullet stopped at the wall: ${bodies.xOf(stopped)}") + assertTrue(bodies.xOf(crossed) > wall + tile, "the one passing solids went through: ${bodies.xOf(crossed)}") + assertTrue(world.particles.xOf(stoppedGrain) < wall, "the bullet grain stopped at the wall: ${world.particles.xOf(stoppedGrain)}") + val crossedX = world.particles.xOf(crossedGrain) + assertTrue(crossedX > wall + tile, "the one passing solids went through: $crossedX") + } + + @Test + fun particlesThatPassSolidsFallThroughAMovingSolid() { + val world = room() + world.solids!!.add(Solid.moving(left = 280f, top = 200f, right = 360f, bottom = 216f)) + val held = world.particles.add(300f, 150f, radius = 2f) + val passed = world.particles.add(340f, 150f, radius = 2f) + world.particles.setSolidCollision(passed, SolidCollision.PASS) + steps(world, 1f) + assertTrue(world.particles.yOf(held) < 200f, "one rests on the moving solid: ${world.particles.yOf(held)}") + assertTrue(world.particles.yOf(passed) > 216f, "the other fell through it: ${world.particles.yOf(passed)}") + } + + @Test + fun aSlotHandedOutAgainCollidesWithTheSolids() { + val world = room() + val box = world.rigidBody(Shape.box(20f, 20f), 200f, 300f) + world.rigidBodies.setSolidCollision(box, SolidCollision.PASS) + world.rigidBodies.remove(box) + val next = world.rigidBody(Shape.box(20f, 20f), 200f, 300f) + assertEquals(box, next, "the new box took the old one's slot") + assertEquals(SolidCollision.COLLIDE, world.rigidBodies.solidCollisionOf(next)) + val drop = world.particles.add(300f, 300f) + world.particles.setSolidCollision(drop, SolidCollision.PASS) + world.particles.remove(drop) + val nextDrop = world.particles.add(300f, 300f) + assertEquals(drop, nextDrop, "the new particle took the old one's slot") + assertEquals(SolidCollision.COLLIDE, world.particles.solidCollisionOf(nextDrop)) } // --- sensors --- @@ -197,7 +352,7 @@ class FiltersTest { val world = room() sensor(world, 320f, 250f) val blob = world.softBody(TestBodies.dome(), 280f, 180f) - val grain = world.particles.add(380f, 150f, radius = 2f, collision = ParticleCollision.EVERYTHING) + val grain = world.particles.add(380f, 150f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) val log = sensorLog(world, 2f) assertEquals(1, log.count { it == "in ${TouchSide.of(blob)}" }, "$log") assertEquals(1, log.count { it == "out ${TouchSide.of(blob)}" }, "$log") @@ -462,12 +617,12 @@ class FiltersTest { fun removingAParticleInASensorAndReusingItsSlotReportsExitAndEntry() { val world = room() val s = sensor(world, 320f, floor - 20f) - val p = world.particles.add(320f, floor - 20f, mass = Particles.STATIC, radius = 3f, collision = ParticleCollision.EVERYTHING) + val p = world.particles.add(320f, floor - 20f, mass = Particles.STATIC, radius = 3f, bodyCollision = BodyCollision.COLLIDE) world.step(dt) assertTrue(world.events.sensorsEntered.has(TouchSide.of(s), TouchSide.of(p))) world.particles.remove(p) - val q = world.particles.add(320f, floor - 20f, mass = Particles.STATIC, radius = 3f, collision = ParticleCollision.EVERYTHING) + val q = world.particles.add(320f, floor - 20f, mass = Particles.STATIC, radius = 3f, bodyCollision = BodyCollision.COLLIDE) assertEquals(p, q, "q reuses p's slot") world.step(dt) diff --git a/klyph-physics/src/nativeTest/kotlin/klyph/physics/ParticlesTest.kt b/klyph-physics/src/nativeTest/kotlin/klyph/physics/ParticlesTest.kt index 2a8f113..29a8ad1 100644 --- a/klyph-physics/src/nativeTest/kotlin/klyph/physics/ParticlesTest.kt +++ b/klyph-physics/src/nativeTest/kotlin/klyph/physics/ParticlesTest.kt @@ -123,9 +123,9 @@ class ParticlesTest { @Test fun aGrainIsAliveCollidesWithEverythingAndBelongsToNoSoftBody() { - val grain = particles.add(0f, 0f, radius = 1f, collision = ParticleCollision.EVERYTHING) + val grain = particles.add(0f, 0f, radius = 1f, bodyCollision = BodyCollision.COLLIDE) val spark = particles.add(1f, 0f, radius = 1f) - val skin = particles.add(2f, 0f, radius = 1f, collision = ParticleCollision.EVERYTHING) + val skin = particles.add(2f, 0f, radius = 1f, bodyCollision = BodyCollision.COLLIDE) particles.owner[skin.index] = 0 assertTrue(particles.isGrain(grain.index)) assertFalse(particles.isGrain(spark.index)) diff --git a/klyph-physics/src/nativeTest/kotlin/klyph/physics/PhysicsWorldTest.kt b/klyph-physics/src/nativeTest/kotlin/klyph/physics/PhysicsWorldTest.kt index 460f18b..97dcd12 100644 --- a/klyph-physics/src/nativeTest/kotlin/klyph/physics/PhysicsWorldTest.kt +++ b/klyph-physics/src/nativeTest/kotlin/klyph/physics/PhysicsWorldTest.kt @@ -95,7 +95,7 @@ class PhysicsWorldTest { val world = PhysicsWorld() world.solids = TestBodies.grid().apply { for (c in 0 until columns) fill(c, 9) } world.softBody(TestBodies.dome(), centerX = 80f, baseY = 100f) - val p = world.particles.add(40f, 20f, radius = 2f, collision = ParticleCollision.EVERYTHING) + val p = world.particles.add(40f, 20f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) world.setVelocity(p, 120f, -50f) return world } diff --git a/klyph-physics/src/nativeTest/kotlin/klyph/physics/ReadoutsTest.kt b/klyph-physics/src/nativeTest/kotlin/klyph/physics/ReadoutsTest.kt index 81084d1..cb456ee 100644 --- a/klyph-physics/src/nativeTest/kotlin/klyph/physics/ReadoutsTest.kt +++ b/klyph-physics/src/nativeTest/kotlin/klyph/physics/ReadoutsTest.kt @@ -45,9 +45,9 @@ class ReadoutsTest { fun twoParticlesThatMeetTouchEachOtherAndAFreeOneTouchesNothing() { val world = PhysicsWorld(PhysicsConfig(gravity = Vec2.ZERO)) val ps = world.particles - val a = ps.add(100f, 100f, radius = 4f, collision = ParticleCollision.EVERYTHING) - val b = ps.add(106f, 100f, radius = 4f, collision = ParticleCollision.EVERYTHING) - val free = ps.add(300f, 300f, radius = 4f, collision = ParticleCollision.EVERYTHING) + val a = ps.add(100f, 100f, radius = 4f, bodyCollision = BodyCollision.COLLIDE) + val b = ps.add(106f, 100f, radius = 4f, bodyCollision = BodyCollision.COLLIDE) + val free = ps.add(300f, 300f, radius = 4f, bodyCollision = BodyCollision.COLLIDE) world.step(dt) assertTrue(world.events.isTouching(a) || world.events.isTouching(b)) val touched = if (world.events.isTouching(b)) world.events.touchedParticleOrNull(b) else world.events.touchedParticleOrNull(a) @@ -80,7 +80,7 @@ class ReadoutsTest { fun theBroadphaseHoldsABoxForEveryBodyAndEveryCollidingParticle() { val world = room() world.softBody(TestBodies.dome(), 80f, 100f) - world.particles.add(120f, 60f, radius = 2f, collision = ParticleCollision.EVERYTHING) + world.particles.add(120f, 60f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) world.particles.add(130f, 60f, radius = 2f) world.step(dt) assertEquals(2, world.broadphase.count, "the body and the colliding particle, not the plain one") diff --git a/klyph-physics/src/nativeTest/kotlin/klyph/physics/ShortcutsTest.kt b/klyph-physics/src/nativeTest/kotlin/klyph/physics/ShortcutsTest.kt index ccea4ef..4a3c4a3 100644 --- a/klyph-physics/src/nativeTest/kotlin/klyph/physics/ShortcutsTest.kt +++ b/klyph-physics/src/nativeTest/kotlin/klyph/physics/ShortcutsTest.kt @@ -87,8 +87,8 @@ class ShortcutsTest { // 24 apart, closing at 1200 units a second: 20 a step, 2.5 a substep (no more than they're // wide, or they'd hop past each other), so they meet in the second step, though their boxes and // circles are apart at its start but for how far they move - val a = ps.add(100f, 100f, radius = 1.25f, collision = ParticleCollision.EVERYTHING) - val b = ps.add(124f, 100f, radius = 1.25f, collision = ParticleCollision.EVERYTHING) + val a = ps.add(100f, 100f, radius = 1.25f, bodyCollision = BodyCollision.COLLIDE) + val b = ps.add(124f, 100f, radius = 1.25f, bodyCollision = BodyCollision.COLLIDE) world.setVelocity(a, 600f, 0f) world.setVelocity(b, -600f, 0f) repeat(3) { world.step(dt) } @@ -101,7 +101,7 @@ class ShortcutsTest { val world = room(PhysicsConfig(iterations = 3)) val random = Random(5) val grains = ArrayList() - repeat(800) { grains += world.particles.add(150f + random.nextFloat() * 300f, 100f + random.nextFloat() * 300f, radius = 1.25f, collision = ParticleCollision.EVERYTHING) } + repeat(800) { grains += world.particles.add(150f + random.nextFloat() * 300f, 100f + random.nextFloat() * 300f, radius = 1.25f, bodyCollision = BodyCollision.COLLIDE) } repeat(180) { world.step(dt) } val ps = world.particles // nothing through anything: every two grains at least nearly their radii apart, none out of the room diff --git a/klyph/src/nativeMain/kotlin/klyph/collision/CollisionLayers.kt b/klyph/src/nativeMain/kotlin/klyph/collision/CollisionLayers.kt index 8d3bd75..cc68e3c 100644 --- a/klyph/src/nativeMain/kotlin/klyph/collision/CollisionLayers.kt +++ b/klyph/src/nativeMain/kotlin/klyph/collision/CollisionLayers.kt @@ -4,6 +4,10 @@ package klyph.collision * A set of up to 32 collision layers, numbered 0 to 31, one bit each. A [Collider] uses one set * for the layers it is on and another for the layers it hits. * + * [Collisions] reports a pair when either collider's mask holds a layer of the other. The + * `klyph-physics` module reads the same sets with a stricter rule: two of its bodies collide only + * when each one's mask holds a layer of the other, so either can refuse. + * * Build a set from single layers with [of] and [plus]: * `CollisionLayers.of(1) + CollisionLayers.of(2)`. [bits] holds layer `i` in bit `i`. * diff --git a/samples/src/nativeTest/kotlin/samples/guide/Physics.kt b/samples/src/nativeTest/kotlin/samples/guide/Physics.kt index a5156af..5c9c332 100644 --- a/samples/src/nativeTest/kotlin/samples/guide/Physics.kt +++ b/samples/src/nativeTest/kotlin/samples/guide/Physics.kt @@ -15,7 +15,7 @@ import klyph.physics.JointEnd import klyph.physics.Material import klyph.physics.Motion import klyph.physics.Overlaps -import klyph.physics.ParticleCollision +import klyph.physics.BodyCollision import klyph.physics.PhysicsBody import klyph.physics.PhysicsConfig import klyph.physics.PhysicsLayers @@ -167,10 +167,10 @@ class Physics { // snippet: layers 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) diff --git a/samples/src/nativeTest/kotlin/samples/physics/ParticleSamples.kt b/samples/src/nativeTest/kotlin/samples/physics/ParticleSamples.kt index 4cbf29b..08fadd4 100644 --- a/samples/src/nativeTest/kotlin/samples/physics/ParticleSamples.kt +++ b/samples/src/nativeTest/kotlin/samples/physics/ParticleSamples.kt @@ -1,9 +1,11 @@ package samples.physics import klyph.collision.CollisionLayers +import klyph.physics.BodyCollision import klyph.physics.Motion -import klyph.physics.ParticleCollision import klyph.physics.PhysicsWorld +import klyph.physics.SolidCollision +import klyph.physics.SolidGrid import samples.Sample import samples.assertPrints import kotlin.test.assertTrue @@ -15,12 +17,12 @@ class ParticleSamples { val world = PhysicsWorld() val spark = world.particles.add(x = 10f, y = 20f) // A grain of sand: round, and pushed by everything else that collides. - val grain = world.particles.add(x = 30f, y = 20f, mass = 0.5f, radius = 2f, collision = ParticleCollision.EVERYTHING) + val grain = world.particles.add(x = 30f, y = 20f, mass = 0.5f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) assertPrints(world.particles.size, "2") assertPrints(world.particles.xOf(spark), "10.0") assertPrints(world.particles.inverseMassOf(grain), "2.0") - assertPrints(world.particles.collisionOf(grain), "EVERYTHING") + assertPrints(world.particles.bodyCollisionOf(grain), "COLLIDE") } @Sample @@ -56,10 +58,27 @@ class ParticleSamples { val world = PhysicsWorld() val player = CollisionLayers.of(0) val enemy = CollisionLayers.of(1) - val grain = world.particles.add(x = 0f, y = 0f, radius = 2f, collision = ParticleCollision.EVERYTHING) + val grain = world.particles.add(x = 0f, y = 0f, radius = 2f, bodyCollision = BodyCollision.COLLIDE) // On the enemy layer, colliding with the player only. world.particles.setLayers(grain, layers = enemy, mask = player) assertPrints(world.particles.layersOf(grain) == enemy, "true") assertPrints(world.particles.maskOf(grain) == player, "true") } + + @Sample + fun setSolidCollision() { + val world = PhysicsWorld() + // A floor of 16-unit tiles along row 9, its top at y = 144. + val grid = SolidGrid(columns = 20, rows = 10, tileSize = 16f) + for (column in 0 until 20) grid.fill(column, 9) + world.solids = grid + val drop = world.particles.add(x = 160f, y = 100f, radius = 2f) + world.particles.setSolidCollision(drop, SolidCollision.PASS) + assertPrints(world.particles.solidCollisionOf(drop), "PASS") + + repeat(60) { world.step(1.seconds / 60) } + + // It fell through the floor. + assertTrue(world.particles.yOf(drop) > 160f) + } } diff --git a/samples/src/nativeTest/kotlin/samples/physics/RigidBodySamples.kt b/samples/src/nativeTest/kotlin/samples/physics/RigidBodySamples.kt index 861d92b..54edb4a 100644 --- a/samples/src/nativeTest/kotlin/samples/physics/RigidBodySamples.kt +++ b/samples/src/nativeTest/kotlin/samples/physics/RigidBodySamples.kt @@ -8,6 +8,8 @@ import klyph.physics.Motion import klyph.physics.PhysicsLayers import klyph.physics.PhysicsWorld import klyph.physics.Shape +import klyph.physics.SolidCollision +import klyph.physics.SolidGrid import klyph.physics.rigidBody import samples.Sample import samples.assertPrints @@ -108,11 +110,28 @@ class RigidBodySamples { val world = PhysicsWorld() val ghosts = CollisionLayers.of(3) val ghost = world.rigidBody(Shape.circle(8f), x = 0f, y = 0f) - // On its own layer, and colliding with nothing but the level. - world.rigidBodies.setLayers(ghost, layers = ghosts, mask = PhysicsLayers.SOLIDS) + // On its own layer, and colliding with no other body. The level still holds it up. + world.rigidBodies.setLayers(ghost, layers = ghosts, mask = CollisionLayers.NONE) assertPrints(world.rigidBodies.layersOf(ghost) == ghosts, "true") } + @Sample + fun setSolidCollision() { + val world = PhysicsWorld() + // A floor of 16-unit tiles along row 9, its top at y = 144. + val grid = SolidGrid(columns = 20, rows = 10, tileSize = 16f) + for (column in 0 until 20) grid.fill(column, 9) + world.solids = grid + val ghost = world.rigidBody(Shape.box(20f, 20f), x = 160f, y = 100f) + world.rigidBodies.setSolidCollision(ghost, SolidCollision.PASS) + assertPrints(world.rigidBodies.solidCollisionOf(ghost), "PASS") + + repeat(60) { world.step(1.seconds / 60) } + + // It fell through the floor. + assertTrue(world.rigidBodies.yOf(ghost) > 160f) + } + @Sample fun wake() { val world = PhysicsWorld() @@ -149,9 +168,9 @@ class LayerSamples { val player = CollisionLayers.of(0) val coins = CollisionLayers.of(1) val coin = world.rigidBody(Shape.circle(4f), x = 0f, y = 0f) - // Coins collide with the player and the level, not with each other. - world.rigidBodies.setLayers(coin, layers = coins, mask = player + PhysicsLayers.SOLIDS) - assertPrints(PhysicsLayers.collide(coins, player + PhysicsLayers.SOLIDS, coins, player + PhysicsLayers.SOLIDS), "false") + // Coins collide with the player, not with each other. The level holds them whatever the mask. + world.rigidBodies.setLayers(coin, layers = coins, mask = player) + assertPrints(PhysicsLayers.collide(coins, player, coins, player), "false") assertPrints(PhysicsLayers.collide(coins, player, player, CollisionLayers.ALL), "true") } } diff --git a/samples/src/nativeTest/kotlin/samples/physics/SoftBodySamples.kt b/samples/src/nativeTest/kotlin/samples/physics/SoftBodySamples.kt index cf3a861..d53fd13 100644 --- a/samples/src/nativeTest/kotlin/samples/physics/SoftBodySamples.kt +++ b/samples/src/nativeTest/kotlin/samples/physics/SoftBodySamples.kt @@ -4,12 +4,14 @@ import klyph.physics.PhysicsWorld import klyph.physics.SelfCollision import klyph.physics.SoftBodyShape import klyph.physics.SoftBodyTuning +import klyph.physics.SolidCollision import klyph.physics.SolidGrid import klyph.physics.SolidTags import klyph.physics.centerXOf import klyph.physics.floorTagsOf import klyph.physics.isOnFloor import klyph.physics.maxYOf +import klyph.physics.minYOf import klyph.physics.meanVelocityXOf import klyph.physics.softBody import samples.Sample @@ -95,6 +97,23 @@ class SoftBodySamples { assertPrints(world.softBodies.selfCollisionOf(sheet), "COLLIDE") } + @Sample + fun setSolidCollision() { + val world = PhysicsWorld() + // A floor of 16-unit tiles along row 9, its top at y = 144. + val grid = SolidGrid(columns = 20, rows = 10, tileSize = 16f) + for (column in 0 until 20) grid.fill(column, 9) + world.solids = grid + val slime = world.softBody(SoftBodyShape.semiDisc(13f, 14, 8, coreMass = 34f), centerX = 160f, baseY = 100f) + world.softBodies.setSolidCollision(slime, SolidCollision.PASS) + assertPrints(world.softBodies.solidCollisionOf(slime), "PASS") + + repeat(60) { world.step(1.seconds / 60) } + + // All of it fell through the floor. + assertTrue(world.softBodies.minYOf(slime) > 160f) + } + @Sample fun floorTagsOf() { val ice = SolidTags.of(0)