File size: 3,514 Bytes
06b3545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""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