def main():
    r = eval(input("What is the radius of your sphere?  "))
    s = Sphere(r)
    A = s.surfaceArea()
    V = s.volume()
    print("The volume of your sphere is {0:0.1f}.".format(V))
    print("The area of your sphere is {0:0.1f}.".format(A))
Exemple #2
0
def main():
    radius = getInputs()
    sphere = Sphere(radius)
    surface = sphere.surfaceArea()
    vol = sphere.volume()

    print("\nSurface Area: {0:0.3f} \nVolume: {1:0.3f}".format(surface, vol))
 def create(cls, name):
     if name == '1' or name == Sphere().name:
         return Sphere()
     elif name == '2' or name == RegularOctahedron().name:
         return RegularOctahedron()
     else:
         raise VolumeCalculatorException(name + ' は無効です.')
def main():
    print("This program calculates the volume and surface area of a sphere.")
    radius = eval(input("Please enter a radius: "))
    sphere = Sphere(radius)

    print("The volume is", sphere.volume(), " and the surface area is",
          sphere.surfaceArea())
def main(args):
    radius = int(args[1])

    print("The radius of the sphere is %d" % (radius))
    s1 = Sphere(radius)
    print("The surface area of sphere is ", s1.surfaceArea())
    print("The volume of sphere is ", s1.volume())
    def __init__(self):
        self.vp = ViewPlane()

        pos = Vector()
        pos.x = 0
        pos.y = 300
        pos.z = -20
        self.sphere = Sphere(pos, 200)

        self.tracer = SphereTracer(self)
        self.mul_tracer = SpheresTracer(self)

        self.spheres = []

        pos1 = Vector()
        pos1.x = 0
        pos1.y = 100
        self.spheres.append(Sphere(pos1, 125))

        pos2 = Vector()
        pos2.x = 50
        pos2.y = 150
        self.spheres.append(Sphere(pos2, 120))

        self.spheres[0].color.g = 200
        self.spheres[0].color.b = 200
        self.spheres[1].color.b = 200
Exemple #7
0
 def test_pattern_object_and_pattern_transformation(self):
     shape = Sphere()
     shape.transform = Transformations.scaling(2, 2, 2)
     pattern = Pattern.test_pattern()
     pattern.transform = Transformations.translation(0.5, 1, 1.5)
     c = pattern.pattern_at_shape(shape, Point(2.5, 3, 3.5))
     self.assertEqual(c, Color(0.75, 0.5, 0.25))
Exemple #8
0
def colors(nx, ny, ns):
    llc = Vector(-2.0, -1.0, -1.0)
    hor = Vector(4.0, 0.0, 0.0)
    ver = Vector(0.0, 2.0, 0.0)
    org = Vector()

    spheres = [
        Sphere(Vector(0, 0, -1), 0.5),
        Sphere(Vector(0, -100.5, -1), 100)
    ]
    world = HitableList(spheres)
    camera = Camera()

    for j in xrange(ny - 1, 0, -1):
        for i in xrange(nx):
            vec = Vector()
            for s in xrange(ns):
                u = (i + random()) / float(nx)
                v = (j + random()) / float(ny)
                ray = camera.get_ray(u, v)
                vec = vec + color(ray, world)

            vec = vec / Vector(ns, ns, ns)
            ir = int(255 * vec.x)
            ig = int(255 * vec.y)
            ib = int(255 * vec.z)

            yield (ir, ig, ib)
Exemple #9
0
def colored_sphere(i, j, nx, ny):
    s = Sphere(Vec3(0, 0, -1), 0.5)
    r = origin_to_pixel(i, j, nx, ny)
    if s.hit(r, 0, float("inf")):
        return (s.normal + Vec3(1, 1, 1)) * 255.99 / 2
    else:
        return blue_to_white(i, j, nx, ny)
Exemple #10
0
def three_spheres(i, j, nx, ny, num_samples=100):
    s1 = Sphere(Vec3(0, 0, -1), 0.5, Lambertian(Vec3(0.1, 0.2, 0.5)))
    s2 = Sphere(Vec3(0, -100.5, -1), 100, Lambertian(Vec3(0.8, 0.8, 0.0)))
    s3 = Sphere(Vec3(-1, 0, -1), 0.5, Dielectric(2.5))
    s4 = Sphere(Vec3(1, 0, -1), 0.5, Metal(Vec3(0.8, 0.6, 0.2), 0.0))
    spheres = HitableList([s1, s2, s3, s4])
    cam = Camera()

    # cam = Camera(origin = Vec3(0, 0, 0),
    # 			lower_left_corner = Vec3(-3, -1.5, -1),
    # 			horizontal = Vec3(6, 0, 0),
    # 			vertical = Vec3(0, 3, 0))

    def color(r, world, depth):
        if world.hit(r, 0.001, float("inf")):
            scattered, attenuation = world.matrl.scatter(
                r, world.p, world.normal)
            if not scattered or depth >= 50:
                return Vec3(0, 0, 0)
            return color(scattered, world, depth + 1) * attenuation
        else:
            v = r.direction().unit_vector(
            )  # use y-coordinate of unit direction to scale blueness
            t = (v.y() + 1) / 2  # ranges between 0 and 1
            return Vec3(255.99, 255.99, 255.99) * (1 - t) + Vec3(
                255.99 * 0.5, 255.99 * 0.7, 255.99) * t

    col = Vec3(0, 0, 0)
    for k in range(num_samples):
        col += color(
            cam.get_ray((i + random.random()) / nx,
                        (j + random.random()) / ny), spheres, 0)

    return col / num_samples
Exemple #11
0
def render_random_spheres(scene):
    total_sphere = random.randint(1, 15)

    light = Light(Color(1.0, 1.0, 1.0, 1.0), 1.0)
    light.transform.position = Vector3(0.0, 2.0, -2.0)
    scene.set_light(light)

    for i in range(0, total_sphere):
        s = Sphere(random.randint(10, 200) / 100.0)
        s.transform.position = Vector3(random.randint(-3, 3),
                                       random.randint(-3, 3),
                                       random.randint(2, 10))
        s.albedo = Color(
            float(random.randint(20, 255)) * 1.0 / 255.0,
            float(random.randint(20, 255)) * 1.0 / 255.0,
            float(random.randint(20, 255)) * 1.0 / 255.0, 1.0)
        print("Sphere got color " + str(s.albedo))
        scene.add_objects(s)

    v1 = Vector3(8.0, 0.0, -1.0)
    v2 = Vector3(0.0, 8.0, -3.0)

    animation_velocity = 0.5

    def update_method(t):
        p = Vector3(0.0, 2.0, -2.0)
        p = p.add(v1.multiply(np.cos(animation_velocity * t * np.pi)))
        p = p.add(v2.multiply(np.sin(animation_velocity * t * np.pi)))

        light.transform.position = p

    return update_method
def lerp(nx, ny):
    result = ["P3", f"{nx} {ny}", "255"]

    lower_left_corner = np.array([-2.0, -1.0, -1.0])
    horizontal = np.array([4.0, 0.0, 0.0])
    vertical = np.array([0.0, 2.0, 0.0])
    origin = np.zeros(3)

    s1 = Sphere(np.array([0, 0, -1]), 0.5)
    s2 = Sphere(np.array([0, -100.5, -1]), 100)
    h = HitableList([s1, s2])

    matrix = list()
    for j in range(ny - 1, -1, -1):
        for i in range(nx):
            u = i / nx
            v = j / ny
            r = Ray(origin, lower_left_corner + u * horizontal + v * vertical)
            c = color(r, h)
            ir = int(255.99 * c[0])
            ig = int(255.99 * c[1])
            ib = int(255.99 * c[2])
            matrix.append([ir, ig, ib])
            result.append(f"{ir} {ig} {ib}")

    p = np.array(matrix)
    print(p.shape)
    return result
Exemple #13
0
def main():
    with open("output2.ppm", "w") as f:
        nx, ny, ns = 200, 100, 100
        header = "P3\n{} {}\n255\n".format(nx, ny)
        f.write(header)

        sphere1 = Sphere(Vec3(0, 0, -1), 0.5)
        sphere2 = Sphere(Vec3(0, -100.5, -1), 100)
        world = Hitable_list([sphere1, sphere2])

        for j in range(ny - 1, -1, -1):
            for i in range(0, nx):

                col = Vec3(0, 0, 0)
                for s in range(ns):
                    u = float(i + random()) / float(nx)
                    v = float(j + random()) / float(ny)
                    ray = Camera().get_ray(u, v)
                    col += color(ray, world)

                col /= ns
                col = Vec3(sqrt(col.r()), sqrt(col.g()), sqrt(col.b()))
                ir = int(255.99 * col.r())
                ig = int(255.99 * col.g())
                ib = int(255.99 * col.b())
                line = "{} {} {}\n".format(ir, ig, ib)
                f.write(line)
Exemple #14
0
def diffuse_sphere(i, j, nx, ny, num_samples=100):
    s1 = Sphere(Vec3(-0.75, 0.75, -1), 0.5, Lambertian(Vec3(0.8, 0.3, 0.3)))
    s2 = Sphere(Vec3(0, -100.5, -1), 100, Lambertian(Vec3(0.2, 0.6, 0.2)))
    spheres = HitableList([s1, s2])
    cam = Camera()

    def color(r, world):
        if world.hit(r, 0.001, float("inf")):
            scattered, attenuation = world.matrl.scatter(
                r, world.p, world.normal)
            if scattered:
                return color(scattered, world) * attenuation
            else:
                return Vec3(0, 0, 0)
        else:
            v = r.direction().unit_vector(
            )  # use y-coordinate of unit direction to scale blueness
            t = (v.y() + 1) / 2  # ranges between 0 and 1
            return Vec3(255.99, 255.99, 255.99) * (1 - t) + Vec3(
                255.99 * 0.5, 255.99 * 0.7, 255.99) * t

    col = Vec3(0, 0, 0)
    for k in range(num_samples):
        col += color(
            cam.get_ray((i + random.random()) / nx,
                        (j + random.random()) / ny), spheres)

    return col / num_samples
Exemple #15
0
 def test_intersect3(self):
     origin = Point(0, 2, -5)
     direction = Vector(0, 0, 1)
     r = Ray(origin, direction)
     s = Sphere()
     xs = Intersections([])
     self.assertTrue(s.intersect(r) == xs)
Exemple #16
0
def main():

    nx = 200
    ny = 100
    ns = 30

    f = open("generated_images/first_world.ppm","w")
    f.write("P3\n%d %d\n255\n"%(nx,ny))

    cam = Camera()

    world = Object3DList(
            [Sphere(Vec3(0.0,0.0,-1.0), 0.5),
             Sphere(Vec3(0.0,-100.5,-1.0),100)])

    # Note break with guide convention, vertical pixels start with index 0 at top
    for y in range(0,ny):
        for x in range(0,nx):
            col = Vec3(0.0,0.0,0.0)
            for _ in range(0, ns):
                u = (float(x)+random.random())/float(nx)
                v = (float(y)+random.random())/float(ny)
                r = cam.get_ray(u, v)
                col += color(r, world)

            col /= ns

            f.write(col.color_string(scale=255.99))

    f.close()
Exemple #17
0
 def test_sphere_behind_ray(self):
     r = Ray(Point(0, 0, 5), Vector(0, 0, 1))
     s = Sphere()
     xs = s.intersect(r)
     self.assertEqual(len(xs), 2)
     self.assertEqual(xs[0].t, -6.0)
     self.assertEqual(xs[1].t, -4.0)
Exemple #18
0
 def test_ray_intersect_sphere_tangent(self):
     r = Ray(Point(0, 1, -5), Vector(0, 0, 1))
     s = Sphere()
     xs = s.intersect(r)
     self.assertEqual(len(xs), 2)
     self.assertEqual(xs[0].t, 5.0)
     self.assertEqual(xs[1].t, 5.0)
Exemple #19
0
 def test_ray_originate_inside_sphere(self):
     r = Ray(Point(0, 0, 0), Vector(0, 0, 1))
     s = Sphere()
     xs = s.intersect(r)
     self.assertEqual(len(xs), 2)
     self.assertEqual(xs[0].t, -1.0)
     self.assertEqual(xs[1].t, 1.0)
Exemple #20
0
    def basic(self):
        self.lookfrom = np.array([3.0, 3.0, 2.0])
        self.lookat = np.array([0.0, 0.0, -1.0])
        self.vup = np.array([0.0, 1.0, 0.0])
        self.vfov = 20.0
        # self.aperature = 2.0
        # self.focus_dist = ru.length(self.lookfrom - self.lookat)

        self.camera = Camera(self.img_width, self.img_height, self.lookfrom,
                             self.lookat, self.vup, self.vfov, self.aperature,
                             self.focus_dist)

        mat_ground = Lambertian(np.array([0.8, 0.8, 0.0]))
        mat_center = Lambertian(np.array([0.1, 0.2, 0.5]))
        mat_left = Dielectric(1.5)
        mat_right = Metal(np.array([0.8, 0.6, 0.2]), 0.0)

        self.world.add(Sphere(np.array([0.0, -100.5, -1.0]), 100, mat_ground))
        self.world.add(Sphere(np.array([0.0, 0.0, -1.0]), 0.5, mat_center))
        self.world.add(Sphere(np.array([-1.0, 0.0, -1.0]), 0.5, mat_left))
        self.world.add(Sphere(np.array([-1.0, 0.0, -1.0]), -0.45, mat_left))
        self.world.add(Sphere(np.array([1.0, 0.0, -1.0]), 0.5, mat_right))

        self.world.add(
            BVHNode(self.world.objects, 0, len(self.world.objects), 0, 1))
        self.background = np.array([0.7, 0.8, 1.0])
Exemple #21
0
 def test_pattern_with_both_an_object_and_a_pattern_transformation(self):
     s = Sphere()
     s.set_transform(scale(2, 2, 2))
     p = TestPattern()
     p.set_pattern_transform(translate(0.5, 1, 1.5))
     c = p.pattern_at_shape(s, Point(2.5, 3, 3.5))
     self.assertTrue(c.equals(Color(0.75, 0.5, 0.25)))
Exemple #22
0
 def test_create_subgroup_from_children(self):
     s1 = Sphere()
     s2 = Sphere()
     g = Group()
     g.make_subgroup([s1, s2])
     self.assertEqual(len(g.members), 1)
     self.assertEqual(g.members[0].members, [s1, s2])
Exemple #23
0
 def test_intersect(self):
     r = Ray(Point(0, 0, -5), Vector(0, 0, 1))
     s = Sphere()
     xs = s.intersect(r)
     self.assertEqual(len(xs), 2)
     self.assertEqual(xs[0].object, s)
     self.assertEqual(xs[1].object, s)
Exemple #24
0
    def test_transformation(self):
        s = Sphere()
        self.assertEqual(s.transform, Matrix.identity())

        t = Matrix.translate(2, 3, 4)
        s.transform = t
        self.assertEqual(s.transform, t)
Exemple #25
0
def DrawGLScene():
    initial_time = time.time()

    global box, eyeX, eyeY, eyeZ, tori, ecube, sphere, SHAPE, num, number, drawType, time_between_frames, refresh_time
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()  # Reset The View

    if (SHAPE == "C"):
        if (num != number):
            box = Box(quad_len)
            box.subdivide(number)
            num = number
        scene.drawPrim(box.primitive3d, eyeX, eyeY, eyeZ, angle_h, angle_v,
                       distance, drawType)
    if (SHAPE == "S"):
        if (num != number):
            sphere = Sphere(2, 2, 2)
            sphere = Sphere(2, 2 + number, 2 + number)
            num = number
        scene.drawPrim(sphere.primitive3d, eyeX, eyeY, eyeZ, angle_h, angle_v,
                       distance, drawType)

    scene.draw_xyz_axis()

    time_after_drawing = time.time()
    if ((time_after_drawing - initial_time) < refresh_time):
        time.sleep(refresh_time - (time_after_drawing - initial_time))

    glutSwapBuffers()
Exemple #26
0
def main():
    with open("output.ppm", "w") as f:
        nx, ny, ns = 200, 100, 100
        header = "P3\n{} {}\n255\n".format(nx, ny)
        f.write(header)

        camera = Camera()
        sphere1 = Sphere(Vec3(0.0, 0.0, -1.0), 0.5,
                         Lambertian(Vec3(0.8, 0.3, 0.3)))
        sphere2 = Sphere(Vec3(0.0, -100.5, -1.0), 100.0,
                         Lambertian(Vec3(0.8, 0.8, 0.0)))
        sphere3 = Sphere(Vec3(1.0, 0.0, -1.0), 0.5, Metal(Vec3(0.8, 0.6, 0.2)))
        sphere4 = Sphere(Vec3(-1.0, 0.0, -1.0), 0.5, Metal(Vec3(0.8, 0.8,
                                                                0.8)))

        world = Hitable_list([sphere1, sphere2, sphere3, sphere4])
        for j in range(ny - 1, -1, -1):
            for i in range(nx):
                col = Vec3(0.0, 0.0, 0.0)
                for k in range(0, ns):
                    u = float(i + random()) / float(nx)
                    v = float(j + random()) / float(ny)
                    ray = camera.get_ray(u, v)
                    col += color(ray, world, 0)

                col /= float(ns)
                col = Vec3(sqrt(col.e0), sqrt(col.e1), sqrt(col.e2))
                ir = int(255.99 * col.r())
                ig = int(255.99 * col.g())
                ib = int(255.99 * col.b())
                line = "{} {} {}\n".format(ir, ig, ib)
                f.write(line)
Exemple #27
0
def main():
	with open("output2.ppm", "w") as f:
		nx, ny = 200, 100
		header = "P3\n{} {}\n255\n".format(nx, ny)
		f.write(header)
		lower_left_corner = Vec3(-2.0, -1.0, -1.0)
		horizontal = Vec3(4.0, 0.0, 0.0)
		vertical = Vec3(0.0, 2.0, 0.0)
		origin = Vec3(0.0, 0.0, 0.0)

		sphere1 = Sphere(Vec3(0, 0, -1), 0.5)
		sphere2 = Sphere(Vec3(0, -100.5, -1), 100)
		world = Hitable_list([sphere1, sphere2])

		for j in range(ny-1, -1, -1):
			for i in range(0, nx):
				u = float(i) / float(nx)
				v = float(j) / float(ny)
				direction = lower_left_corner + horizontal * u + vertical * v
				ray = Ray(origin, direction)
				col = color(ray, world)
				ir = int(255.99 * col.r())
				ig = int(255.99 * col.g())
				ib = int(255.99 * col.b())
				line = "{} {} {}\n".format(ir, ig, ib)
				f.write(line)
Exemple #28
0
 def test_intersect_scaled_sphere_with_ray(self):
     r = Ray(Point(0, 0, -5), Vector(0, 0, 1))
     s = Sphere()
     s.transform = Transformations.scaling(2, 2, 2)
     xs = s.intersect(r)
     self.assertEqual(len(xs), 2)
     self.assertEqual(xs[0].t, 3)
     self.assertEqual(xs[1].t, 7)
Exemple #29
0
def two_perlin_spheres() -> Hitable:
    pertext = noise_texture(0.1)
    h_list = list()
    h_list.append(
        Sphere(np.array((0, -1000, 0)), 1000, material.lambertian(pertext)))
    h_list.append(Sphere(np.array((0, 2, 0)), 2, material.lambertian(pertext)))

    return hitable_list(h_list)
 def test_circle_comparison(self):
     s1 = Sphere(10)
     s2 = Sphere.from_diameter(40)
     assert s1 < s2
     assert s2 > s1
     assert s1 != s2
     s3 = eval(repr(s2))
     assert s3 == s2
Exemple #31
0
 def test_stripes_with_an_object_transformation(self):
     black = Color(0, 0, 0)
     white = Color(1, 1, 1)
     s = Sphere()
     s.set_transform(scale(2, 2, 2))
     p = StripePattern(white, black)
     c = p.pattern_at_shape(s, Point(1.5, 0, 0))
     self.assertTrue(c.equals(white))
Exemple #32
0
 def showNormals(s,figm=None,algo='sobel',color=(1,0,0),as2D=False):
   s.getNormals(algo)
   if as2D:
     if figm is None:
       figm = plt.figure()
     I = (s.n.copy()+1.0)*0.5 # make non negative
     I[np.logical_not(s.mask),0] = 0.;
     I[np.logical_not(s.mask),1] = 0.;
     I[np.logical_not(s.mask),2] = 0.;
     plt.imshow(I)
   else:
     if figm is None:
       figm = mlab.figure(bgcolor=(1,1,1)) 
     M = Sphere(2)
     M.plotFanzy(figm,1.0,linewidth=1)
     mlab.points3d(s.n[s.mask,0],s.n[s.mask,1],s.n[s.mask,2],
         scale_factor=0.01, color=color, figure=figm, 
         mode='point',mask_points=1)
   return figm
    def __init__(self, parent=None):
        super(RenderArea, self).__init__(parent)

        self.sphere = Sphere(self)

        self.pen = QPen(QColor(0, 0, 0), 0)
        self.faces_color = QColor(0, 255, 0)
        self.is_light = False
        self.is_clipping = False

        self.setBackgroundRole(QPalette.Base)
        self.setAutoFillBackground(True)
Exemple #34
0
class TestSphereFunctions(unittest.TestCase):

    def setUp(self):
        self.sphere = Sphere(np.array([0,0,0]), 2.0)

    def test_sphere_size(self):
        self.assertEqual(self.sphere.diameter, 2)

    def test_inSphere(self):
        x = [11, 11, 11]
        self.assertFalse(self.sphere.insideSphere(x))

    def test_xyzPoint(self):
        theta = 0
        phi = 0
        predictedXYZ = self.sphere.xyzPoint(theta, phi)
        self.assertTrue(np.array_equal([0,1,0], predictedXYZ))

    def test_reflection(self):
        v = [0,0,1]
        theta = pi/4.0
        phi = pi/2.0
        predictedR = self.sphere.reflection(v, theta, phi)
        self.assertTrue(np.allclose([0,1,0], predictedR, atol=tol))
class RenderArea(QWidget):
    """
    Класс области рисования
    """
    def __init__(self, parent=None):
        super(RenderArea, self).__init__(parent)

        self.sphere = Sphere(self)

        self.pen = QPen(QColor(0, 0, 0), 0)
        self.faces_color = QColor(0, 255, 0)
        self.is_light = False
        self.is_clipping = False

        self.setBackgroundRole(QPalette.Base)
        self.setAutoFillBackground(True)

    def minimumSizeHint(self):
        return QSize(200, 200)

    def sizeHint(self):
        return QSize(400, 400)

    def set_pen_width(self, width):
        self.pen = QPen(self.pen.color(), width)
        self.update()

    def set_pen_color(self, label):
        color = QColorDialog.getColor()
        if color.isValid():
            self.pen = QPen(color, self.pen.width())
            label_palette = QPalette()
            label_palette.setColor(QPalette.WindowText, color)
            label.setPalette(label_palette)
            label.setText("Цвет линии " + color.name())
        self.update()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setPen(self.pen)

        # Пересчитываем сферу
        self.sphere.recalculate()

        # Рисуем
        for face in self.sphere.geom.faces:
            self.draw_item(face, painter)

        # Окантовка виджета
        painter.setPen(self.palette().dark().color())
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))

    def draw_item(self, face, painter):
        is_draw = True
        if self.is_clipping:
            is_draw = self.sphere.is_face_visible(face)
        if is_draw:
            polygon = QPolygon()
            for index, point_index in enumerate(face):
                p1_x = int(self.sphere.geom.points[face[index-1]][0])
                p1_y = int(self.sphere.geom.points[face[index-1]][1])
                p1_z = int(self.sphere.geom.points[face[index-1]][2])

                p2_x = int(self.sphere.geom.points[point_index][0])
                p2_y = int(self.sphere.geom.points[point_index][1])
                p2_z = int(self.sphere.geom.points[point_index][2])

                if self.sphere.projection_name == "front":
                    # Фронтальная проекция (вид спереди) -> z = 0
                    real_p1 = QPoint(p1_x, p1_y)
                    real_p2 = QPoint(p2_x, p2_y)
                elif self.sphere.projection_name == "horizontal":
                    # Горизонтальная проекция (вид сверху) -> y = 0
                    real_p1 = QPoint(p1_x, p1_z)
                    real_p2 = QPoint(p2_x, p2_z)
                elif self.sphere.projection_name == "profile":
                    # Профильная проекция (вид сбоку) -> x = 0
                    real_p1 = QPoint(p1_y, p1_z)
                    real_p2 = QPoint(p2_y, p2_z)
                else:
                    real_p1 = QPoint(p1_x, p1_y)
                    real_p2 = QPoint(p2_x, p2_y)

                # Точки для проволочного рисования
                real_p1.setX(self.width()/2 + real_p1.x())
                real_p1.setY(self.height()/2 - real_p1.y())
                real_p2.setX(self.width()/2 + real_p2.x())
                real_p2.setY(self.height()/2 - real_p2.y())

                # Полигоны для рисования с цветом
                polygon.append(real_p1)
                polygon.append(real_p2)

                if not self.is_light:
                    painter.drawLine(real_p1, real_p2)

            if self.is_light:

                painter.setBrush(self.sphere.get_face_light(face, self.faces_color))
                painter.drawPolygon(polygon)

    def set_projection(self, button):
        self.sphere.projection_name = button.objectName()
        self.update()

    def set_clipping(self, state):
        self.is_clipping = True if state == Qt.Checked else False
        self.update()

    def set_faces_color(self, label):
        color = QColorDialog.getColor()
        if color.isValid():
            self.faces_color = color
            label_palette = QPalette()
            label_palette.setColor(QPalette.WindowText, color)
            label.setPalette(label_palette)
            label.setText("Цвет объекта " + color.name())
        self.update()

    def set_light(self, is_light, clipping_checkbox):
        self.is_light = is_light
        clipping_checkbox.setChecked(self.is_light)
        clipping_checkbox.setDisabled(self.is_light)
        self.update()
Exemple #36
0
if options.zlm:
    vsh = "Zlm"
else:
    vsh = "Xlm"

R       = options.R      # radius of sphere
theta0  = options.theta0 # center point of the 
phi0    = options.phi0   # projection is (theta0, phi0)
l       = options.l      # degree of VSH
m       = options.m      # order of VSH
N_phi   = 12             # arrows in phi direction
N_theta = 12             # arrows in theta direction

# create a new sphere
proj = Sphere(R, theta0, phi0)

# draw the horizon
proj.draw_circle()

# draw aequator, longitudes and latitudes with dashed lines
attrs = [style.linestyle.dashed, deformer.smoothed(0.2), color.cmyk.Periwinkle]
proj.draw_longitudes(5, attrs=attrs)
proj.draw_latitudes(10, attrs=attrs)
proj.draw_curve(zip([0]*100, linspace(0,2*pi,100)), attrs=[deformer.smoothed(0.2), color.cmyk.Periwinkle])
proj.draw_curve(zip(linspace(0,2*pi,100), [0]*100), attrs=[deformer.smoothed(0.2), color.cmyk.Periwinkle])

# set point northpole
proj.draw_point(0,pi/2, attrs=[color.cmyk.BrickRed])

# draw the vector field
Exemple #37
0
#    figm1 = rgbd.showNormals(as2D=True); 
#    figm1.show()
#    plt.show()

#    plt.show()
#    figm2 = rgbd.showWeightedNormals(algo=algo)
#    fig = rgbd.showAxialSigma()
#    fig = rgbd.showLateralSigma(theta=30.0)
    #fig = rgbd.bilateralDepthFiltering(theta=30.0)
#    figm0 = rgbd.showPc(showNormals=True,algo=algo)
#    figm1 = rgbd.showNormals()


    # show raw normals
    figm1 = mlab.figure(bgcolor=(1,1,1))
    M = Sphere(2)
    M.plotFanzy(figm1,1.0) 
    from js.utils.plot.colors import colorScheme
    rgbd.n[2,:] *= -1.
    figm1=rgbd.showNormals(figm=figm1,color=colorScheme("labelMap")["orange"])
    # show clustered normals
    figm3 = mlab.figure(bgcolor=(1,1,1))
    M = Sphere(2)
    M.plotFanzy(figm1,1.0) 
    mlab.points3d(n[0,:],n[1,:],n[2,:],-z[-1,:],colormap='jet',
            mode='point')
#    for k in range(K):
#      ids = z[-1,:]==k
#      if np.count_nonzero(ids) > 0:
#        mlab.points3d(n[0,ids],n[1,ids],n[2,ids],color=((float(k)/K),0,0),
#            mode='point')
Exemple #38
0
y_range = -1e10, 1e10
z_range = -1e10, 1e10
x_speedmax = 10e3
y_speedmax = 10e3
z_speedmax = 10e3

M_EARTH = 5.97219e24
M_MOON = 7.34767309e22
PERIOD = 27.321582 * 24 * 60 * 60
MOON_DIS_TO_EARTH = 384405e3
EARTH_DIS_TO_BARYCENTER = M_MOON * MOON_DIS_TO_EARTH / (M_MOON + M_EARTH)
MOON_DIS_TO_BARYCENTER = MOON_DIS_TO_EARTH - EARTH_DIS_TO_BARYCENTER
EARTH_SPEED = 2 * np.pi * EARTH_DIS_TO_BARYCENTER / PERIOD
MOON_SPEED = 2 * np.pi * MOON_DIS_TO_BARYCENTER / PERIOD

earth = Sphere(radius=6.371e3, mass=5.97219e24)
moon = Sphere(radius=1.7374e3, mass=7.34767309e22)
earth.pos = np.array([-EARTH_DIS_TO_BARYCENTER, 0, 0])
moon.pos = np.array([MOON_DIS_TO_BARYCENTER, 0, 0])
earth.vel = np.array([0, -EARTH_SPEED, 0])
moon.vel = np.array([0, MOON_SPEED, 0])

pospriors = [UniformPrior(x_range[0], x_range[1]), UniformPrior(y_range[0], y_range[1]), GaussianPrior(0, 5e3)]
velpriors = [UniformPrior(0, x_speedmax), UniformPrior(0, y_speedmax), UniformPrior(0, z_speedmax)]

#asteroids = spawn_asteroids(num_asteroids, pospriors, velpriors)
#asteroid_field = spawn_edge_asteroids(num_asteroids_per_edge, pospriors, velpriors, 0, x_range[0])
#asteroid_field = asteroid_field.append_field(spawn_edge_asteroids(num_asteroids_per_edge, pospriors, velpriors, 0, x_range[1]))
#asteroid_field = asteroid_field.append_field(spawn_edge_asteroids(num_asteroids_per_edge, pospriors, velpriors, 1, y_range[0]))
#asteroid_field = asteroid_field.append_field(spawn_edge_asteroids(num_asteroids_per_edge, pospriors, velpriors, 1, y_range[1]))
edges = np.array([x_range, y_range, [0, 0]])
Exemple #39
0
 def __init__(self, filePath):
     self.width = 0
     self.height = 0
     self.materials = []
     self.lights = []
     self.spheres = []
     f = open(filePath)
     section = ''
     for line in f:
         l = line.strip()
         if section == '':
             if len(l) != 0:
                 if l[:2] != '//':
                     section = l
         else:
             if section.find('Scene') != -1:
                 if l == '{':
                     pass
                 elif l == '}':
                     section = ''
                 else:
                     words = l.split('=')
                     if words[0] == 'Width':
                         self.width = convertStr(words[1])
                     elif words[0] == 'Height':
                         self.height = convertStr(words[1])
             elif section.find('Material') != -1:
                 if l == '{':
                     tempMat = Material()
                 elif l == '}':
                     self.materials.append(tempMat)
                     section = ''
                 else:
                     words = l.split('=')
                     if words[0] == 'Diffuse':
                         params = words[1].split()
                         tempMat.setDiffuse(Color(convertStr(params[0]),convertStr(params[1]),convertStr(params[2])))
                     elif words[0] == 'Reflection':
                         tempMat.setReflection(convertStr(words[1]))
                     elif words[0] == 'Id':
                         tempMat.setId(convertStr(words[1]))
             elif section.find('Sphere') != -1:
                 if l == '{':
                     tempSphere = Sphere()
                 elif l == '}':
                     self.spheres.append(tempSphere)
                     section = ''
                 else:
                     words = l.split('=')
                     if words[0] == 'Center':
                         params = words[1].split()
                         tempSphere.setPosition(Point(convertStr(params[0]),convertStr(params[1]),convertStr(params[2])))
                     elif words[0] == 'Size':
                         tempSphere.setSize(convertStr(words[1]))
                     elif words[0] == 'Material':
                         tempSphere.setMaterial(convertStr(words[1]))
             elif section.find('Light') != -1:
                 if l == '{':
                     tempLight = Light()
                 elif l == '}':
                     self.lights.append(tempLight)
                     section = ''
                 else:
                     words = l.split('=')
                     if words[0] == 'Position':
                         params = words[1].split()
                         tempLight.setPosition(Point(convertStr(params[0]),convertStr(params[1]),convertStr(params[2])))
                     elif words[0] == 'Intensity':
                         params = words[1].split()
                         tempLight.setIntensity(Color(convertStr(params[0]),convertStr(params[1]),convertStr(params[2])))
Exemple #40
0
 def setUp(self):
     self.sphere = Sphere(np.array([0,0,0]), 2.0)