physics

Garnet Physics

Fixed-step 2D rigid body simulation backed by the vendored Box2D 3.1.1 runtime. This shard can run headlessly and has no scene or renderer dependency. Build its static library once before compiling a Crystal program.

cmake -S physics/native -B physics/native/build -DCMAKE_BUILD_TYPE=Release
cmake --build physics/native/build --parallel
require "garnet-physics"

alias P = Garnet::Physics
world = P::World.new
begin
  floor = world.box(:static, half: P::Vec2.new(10, 0.5), at: P::Vec2.new(0, 5))
  ball = world.circle(:dynamic, 0.5, at: P::Vec2.zero)
  frame = world.step
  puts frame.pose(ball).position
ensure
  world.close
end

A world uses meters, radians, seconds and Y-down coordinates, so World::DEFAULT_GRAVITY is +9.81 on Y ("down" on screen). The 3D shard is Y-up and uses -9.81; both defaults point down in their own convention. Advance a world on the thread that created it.

Physics::Vec2 is an alias of Garnet::Math::Vec2, so poses, scene transforms and input vectors share one type and its arithmetic (+ - * /, dot, length, normalized, lerp, rotate). Sizes, angles, lengths and material properties accept any Number.

Shapes

Method Shape value Measurements
box(kind, half:, at:) BoxShape.half(half) half extents, like 3D
box(kind, position, width, height) BoxShape.new(width, height) full extents (original form)
circle(kind, radius, at:) CircleShape.new(radius) radius
capsule(kind, half_height, radius, at:) CapsuleShape.new(half_height, radius) segment along local Y, like 3D
polygon(kind, points, at:, radius:) PolygonShape.new(points) 3–8 points; the convex hull is used

compound(kind, shapes, at:, angle:) builds one body from any mix of Shape values, each with its own offset: and angle:. Every shape takes density:, friction:, restitution:, category:, mask: and sensor:. Degenerate geometry raises ArgumentError.

Collision layers are UInt32 bitmasks (Physics::Bits), the same width as garnet-physics3d. Bodies collide when each one's category intersects the other's mask. UInt64::MAX is still accepted as "all layers"; other values above UInt32::MAX raise ArgumentError.

Stepping, contacts and triggers

  • advance steps once without copying poses. Read pose, position, contacts, triggers, each_contact or each_trigger afterwards.
  • step steps once and returns a Frame. Its tick, pose(body), contacts and triggers are copies, so they survive later steps and close.
  • tick counts completed steps.

A Contact has kind (Begin or End), first, second, began?, ended? and involves?(body). For triggers, first is the sensor body. Removing a body still reports its end transitions on the next step. The same Contact shape is used by garnet-physics3d.

Threads and lifetime

Pass a job pool to spread Box2D's broad phase, narrow phase, solver and body finalization over its workers:

world = P::World.new(jobs: ecs_world.jobs) # or Garnet::Jobs.shared

Physics::TaskSystem backs Box2D's task callbacks with Garnet::Jobs (workerCount = jobs.worker_count + 1, the stepping thread included). Poses are bit-for-bit identical with and without a pool and with any worker count, and stepping allocates nothing on the Crystal heap. The pool needs at most 63 workers, and only one thread at a time may step worlds that share a pool. Without -Dpreview_mt -Dexecution_context the pool has no workers and everything runs on the owner thread, as without jobs:. physics/bench/stacks.cr measures the step time.

Call close when a world is no longer needed. A world dropped without it is released by its finalizer, which only queues the native release onto the owner thread's Garnet::ReleaseQueue; the ECS schedule drains it every frame, and other owners call Garnet::ReleaseQueue.drain_current. World.live_count counts native worlds not yet released.

Queries

hit = world.raycast(origin, direction, 20, exclude: player, mask: WALLS)
sweep = world.circlecast(origin, 0.4, direction, 3)
box = world.shapecast(P::BoxShape.new(1, 2), direction, 3, at: origin)
nearby = world.overlap(P::CircleShape.new(2), at: origin)
world.overlap(P::CircleShape.new(2), at: origin) { |body| ... } # no array allocation

Casts return the closest Hit (body, distance, point, normal) or nil. Every query skips sensor shapes and accepts category:/mask:. Overlaps report each body once.

Bodies and joints

impulse, velocity, teleport and kinematic_target act on body handles. distance_joint constrains two bodies at local anchors. remove(body) and remove_joint(joint) release handles; removing a body also removes its joints. Handles identify their world, and a removed handle never resolves to a later body: using one raises Physics::Error, a Garnet::Error.

Deprecated names

Deprecated Use
World#destroy World#remove
World#destroy_joint World#remove_joint
Frame#sequence Frame#tick
Contact#a, Contact#b Contact#first, Contact#second
UInt64 masks UInt32 masks

See garnet-physics-scene for the ECS plugin, which creates bodies from components, writes Scene::Components::Pose and emits contact and trigger events.

Repository

physics

Owner
Statistic
  • 0
  • 0
  • 0
  • 1
  • 2
  • 2 days ago
  • November 30, 2026
License

MIT License

Links
Synced at

Thu, 03 Dec 2026 02:11:04 GMT

Languages