"""Minimal 2D rigid-body physics: discs in a box with elastic collisions. Cubes and cylinders are *rendered* as squares / rings (top-down view, like looking down on the CLEVRER scene) but use a circular footprint for physics. This keeps the engine tiny, stable and fast while preserving the causal event structure (collisions, starts/stops of motion) that CLEVRER questions need. """ from dataclasses import dataclass, field import numpy as np from . import config @dataclass class Body: idx: int color: str shape: str material: str size: str radius: float pos: np.ndarray # (2,) world coordinates vel: np.ndarray # (2,) spin: float = 0.0 # visual angular velocity (rad/s) angle: float = 0.0 # visual rotation angle (rad) mass: float = 1.0 is_probe: bool = False @property def speed(self) -> float: return float(np.linalg.norm(self.vel)) def mass_of(radius: float, material: str) -> float: # all shapes use a circular footprint: m = density * pi * r^2 return config.DENSITY[material] * np.pi * radius ** 2 class World: """A box arena with elastic object-object and object-wall collisions.""" def __init__(self, bodies, half: float = config.WORLD_HALF): self.bodies = list(bodies) self.half = half def step(self, h: float): """Advance physics by h seconds. Returns: contacts: list of (idx_a, idx_b) pairs that collided this step wall_hits: list of (idx, axis, side) with side in {-1, +1} """ contacts, wall_hits = [], [] # integrate for b in self.bodies: b.pos = b.pos + b.vel * h b.vel = b.vel * config.DRAG b.angle = (b.angle + b.spin * h) % (2.0 * np.pi) # pairwise object collisions bs = self.bodies for i in range(len(bs)): for j in range(i + 1, len(bs)): A, B = bs[i], bs[j] d = B.pos - A.pos dist = float(np.linalg.norm(d)) rsum = A.radius + B.radius if dist < rsum and dist > 1e-9: n = d / dist # impulse along the normal if approaching v_rel_n = float(np.dot(B.vel - A.vel, n)) if v_rel_n < 0.0: e = config.RESTITUTION jimp = -(1.0 + e) * v_rel_n / (1.0 / A.mass + 1.0 / B.mass) A.vel = A.vel - (jimp / A.mass) * n B.vel = B.vel + (jimp / B.mass) * n contacts.append((A.idx, B.idx)) # positional correction so objects never sink into each other push = n * (0.5 * (rsum - dist)) A.pos = A.pos - push B.pos = B.pos + push # walls for b in self.bodies: for ax in range(2): lim = self.half - b.radius if b.pos[ax] > lim and b.vel[ax] > 0: b.pos[ax] = lim b.vel[ax] = -b.vel[ax] * config.WALL_RESTITUTION wall_hits.append((b.idx, ax, +1)) elif b.pos[ax] < -lim and b.vel[ax] < 0: b.pos[ax] = -lim b.vel[ax] = -b.vel[ax] * config.WALL_RESTITUTION wall_hits.append((b.idx, ax, -1)) return contacts, wall_hits