コード例 #1
0
    def testMerge(self) -> None:
        bb1 = p.BB(0, 0, 10, 10)
        bb2 = p.BB(2, 0, 10, 10)
        bb3 = p.BB(10, 10, 15, 15)

        self.assertEqual(bb1.merge(bb2), p.BB(0, 0, 10, 10))
        self.assertEqual(bb2.merge(bb3).merge(bb1), p.BB(0, 0, 15, 15))
コード例 #2
0
    def testMethods(self) -> None:
        bb1 = p.BB(0, 0, 10, 10)
        bb2 = p.BB(10, 10, 20, 20)
        bb3 = p.BB(4, 4, 5, 5)
        bb4 = p.BB(2, 0, 10, 10)

        v1 = Vec2d(1, 1)
        v2 = Vec2d(100, 3)
        self.assertTrue(bb1.intersects(bb2))
        self.assertFalse(bb3.intersects(bb2))

        self.assertTrue(bb1.intersects_segment(v1, v2))
        self.assertFalse(bb3.intersects_segment(v1, v2))

        self.assertTrue(bb1.contains(bb3))
        self.assertFalse(bb1.contains(bb2))

        self.assertTrue(bb1.contains_vect(v1))
        self.assertFalse(bb1.contains_vect(v2))

        self.assertEqual(bb1.expand(v1), bb1)
        self.assertEqual(bb1.expand(-v2), p.BB(-100, -3, 10, 10))

        self.assertEqual(bb1.center(), (5, 5))
        self.assertEqual(bb1.area(), 100)

        self.assertEqual(bb1.merged_area(bb2), 400)

        self.assertEqual(bb2.segment_query(v1, v2), float("inf"))
        self.assertEqual(bb1.segment_query((-1, 1), (99, 1)), 0.01)

        self.assertEqual(bb1.clamp_vect(v2), Vec2d(10, 3))
コード例 #3
0
    def testPickle(self) -> None:
        x = p.BB(4, 4, 5, 5)

        s = pickle.dumps(x, 2)
        actual = pickle.loads(s)

        self.assertEqual(x, actual)

        self.assertEqual(p.BB(*x), x)
コード例 #4
0
    def testCreation(self):
        bb_empty = p.BB()

        self.assertEqual(bb_empty.left, 0)
        self.assertEqual(bb_empty.bottom, 0)
        self.assertEqual(bb_empty.right, 0)
        self.assertEqual(bb_empty.top, 0)

        bb_defined = p.BB(-10, -5, 15, 20)

        self.assertEqual(bb_defined.left, -10)
        self.assertEqual(bb_defined.bottom, -5)
        self.assertEqual(bb_defined.right, 15)
        self.assertEqual(bb_defined.top, 20)
コード例 #5
0
    def begin_render(self, process: ProcessTimed, view: View) -> None:
        self._surface.fill((240, 240, 240))  # set background
        # get all objects in frame
        view_position = self._view_position
        view_world_size = self._view_world_size
        # BB(left, bottom, right, top)
        shapes = process.space.bb_query(
            pymunk.BB(view_position[0], view_position[1],
                      view_position[0] + view_world_size[0],
                      view_position[1] + view_world_size[1]), ShapeFilter())

        entities = [
            shape.body.entity for shape in shapes
            if shape.body is not None and shape.body.entity is not None
        ]

        # render objects in entity type order
        # TODO: make plane ordering more sensible
        render_planes = {}
        for entity in entities:
            plane = entity.type_
            if plane in render_planes:
                render_planes[plane].append(entity)
            else:
                render_planes[plane] = [entity]

        for plane in sorted(render_planes.keys(), reverse=True):
            for entity in render_planes[plane]:
                entity.render(self)
コード例 #6
0
    def testCircleBB(self) -> None:
        b = p.Body(10, 10)
        c = p.Circle(b, 5)

        c.cache_bb()

        self.assertEqual(c.bb, p.BB(-5.0, -5.0, 5.0, 5.0))
コード例 #7
0
    def testCircleNoBody(self):
        s = p.Space()
        c = p.Circle(None, 5)

        c.update((10, 10), (1, 0))

        self.assertEqual(c.bb, p.BB(5, 5, 15, 15))
コード例 #8
0
ファイル: setup.py プロジェクト: wilmot208/pool-simulator
    def _add_static_scenery(self):
        """
        Create the static bodies.
        :return: None
        """
        space = self._space

        logo_img = pygame.image.load("table_outline.png")
        logo_bb = pymunk.BB(0, 0, logo_img.get_width(), logo_img.get_height())

        def sample_func(point):
            try:
                p = pymunk.pygame_util.to_pygame(point, logo_img)
                color = logo_img.get_at(p)

                return color.hsla[2]
            except:
                return 0

        line_set = pymunk.autogeometry.PolylineSet()

        def segment_func(v0, v1):
            line_set.collect_segment(v0, v1)

        logo_img.lock()
        pymunk.autogeometry.march_soft(
            logo_bb,
            logo_img.get_width(), logo_img.get_height(),
            99,
            segment_func,
            sample_func)
        logo_img.unlock()

        r = 10

        for line in line_set:
            line = pymunk.autogeometry.simplify_curves(line, .7)

            max_x = 0
            min_x = 1000
            max_y = 0
            min_y = 1000
            for l in line:
                max_x = max(max_x, l.x)
                min_x = min(min_x, l.x)
                max_y = max(max_y, l.y)
                min_y = min(min_y, l.y)

            r += 30
            if r > 255:
                r = 0

            if True:
                for i in range(len(line)-1):
                    shape = pymunk.Segment(
                        space.static_body, line[i], line[i+1], 1)
                    shape.friction = 0.9
                    shape.elasticity = 0.95
                    shape.color = (0, 0, 0)
                    space.add(shape)
コード例 #9
0
    def testCircleNoBody(self):
        s = p.Space()
        c = p.Circle(None,5)

        bb = c.update(p.Transform(1, 2, 3, 4, 5, 6))
        self.assertEqual(c.bb, bb)
        self.assertEqual(c.bb, p.BB(0, 1, 10, 11))
コード例 #10
0
    def testBB(self):
        c = p.Poly(None, [(2,2),(4,3),(3,5)])
        bb = c.update(p.Transform.identity())
        self.assertEqual(bb, c.bb)
        self.assertEqual(c.bb, p.BB(2, 2, 4, 5))

        b = p.Body(1,2)
        c = p.Poly(b, [(2,2),(4,3),(3,5)])
        c.cache_bb()
        self.assertEqual(c.bb, p.BB(2, 2, 4, 5))

        s = p.Space()
        b = p.Body(1,2)
        c = p.Poly(b, [(2,2),(4,3),(3,5)])
        s.add(b,c)
        self.assertEqual(c.bb, p.BB(2, 2, 4, 5))
コード例 #11
0
 def testBBQuerySensor(self):
     s = p.Space()
     c = p.Circle(s.static_body, 10)
     c.sensor = True
     s.add(c)
     hits = s.bb_query(p.BB(0, 0, 10, 10), p.ShapeFilter())
     self.assertEqual(len(hits), 1)
コード例 #12
0
    def testCreateBox(self):
        c = p.Poly.create_box(None, (4, 2), 3)
        self.assertEqual(c.get_vertices(), [(2, -1), (2, 1), (-2, 1),
                                            (-2, -1)])

        c = p.Poly.create_box_bb(None, p.BB(1, 2, 3, 4), 3)
        self.assertEqual(c.get_vertices(), [(3, 2), (3, 4), (1, 4), (1, 2)])
コード例 #13
0
    def fill(self):
        ''' fill space with objects'''
        assert self.player_body is None and len(
            self.bouncer_objects
        ) == 0, "Do you really want to call fill() on already filled environment?"
        if self.moving_walls:
            # create moving walls
            self.player_body = create_walls(self,
                                            self.cfg['inner_box_height'],
                                            self.cfg['inner_box_width'],
                                            kinematic=True,
                                            color=THECOLORS['gray10'],
                                            center=True)
        # --  Set random bouncers
        self.bouncer_objects = []
        # First, get bounding box to place bouncers in
        walls = self.enclosing_wall_shapes
        assert len(
            walls
        ) == 4, "Placing objects currently only works for inside a box. Need to add stuff if you want non-box outer walls."
        corners = np.array(
            [pymunk_utils.shapes_abs_position(w) for w in walls])
        bb = pymunk.BB(np.min(corners[:, :, 0]), np.min(corners[:, :, 1]),
                       np.max(corners[:, :, 0]), np.max(corners[:, :, 1]))
        #if moving_walls:
        #    bb = pymunk.BB(self.player_body.position[0], self.player_body.position[1], self.player_body.position[0] + self.cfg['inner_box_width'],
        #               self.player_body.position[1] + self.cfg['inner_box_height'])

        for _ in range(self.n_bouncers):
            bouncer = create_bouncer(self,
                                     shape_types=self.cfg['bouncer_shapes'],
                                     bb=bb)
            self.bouncer_objects.append(bouncer)
        if not self.allow_rotation:
            for bd in self.space.bodies:
                bd.angular_velocity = 0.
                bd.angular_velocity_limit = 0.
        self.count_shapes()  # contains assertion
        if self.clutter_background and self.clutter_background_white:
            self.background_surf = generate_cluttered_background(
                ['circle', 'rectangle', 'triangle'],
                self.screen_size[0],
                self.screen_size[1],
                self.draw_options,
                sz_min=self.clutter_sz_min,
                sz_max=self.clutter_sz_max,
                same_sided=False,
                n_objects=self.clutter_num,
                colors=[THECOLORS['white']])
        elif self.clutter_background:
            self.background_surf = generate_cluttered_background(
                ['circle', 'rectangle', 'triangle'],
                self.screen_size[0],
                self.screen_size[1],
                self.draw_options,
                sz_min=self.clutter_sz_min,
                sz_max=self.clutter_sz_max,
                same_sided=False,
                n_objects=self.clutter_num)
コード例 #14
0
    def avoirCarreProximite(self):

        gauche = self.position.x - Personne.RAYON_DE_PROXIMITE
        droite = self.position.x + Personne.RAYON_DE_PROXIMITE
        haut = self.position.y + Personne.RAYON_DE_PROXIMITE
        bas = self.position.y - Personne.RAYON_DE_PROXIMITE

        return pymunk.BB(gauche, bas, droite, haut)
コード例 #15
0
    def testPolyBB(self):
        s = p.Space()
        b = p.Body(10, 10)
        c = p.Poly(b, [(2, 2), (4, 3), (3, 5)])

        c.cache_bb()

        self.assertEqual(c.bb, p.BB(2, 2, 4, 5))
コード例 #16
0
    def testBB(self):
        s = p.Space()
        b = p.Body(10,10)
        c = p.Segment(b,(2,2),(2,3),2)

        c.cache_bb()

        self.assertEqual(c.bb, p.BB(0, 0, 4.0, 5.0))
コード例 #17
0
    def testPickle(self):
        x = p.BB(4, 4, 5, 5)

        s = pickle.dumps(x, 2)
        actual = pickle.loads(s)

        self.assertEqual(x, actual)

        x2 = x.copy()
コード例 #18
0
    def testCreation(self) -> None:
        bb_empty = p.BB()

        self.assertEqual(bb_empty.left, 0)
        self.assertEqual(bb_empty.bottom, 0)
        self.assertEqual(bb_empty.right, 0)
        self.assertEqual(bb_empty.top, 0)

        bb_defined = p.BB(-10, -5, 15, 20)

        self.assertEqual(bb_defined.left, -10)
        self.assertEqual(bb_defined.bottom, -5)
        self.assertEqual(bb_defined.right, 15)
        self.assertEqual(bb_defined.top, 20)

        bb_circle = p.BB.newForCircle((3, 3), 3)
        self.assertEqual(bb_circle.left, 0)
        self.assertEqual(bb_circle.bottom, 0)
        self.assertEqual(bb_circle.right, 6)
        self.assertEqual(bb_circle.top, 6)
コード例 #19
0
    def testPolyUnsafeSet(self):
        s = p.Space()
        b = p.Body(10, 10)
        c = p.Poly(b, [(2, 2), (4, 3), (3, 5)])

        c.cache_bb()

        c.unsafe_set_vertices([(0, 0), (1, 0), (1, 1)])
        c.cache_bb()

        self.assertEqual(c.bb, p.BB(0, 0, 1, 1))
コード例 #20
0
 def cell_bb(self, i, j, position):
     ## figure out where (i,j) actually is and make pymunk bounding box
     half_grid_width = (self.grid_width - 0.5) * self.cell_width / 2
     half_grid_length = (self.grid_length - 0.5) * self.cell_length / 2
     x = position[0] + i * self.cell_length - half_grid_length
     y = position[1] + j * self.cell_width - half_grid_width + 1
     left = x - self.cell_length / 2
     right = x + self.cell_length / 2
     bottom = y - self.cell_width / 2
     top = y + self.cell_width / 2
     bb = pymunk.BB(left, bottom, right, top)
     return bb
コード例 #21
0
    def testMethods(self):
        bb1 = p.BB(0, 0, 10, 10)
        bb2 = p.BB(10, 10, 20, 20)
        bb3 = p.BB(4, 4, 5, 5)
        v1 = Vec2d(1, 1)
        v2 = Vec2d(100, 5)
        self.assert_(bb1.intersects(bb2))

        self.assertFalse(bb1.contains(bb2))
        self.assert_(bb1.contains(bb3))

        self.assert_(bb1.contains_vect(v1))
        self.assertFalse(bb1.contains_vect(v2))

        self.assertEqual(bb1.merge(bb2), p.BB(0, 0, 20, 20))

        self.assertEqual(bb1.expand(v1), bb1)
        self.assertEqual(bb1.expand(-v2), p.BB(-100, -5, 10, 10))

        self.assertEqual(bb1.clamp_vect(v2), Vec2d(10, 5))

        self.assertEqual(bb1.wrap_vect((11, 11)), (1, 1))
コード例 #22
0
ファイル: main.py プロジェクト: zman97211/pymunk
    def create_logo_lines(self, logo_img):
        logo_bb = pymunk.BB(0, 0, logo_img.width, logo_img.height)

        def sample_func(point):
            try:
                color = logo_img.read_pixel(point.x, point.y)
                return color[3] * 255
            except:
                return 0

        line_set = pymunk.autogeometry.PolylineSet()

        def segment_func(v0, v1):
            line_set.collect_segment(v0, v1)

        pymunk.autogeometry.march_soft(logo_bb, logo_img.width,
                                       logo_img.height, 99, segment_func,
                                       sample_func)

        r = 10

        letter_group = 0
        lines = []
        for line in line_set:
            line = pymunk.autogeometry.simplify_curves(line, .7)

            max_x = 0
            min_x = 1000
            max_y = 0
            min_y = 1000
            for l in line:
                max_x = max(max_x, l.x)
                min_x = min(min_x, l.x)
                max_y = max(max_y, l.y)
                min_y = min(min_y, l.y)
            w, h = max_x - min_x, max_y - min_y

            # we skip the line which has less than 35 height, since its the "hole" in
            # the p in pymunk, and we dont need it.
            if h < 35:
                continue

            center = Vec2d(min_x + w / 2., min_y + h / 2.)
            t = pymunk.Transform(a=1.0, d=1.0, tx=-center.x, ty=-center.y)

            r += 30
            if r > 255:
                r = 0
            line = [Vec2d(l.x, 300 - l.y) for l in line]
            lines.append(line)
        return lines
コード例 #23
0
ファイル: RFP_GFP_temp.py プロジェクト: setaucl/iGEM
 def setRandomPosition(self):
     border = 3*R
     max_tries=10
     while max_tries>0:
         x=random.randint(border,self.world.width-border)
         y=random.randint(border,self.world.height-border)
         filter = pymunk.ShapeFilter(mask=pymunk.ShapeFilter.ALL_MASKS)
         results = self.world.space.bb_query(
             pymunk.BB(x-border,y-border,x+border,y+border),
                     filter)
         if len(results)==0:
             max_tries=0
     self.body.position = (x,y)
     return
コード例 #24
0
    def draw(self, surface, camera):
        cam_rect = camera.get_rect()
        cam_bb = pymunk.BB(cam_rect.left, cam_rect.top, cam_rect.right,
                           cam_rect.bottom)
        cam_tl = Vec2d(cam_rect.topleft)
        cam_offset = Vec2d(self.draw_offset)
        zoom = camera.get_current_zoom()

        blit = surface.blit
        sprite_dict = self.spritedict

        for sprite in self.layer_sorted():
            if sprite.bb.intersects(cam_bb):
                s_img = sprite.image
                img = pygame.transform.rotozoom(s_img, -sprite.angle, zoom)

                img_size = img.get_size()
                s_pos = sprite.position
                sc = (int(cam_offset[0] + (s_pos[0] - cam_tl[0]) * zoom -
                          img_size[0] / 2),
                      int(cam_offset[1] + (s_pos[1] - cam_tl[1]) * zoom -
                          img_size[1] / 2))
                sprite_dict[sprite] = blit(img, sc)

        cam_c = Vec2d(cam_rect.center)
        cam_h = (CAMERA_SOUND_HEIGHT / zoom)**2
        for snd in self.sounds:
            sound = snd[0]
            kwargs = snd[2]
            c = kwargs.get('channel', None)
            if c is not None:
                c = pygame.mixer.Channel(c)
                c.play(sound)
            else:
                c = sound.play(kwargs.get('loops', 0),
                               kwargs.get('max_time', 0),
                               kwargs.get('fade_ms', 0))
            if c is not None:
                to_s = snd[1].position - cam_c
                d = to_s.get_length_sqrd()
                v = SOUND_COEF / (math.sqrt(d + cam_h) + 1)
                c.set_volume(v)

        self.sounds.clear()
        self.lostsprites = []
コード例 #25
0
    def testBBQuery(self):
        s = p.Space()

        b1 = p.Body(1, 1)
        b1.position = 19, 0
        s1 = p.Circle(b1, 10)
        s.add(s1)

        b2 = p.Body(1, 1)
        b2.position = 0, 0
        s2 = p.Circle(b2, 10)
        s.add(s2)

        bb = p.BB(-7, -7, 7, 7)
        hits = s.bb_query(bb, p.ShapeFilter())
        self.assertEqual(len(hits), 1)
        self.assertTrue(s2 in hits)
        self.assertTrue(s1 not in hits)
コード例 #26
0
def map_gen(space):
    from pymunk.autogeometry import march_hard, march_soft
    img = [
        "xxxxxxxxxxxxxxx", "x             x", "x             x",
        "x xxxxx       x", "x x           x", "x x           x",
        "x             x", "xxxxxxxxxxxxxxx"
    ]

    verts = []

    def segment_func(v0, v1):
        px = (v0 * 50) + pm.vec2d.Vec2d(100, 100)
        py = (v1 * 50) + pm.vec2d.Vec2d(100, 100)
        verts.extend([px, py])

    def sample_func(point):
        x = int(point.x)
        y = int(point.y)
        return 1.0 if img[y][x] == "x" else 0.0

    march_hard(pm.BB(0, 0, 14, 7), 15, 8, .1, segment_func, sample_func)

    p = pm.Poly(space.static_body, verts, radius=50)
    space.add(p)
コード例 #27
0
def create_bouncer(env, shape_types=['circle'], bb=None, same_sided=False):
    assert isinstance(env, AbstractEnv)
    if bb is None:
        bb = pymunk.BB(0, 0, env.screen_size[0], env.screen_size[1])

    shape_type = shape_types[np.random.randint(0, len(shape_types))]
    vel = tuple(utils.rand_float(-env.v0_max, env.v0_max, shape=(2, )))
    radius = utils.rand_float(env.sz_min / 2., env.sz_max / 2., shape=())
    if env.mass_propto_area:
        mass = None
    else:
        mass = utils.rand_float(env.m_min, env.m_max, shape=(
        ))  # np.random.random(size=1) * (env.m_max - env.m_min) + env.m_min
        assert mass <= env.m_max and mass >= env.m_min
    assert shape_type in bc.shape_types
    assert radius * 2 < min([bb.top - bb.bottom, bb.right - bb.left])

    if shape_type is 'circle':
        bouncer = bc.CircleBouncer(mass,
                                   vel,
                                   radius=radius,
                                   mass_propto_area=env.mass_propto_area)
    elif shape_type is 'rectangle':
        height = radius * 2
        if not same_sided:
            width = utils.rand_float(env.sz_min, env.sz_max, shape=())
        else:
            width = height
        assert width < min([bb.top - bb.bottom, bb.right - bb.left])
        bouncer = bc.RectangleBouncer(mass,
                                      vel,
                                      height=height,
                                      width=width,
                                      mass_propto_area=env.mass_propto_area)
    elif shape_type is 'triangle':
        height = radius * 2
        width = None if same_sided else utils.rand_float(
            env.sz_min, env.sz_max, shape=())
        bouncer = bc.TriangleBouncer(mass,
                                     vel,
                                     height=height,
                                     width=width,
                                     mass_propto_area=env.mass_propto_area)
    else:
        raise NotImplementedError("Shape type " + shape_type +
                                  " has not been implemented so far.")

    bouncer_body = bouncer.bodies[0]
    bouncer_shape = bouncer.shapes[bouncer_body][0]
    bouncer_shape.elasticity = 1.
    bouncer_shape.collision_type = CollisionTypes.BOUNCERS.value
    bouncer_body.velocity = vel
    bouncer_body.angle = utils.rand_float(0, 2. * np.pi)
    bouncer_body.angular_velocity = utils.rand_float(
        -env.w0_max, env.w0_max) if env.allow_rotation else 0.
    bouncer_body.velocity_func = env.limit_velocity_func
    # direction = pymunk.Vec2d(1, 0).rotated(bouncer_body.angle)
    ok = pymunk_utils.assign_valid_location(bouncer_body,
                                            env.space,
                                            bb,
                                            maxiter=100,
                                            radius=(bouncer.diameter / 2. +
                                                    env.min_wall_width / 2.))
    if not ok:
        raise AssertionError("Could not create new body; space too crowded")

    env.space.add(bouncer_body, bouncer_shape)
    return bouncer
コード例 #28
0
ファイル: index_video.py プロジェクト: yurokji/pymunk
screen = pygame.display.set_mode((690, 300))
clock = pygame.time.Clock()

clock.tick(1)

### Physics stuff
space = pymunk.Space()
space.gravity = 0, 900
space.sleep_time_threshold = 0.3

draw_options = pymunk.pygame_util.DrawOptions(screen)
pymunk.pygame_util.positive_y_is_up = False

### Generate geometry from pymunk logo image
logo_img = pygame.image.load("pymunk_logo_sphinx.png")
logo_bb = pymunk.BB(0, 0, logo_img.get_width(), logo_img.get_height())


def sample_func(point):
    try:
        p = pymunk.pygame_util.to_pygame(point, logo_img)
        color = logo_img.get_at(p)

        return color.a
        # return color.hsla[2]
    except:
        return 0


logo_img.lock()
line_set = pymunk.autogeometry.march_soft(logo_bb, logo_img.get_width(),
コード例 #29
0
ファイル: main.py プロジェクト: Ethan7/TwitchPlaysMultiplayer
winlabel = cocos.text.Label("",
                            font_name="Arial",
                            font_size=16,
                            color=(255, 255, 255, 255),
                            anchor_x="center")
winlabel.position = window.width / 2, window.height / 2
game_scene.add(winlabel)

pyglet.clock.schedule_interval(update, 1.0 / 60)

#Pymunk Code
space = pymunk.Space()
space._set_sleep_time_threshold(5)
space.gravity = 0, -1000
bound_box = pymunk.BB(0, 0, window.width, window.height)
handler = space.add_collision_handler(1, 2)
handler._set_pre_solve(reset)

#objective
objective = cocos.sprite.Sprite("img/objective.png")
objective.position = (window.width - objective.width,
                      window.height - objective.height)
objective.shape = pymunk.Poly.create_box(None,
                                         size=(objective.width,
                                               objective.height))
objective.body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
#Mass and Moment of Inertia
objective.shape.body = objective.body
objective.shape.elastivity = 0.0
objective.shape.friction = 0.0
コード例 #30
0
    def testBBQuery(self):
        bb = p.BB(-7, -7, 7, 7)

        hits = self.s.bb_query(bb)
        self.assertTrue(self.s1 in hits)
        self.assertTrue(self.s2 not in hits)