Exemple #1
0
 def getDDD(self, t: float) -> Vector:
     """Interpolate the 3rd derivative along the spline where 0 <= t <= self.length."""
     assert 0 <= t <= self.length
     index = int(np.floor(t))
     t -= index
     dddx = 6 * self.ax[index]
     dddy = 6 * self.ay[index]
     return Vector(dddx, dddy)
Exemple #2
0
 def getDD(self, t: float) -> Vector:
     """Interpolate the 2nd derivative along the spline where 0 <= t <= self.length."""
     assert 0 <= t <= self.length
     index = int(np.floor(t))
     t -= index
     ddx = (6 * self.ax[index] * t) + (2 * self.bx[index])
     ddy = (6 * self.ay[index] * t) + (2 * self.by[index])
     return Vector(ddx, ddy)
Exemple #3
0
    def get_instantaneous_velocity(self):
        entity = self.entity
        x, y = entity.position
        lx, ly = self.last_position

        x -= lx
        y -= ly

        return Vector(entity.name + " instantaneous velocity", x, y)
Exemple #4
0
 def define_ball(self):
     player = randint(0, 1)
     self.ball = Ball(v=Vector(0, 0),
                      circle=Ellipse(size=[ballsize, ballsize],
                                     pos=[
                                         self.halves[player].node.pos[0],
                                         window_height * 2 / 3
                                     ]),
                      parent=self)
Exemple #5
0
    def __init__(self, node_x, node_y, **kwargs):
        super(Half, self).__init__(**kwargs)

        self.node = Node(
            size = [nodesize, nodesize],
            pos = [node_x, node_y]
        )

        self.vector = Vector(0, 0)
Exemple #6
0
def test_vector_cross():
    v1 = Vector([2, 3])
    v2 = Vector([1, 7])
    assert v1.cross(v2) == Vector([11])

    v3 = Vector([2, 7, 4])
    v4 = Vector([3, 9, 8])
    assert v3.cross(v4) == Vector([20, -4, -3])

    assert v1.cross(v3) == Vector([12, -8, 8])
    assert v4.cross(v2) == Vector([-56, 8, 12])
Exemple #7
0
    def make_stars(self, depth):
        average_number = 1 + depth * 1
        spread = 1
        number_of_stars = int(
            round(max(random.gauss(average_number, spread), 0)))

        for i in range(number_of_stars):
            x = random.uniform(0, Section.width) + self.position.x
            y = random.uniform(0, Section.height) + self.position.y
            self.stars.append(Star(Vector(x, y), depth))
def string_to_points(s):
    try:
        res = []
        for x, y in re.findall(r'\((.*?),\s*(.*?)\)', s):
            res.append(Vector(float(x), float(y)))
        return res
    except (TypeError, ValueError):
        return []
    except Exception:
        traceback.print_exc()
def update():
    axes.clear()
    axes.set_aspect('equal')
    axes.set_xticks(np.linspace(-1.0, 1.0, 5))
    axes.set_yticks(np.linspace(-1.0, 1.0, 5))
    axes.set_zticks(np.linspace(0.0, 2.0, 5))
    axes.set_xlim(-1.0, 1.0)
    axes.set_ylim(-1.0, 1.0)
    axes.set_zlim(0.0, 2.0)
    axes.set_xlabel('X')
    axes.set_ylabel('Y')
    axes.set_zlabel('Z')

    brdf = BRDF(D=brdf_D, F=brdf_F, G=brdf_V, V=brdf_V)
    if brdf_C == 'All':
        f, color = brdf.__call__, color_C
    elif brdf_C == 'D':
        f, color = brdf.evaluate_D, color_D
    elif brdf_C == 'F':
        f, color = brdf.evaluate_F, color_F
    elif brdf_C == 'G':
        f, color = brdf.evaluate_G, color_V
    elif brdf_C == 'V':
        f, color = brdf.evaluate_V, color_V
    else:
        f, color = None, None

    hemisphere = Hemisphere()
    for i in range(hemisphere.nb_samples[0]):
        for j in range(hemisphere.nb_samples[1]):
            l = np.array([
                hemisphere.xs_world[i, j], hemisphere.ys_world[i, j],
                hemisphere.zs_world[i, j]
            ])
            radius = multiplier * f(n=n, l=l, v=v, material=material)
            hemisphere.xs_world[i, j] *= radius
            hemisphere.ys_world[i, j] *= radius
            hemisphere.zs_world[i, j] *= radius

    hemisphere.draw(axes, color=color)
    Vector(p_end=n).draw(axes)
    Vector(p_end=v).draw(axes)
    Vector(p_end=reflected_direction(n, v)).draw(axes)
Exemple #10
0
def save_len():
    first_atom = int(to_change[0][serial_number_l:serial_number_r])
    last_atom = int(to_change[-1][serial_number_l:serial_number_r])
    with open(file_name, 'r') as fin:

        s = fin.readline()

        while not (s.startswith("CONECT")):
            s = fin.readline()

        while s.startswith("CONECT"):
            atom = int(s[serial_number_l:serial_number_r])
            if (atom >= first_atom and atom <= last_atom):
                atom -= first_atom
                first = s[first_l:first_r]
                second = s[second_l:second_r]
                third = s[third_l:third_r]
                fourth = s[fourth_l:fourth_r]
                if (first.strip() != "" and int(first) >= first_atom
                        and int(first) <= last_atom):
                    first = int(first) - first_atom
                    bond_length[atom].append(
                        (first, Vector(crd[atom], crd[first]).len()))

                if (second.strip() != "" and int(second) >= first_atom
                        and int(second) <= last_atom):
                    second = int(second) - first_atom
                    bond_length[atom].append(
                        (second, Vector(crd[atom], crd[second]).len()))

                if (third.strip() != "" and int(third) >= first_atom
                        and int(third) <= last_atom):
                    third = int(third) - first_atom
                    bond_length[atom].append(
                        (third, Vector(crd[atom], crd[third]).len()))

                if (fourth.strip() != "" and int(fourth) >= first_atom
                        and int(fourth) <= last_atom):
                    fourth = int(fourth) - first_atom
                    bond_length[atom].append(
                        (fourth, Vector(crd[atom], crd[fourth]).len()))

            s = fin.readline()
Exemple #11
0
    def under_mapify(self):
        data = [[day15.load.WALL] * 3,
                [day15.load.OPEN, day15.load.ELF, day15.load.GOB]]

        inodes = day15.load._mapify(data)

        node = next(inodes)
        assert isinstance(node, day15.Node)
        assert not node.unit
        assert node.position == Vector(0, 1)

        node = next(inodes)
        assert isinstance(node, day15.Node)
        assert isinstance(node.unit, day15.Elf)
        assert node.position == Vector(1, 1)

        node = next(inodes)
        assert isinstance(node, day15.Node)
        assert isinstance(node.unit, day15.Goblin)
        assert node.position == Vector(2, 1)
Exemple #12
0
def find_angle(atoms, target_coordinates, point1, point2):
    b, c = 0, 0
    for i in range(3):
        o = find_intersection_point(point1, point2, atoms[i])
        r = Vector(o, atoms[i])
        f = Vector(o, target_coordinates[i])

        if (r.len() < eps**10):
            print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            return Angle(0, 1)

        # если эти 3 точки лежат на одной прямой, что бы я ни делала, это ни на что не повлияет

        axis = Vector(point1, point2) / Vector(point1, point2).len()
        r1 = r / r.len()
        s1 = vmul(r1, axis)
        b += 2 * r.len() * (f * r1)
        c += 2 * r.len() * (f * s1)

    return Angle(c / sqrt(b**2 + c**2), b / sqrt(b**2 + c**2))
Exemple #13
0
    def __init__(self, entity):
        self.entity = entity

        self.mass = 1
        self.elasticity = 1
        self.gravity = 0
        self.friction = .75

        self.velocity = Vector(entity.name + " velocity", 0, 0)
        self.forces = []
        self.last_position = 0, 0
 def lines_between_2_lines(self,
                           line1,
                           line2,
                           amount_of_lines,
                           line_width=1,
                           color=(0, 0, 0),
                           w1=None,
                           w2=None):
     line1_points = line1.get_split_points(amount_of_lines, w1)
     line2_points = line2.get_split_points(amount_of_lines, w2)
     for start, end in zip(line1_points, line2_points):
         self.draw_line(Vector(start, end), line_width, color)
Exemple #15
0
    def _mapify(cls, grid):
        for y, row in enumerate(grid):
            for x, item in enumerate(row):
                if not item is cls.WALL:
                    node = Node(Vector(x, y))

                    if item is cls.ELF:
                        Elf(node)
                    elif item is cls.GOB:
                        Goblin(node)

                    yield node
 def fill_table(self):
     line1_points = self.table.lines["left"].line.get_split_points(
         len(self.table.data) + 1)
     line2_points = self.table.lines["right"].line.get_split_points(
         len(self.table.data) + 1)
     for start, end, data_row in zip(line1_points[1:], line2_points[1:],
                                     self.table.data):
         self.annotate_line_manually(line=Vector(start, end),
                                     values=data_row,
                                     placements=[0.25, 0.75],
                                     format="float",
                                     offset_y=8)
Exemple #17
0
def constructNotNormalRecsSample1():
    start_pt1, start_pt2 = Point2D([-2.989484, 2.030411]), Point2D([-0.040854, -9.81334])
    vec_lst1 = [ Vector(4.523321,-1.382918), Vector(3.008505,9.840376), Vector(-4.523321,1.382918), Vector(-3.008505,-9.840376) ]
    vec_lst2 = [Vector(8.19364, 4.667886), Vector(-2.098816, 3.684097), Vector(-8.19364, -4.667886), Vector(2.098816, -3.684097)]
    rec1 = Rectangle(vec_lst1, start_pt1)
    rec2 = Rectangle(vec_lst2, start_pt2)
    return rec1, rec2
Exemple #18
0
        def _inner():
            for y in range(max_y + 1):
                for x in range(max_x + 1):
                    position = Vector(x, y)
                    thing = self.carts.get(position) or self.tracks.get(
                        position)

                    if thing:
                        yield str(thing)
                    else:
                        yield ' '

                yield '\n'
Exemple #19
0
 def __init__(self, a=1.0, b=1.0, c=0.0, d=0.0, e=0.0, f=-1.0, color=None):
     Shape.__init__(self, color)
     if c * c - 4 * a * b >= 0:
         raise Exception("Not an ellipse")
     self.a = a
     self.b = b
     self.c = c
     self.d = d
     self.e = e
     self.f = f
     self.gradient = Transform(2 * a, c, d, c, 2 * b, e)
     self.center = self.gradient.inverse() * Vector(0, 0)
     y1, y2 = quadratic(b - c * c / 4 * a, e - c * d / 2 * a,
                        f - d * d / 4 * a)
     x1, x2 = quadratic(a - c * c / 4 * b, d - c * e / 2 * b,
                        f - e * e / 4 * b)
     self.bound = AABox.from_vectors(Vector(-(d + c * y1) / 2 * a, y1),
                                     Vector(-(d + c * y2) / 2 * a, y2),
                                     Vector(x1, -(e + c * x1) / 2 * b),
                                     Vector(x2, -(e + c * x2) / 2 * b))
     if not self.contains(self.center):
         raise Exception("Internal error, center not inside ellipse")
Exemple #20
0
    def __init__(self, meteor_model, position):
        GameObjectModel.__init__(self, position)

        self.meteor_model = meteor_model

        self.rotation = self.target_angle()
        self.velocity = Vector(0, 0)
        self.can_switch = True

        self.last_position = self.position
        self.moved = False
        self.last_direction = "right"
        self.time = 0
Exemple #21
0
 def shoot(self):
     if self.can_shoot:
         self.can_shoot = False
         self.shot_timer = self.shot_cooldown
         my_pos = self.get_position()
         my_ang = self.get_rotation()
         shot_pos = my_pos + Vector(
             math.cos(math.radians(my_ang + 180)) *
             (WIDTH + BULLET_DIAMETER + 0.05) / 2.,
             math.sin(math.radians(my_ang + 180)) *
             (WIDTH + BULLET_DIAMETER + 0.05) / 2.)
         shot = self.arena.make(Bullet,
                                position=shot_pos,
                                direction=my_ang + 180)
Exemple #22
0
    def __init__(self,
                 direction_vector: Vector = Vector([1, 0, 0]),
                 point: Point = Point(0, 0, 0)):

        if type(direction_vector) != Vector:
            raise TypeError("direction_vector must be of type Vector")
        if not isinstance(point, Point):
            raise TypeError("point must be of type Point")

        if direction_vector.is_zero_vector():
            raise ValueError(
                f"direction_vector: {direction_vector} is an undefined vector")
        self.direction_vector = direction_vector
        self.point = point
Exemple #23
0
class ROBOT:
    outline = Box(Vector(0.6 * M, 0.5 * M))

    _armor_length = 0.14 * M
    armor_lines = [
        LineSegment(*y_mirrors(Vector(outline.dims.x / 2, _armor_length / 2))),
        LineSegment(*x_mirrors(Vector(_armor_length / 2, outline.dims.y / 2))),
        LineSegment(*x_mirrors(Vector(_armor_length / 2, -outline.dims.y /
                                      2))),
        LineSegment(*y_mirrors(Vector(-outline.dims.x / 2, _armor_length / 2)))
    ]
    armor_damages = [20, 40, 40, 60]

    _drive_radius = 0.3 * M
    _factor = 1 / (math.sqrt(2) * _drive_radius)
    drive_config = MotionConfig(3 * MS, 6 * MS2, 0.1 * MS2)
    rotation_config = MotionConfig(_factor * drive_config.top_speed,
                                   _factor * drive_config.top_accel,
                                   _factor * drive_config.friction_decel)
    gimbal_yaw_config = MotionConfig(300 * DS, 1000 * DS2, 10 * DS2)

    zero_tolerance = 0.001
    rebound_coeff = 0.4
    shot_cooldown = 0.1 * S
Exemple #24
0
    def collidesCircle(self, collider):
        """Is the circular `collider` colliding self?"""
        x1 = self.pos.x - self.size_x / 2  # Left.
        x2 = x1 + self.size_x  # Right.
        y1 = self.pos.y - self.size_y / 2  # Bottom.
        y2 = y1 + self.size_y  # Top.
        x, y = collider.pos

        # Voronoi cells:
        #
        # 7 8 9
        # 4 5 6
        # 1 2 3
        #
        # 5 means you are inside the rectangle.
        # 1, 3, 7 and 9: the closest feature is a corner.
        # 2, 4, 6 and 8: the closest feature is an edge.

        if x <= x1 and y <= y1:
            return self._withCorner(Vector(x1, y1), collider)  # Cell 1.
        elif x >= x2 and y <= y1:
            return self._withCorner(Vector(x2, y1), collider)  # Cell 3.
        elif y <= y1:
            return self._withHorizontalEdge(y1, -1, collider)  # Cell 2.

        elif x <= x1 and y >= y2:
            return self._withCorner(Vector(x1, y2), collider)  # Cell 7.
        elif x >= x2 and y >= y2:
            return self._withCorner(Vector(x2, y2), collider)  # Cell 9.
        elif y >= y2:
            return self._withHorizontalEdge(y2, 1, collider)  # Cell 8.

        elif x <= x1:
            return self._withVerticalEdge(x1, -1, collider)  # Cell 4.
        elif x >= x2:
            return self._withVerticalEdge(x2, 1, collider)  # Cell 6.
Exemple #25
0
 def draw(self, image, super_sampling=6):
     if not self.bound.overlaps(image.bounds()):
         return
     color = self.color
     r = float(image.resolution)
     jitter = [
         Vector((x + random.random()) / super_sampling / r,
                (y + random.random()) / super_sampling / r)
         for (x, y) in product(xrange(super_sampling), repeat=2)
     ]
     lj = len(jitter)
     l_x = max(int(self.bound.low.x * r), 0)
     l_y = max(int(self.bound.low.y * r), 0)
     h_x = min(int(self.bound.high.x * r), r - 1)
     h_y = min(int(self.bound.high.y * r), r - 1)
     for y in xrange(l_y, int(h_y + 1)):
         x = l_x
         while x <= h_x:
             corner = Vector(x / r, y / r)
             b = self.signed_distance_bound(corner)
             pixel_diameter = (2**0.5) / r
             if b > pixel_diameter:
                 steps = int(r * (b - (pixel_diameter - 1.0 / r)))
                 for x_ in xrange(x, min(x + steps, int(h_x + 1))):
                     image.pixels[y][x_].draw(color)
                 x += steps
             elif b < -pixel_diameter:
                 steps = int(r * (-b - (pixel_diameter - 1.0 / r)))
                 x += steps
             else:
                 coverage = 0
                 for j in jitter:
                     if self.contains(corner + j):
                         coverage += 1.0
                 image.pixels[y][x].draw(color.fainter(coverage / lj))
                 x += 1
Exemple #26
0
 def _subfile(self, pieces, line):
 
     if len(pieces) != 14:
         raise PartError, "Invalid part data in %s at line %i" % (self.path, line)
     
     colour = int(pieces[0])
     position = map(float, pieces[1:4])
     rows = [map(float, pieces[4:7]),
             map(float, pieces[7:10]),
             map(float, pieces[10:13])]
     part = pieces[13].upper()
     if part.endswith(".DAT"):
         part = part[:-4]
     
     return Piece(Colour(colour), Vector(*position), Matrix(rows), part)
 def test_cross(self):
     
     self.assertEqual( self.a.cross(self.b), Vector(0.0, +1.0, -1.0) )
     self.assertEqual( self.b.cross(self.a), Vector(0.0, -1.0, +1.0) )
     
     self.assertEqual( self.b.cross(self.c), Vector(0.0, -1.0, 0.0) )
     self.assertEqual( self.c.cross(self.b), Vector(0.0, +1.0, 0.0) )
     
     self.assertEqual( self.a.cross(self.c), Vector(+1.0, -1.0, 0.0) )
     self.assertEqual( self.c.cross(self.a), Vector(-1.0, +1.0, 0.0) )
def test_cross(a, b, c):

    assert a.cross(b) == Vector(0.0, +1.0, -1.0)
    assert b.cross(a) == Vector(0.0, -1.0, +1.0)

    assert b.cross(c) == Vector(0.0, -1.0, 0.0)
    assert c.cross(b) == Vector(0.0, +1.0, 0.0)

    assert a.cross(c) == Vector(+1.0, -1.0, 0.0)
    assert c.cross(a) == Vector(-1.0, +1.0, 0.0)
Exemple #29
0
    def _withHorizontalEdge(self, y_edge, sign, collider):
        """Sign = -1 if the other body is under the edge, and +1 if above.

        """
        # Here I look for the point on the collider's circle that's right
        # above or under its center.  If there is collision, that's because of
        # this point.
        y_other_body = collider.pos.y - sign * collider.radius
        # Here I am already measuring the penetration, actually.
        difference = y_edge - y_other_body
        # Except that if the sign of the penetration is not correct, there is
        # no collision.  I explain why I round in CircularBody.collidesCircle.
        if round(difference, 6) / sign <= 0:
            return None
        # Here there is collision, wrap it up.
        penetration = Vector(0, difference)
        return Collision(abs(difference), collider, self, penetration)
Exemple #30
0
    def _withVerticalEdge(self, x_edge, sign, collider):
        """Sign = -1 if the other body is left ot the edge, and +1 if right.

        """
        # Here I look for the point on the collider's circle that's exactly
        # left or right of its center.  If there is collision, that's because
        # of this point.
        x_other_body = collider.pos.x - sign * collider.radius
        # Here I am already measuring the penetration, actually.
        difference = x_edge - x_other_body
        # Except that if the sign of the penetration is not correct, there is
        # no collision.  I explain why I round in CircularBody.collidesCircle.
        if round(difference, 6) / sign <= 0:
            return None
        # Here there is collision, wrap it up.
        penetration = Vector(difference, 0)
        return Collision(abs(difference), collider, self, penetration)