示例#1
0
 def setUp(self):
     """
     Initial state before each test.
     """
     self.tr1 = triangle.Triangle((7, 1), (1, 9), (1, 1))
     self.tr2 = triangle.Triangle((3.0, 0.0), (0.0, 4.0), (0.0, 0.0))
     self.floattest = triangle.Triangle((3.3, 0.0), (0.2, 4.2), (0.0, 0.0))
示例#2
0
def test_triangle():
    """
    test triangle and search count of errors
    :return: int
    """
    errors = 0
    try:
        import triangle
        import point
    except:
        errors += 1
    try:
        triangle = triangle.Triangle(point.Point(1, 1), point.Point(3, 1),\
                                     point.Point(2, 3))
    except:
        errors += 1
    try:
        print(triangle.is_triangle())
    except:
        errors += 1
    try:
        print(triangle.perimeter())
    except:
        errors += 1
    try:
        print(triangle.area())
    except:
        errors += 1
    try:
        print(triangle)
    except:
        errors += 1
    return errors
示例#3
0
    def run(self):

        # Succesively add a new polygon that contributes to reduce overall error
        # until stopping criteria is achieved

        min_err = self.fitness(self.source)
        cur = copy.deepcopy(self.source)
        improvements = 0

        for i in range(self.iterations):

            next = copy.deepcopy(cur)

            if self.type == 1:

                c = circle.Circle(self.height, self.width, 0.1)
                info = c.getInfo()

                cv2.circle(cur, info[0], info[1], info[2], -1)
                cv2.addWeighted(cur, info[3], next, 1 - info[3], 0, next)

            elif self.type == 2:

                e = ellipse.Ellipse(self.height, self.width, 0.1)
                info = e.getInfo()

                cv2.ellipse(cur, info[0], info[1], info[2], 0, 360, info[3],
                            -1)
                cv2.addWeighted(cur, info[4], next, 1 - info[4], 0, next)

            elif self.type == 3:

                t = triangle.Triangle(self.height, self.width, 0.1)
                info = t.getInfo()

                cv2.fillConvexPoly(cur, np.asarray(info[0]), info[1])
                cv2.addWeighted(cur, info[2], next, 1 - info[2], 0, next)

            elif self.type == 4:

                r = quadrilateral.Quadrilateral(self.height, self.width, 0.1)
                info = r.getInfo()

                cv2.fillConvexPoly(cur, np.asarray(info[0]), info[1])
                cv2.addWeighted(cur, info[2], next, 1 - info[2], 0, next)

            # Compute dissimilarity
            err = self.fitness(next)

            # Update the solution that provides more fitness
            if err < min_err:
                min_err = err
                improvements = improvements + 1
                cur = copy.deepcopy(next)
                cv2.imwrite(
                    "Refine_Error_" + str(i) + "_" + str(min_err) + ".jpg",
                    cur)

            if improvements == self.maximprovements:
                break
	def __init__(self, filename):
		self.filename = filename
		self.done = False

		self.triangles = []
		scene = pyassimp.load(self.filename, pyassimp.postprocess.aiProcess_Triangulate)

		if scene:
			for index, mesh in enumerate(scene.meshes):
				for num in range(len(mesh.faces)):
					face = mesh.faces[num]
					if face.size == 3:
						vertex = [glm.vec3(), glm.vec3(), glm.vec3()]
						vertex[0].x = mesh.vertices[face[0], 0]
						vertex[0].y = mesh.vertices[face[0], 1]
						vertex[0].z = mesh.vertices[face[0], 2]
						vertex[1].x = mesh.vertices[face[1], 0]
						vertex[1].y = mesh.vertices[face[1], 1]
						vertex[1].z = mesh.vertices[face[1], 2]
						vertex[2].x = mesh.vertices[face[2], 0]
						vertex[2].y = mesh.vertices[face[2], 1]
						vertex[2].z = mesh.vertices[face[2], 2]
						self.triangles.append(triangle.Triangle(glm.vec3(vertex[0].x, vertex[0].y, vertex[0].z), glm.vec3(vertex[1].x, vertex[1].y, vertex[1].z), glm.vec3(vertex[2].x, vertex[2].y, vertex[2].z), material.Material()))

			self.done = True
示例#5
0
def readTexture(line):
    split = line.split()
    texture = []
    for i in range(1, len(split)):
        texture.append(split[i].split('/')[1])
    triangle = tr.Triangle(texture[0], texture[1], texture[2])
    return triangle
示例#6
0
    def triangulate_cdt(vertices, segment_loops):
        assert len(segment_loops) > 0
        triangles = []

        t = shewchuk_triangle.Triangle()

        boundary_offset = len(segment_loops[0])
        points = [(sv.u, sv.v) for sv in vertices]
        markersBoundary = [1] * boundary_offset
        markersInner = [0] * (len(points) - boundary_offset)
        markers = markersBoundary + markersInner
        segments = []
        for segment_loop in segment_loops:
            segments += segment_loop

        t.set_points(points, markers=markers)
        t.set_segments(segments)

        t.triangulate(mode='pzQ')

        for triNode in t.get_triangles():
            ([i0, i1, i2], neighbors, attri) = triNode
            triangles.append((i0, i1, i2))

        return triangles
示例#7
0
def readTextureInTriangl(line):
    split = line.split(' ')
    texture = []
    for i in range(2, len(split)):
        texture.append(split[i])
    triangle = tr.Triangle(texture[0], texture[1], texture[2], texture[0],
                           texture[1], texture[2])
    return triangle
示例#8
0
def create_random_triangles(size, num_triangles, color_type):
    import triangle
    triangles = []
    for x in range(num_triangles):
        coords = []
        color = []
        for i in range(3):
            coords.append(random.randint(0, size.x))
            coords.append(random.randint(0, size.y))
        if color_type == GRAY_SCALE:
            t = triangle.Triangle(coords, random.randint(0, 255),
                                  random.randint(0, 255))
        else:
            for i in range(3):
                color.append(random.randint(0, 255))
            t = triangle.Triangle(coords, tuple(color), random.randint(0, 255))
        triangles.append(t)
    return triangles
 def create_model(self, model, position):
     if model.done:
         for index in range(len(model.triangles)):
             self.primitives.append(
                 triangle.Triangle(
                     position + model.triangles[index].vertex1,
                     position + model.triangles[index].vertex2,
                     position + model.triangles[index].vertex3,
                     diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68))))
示例#10
0
 def test_instance_of_triangle_with_values_of_coordinates_that_not_number_negative(
         self):
     """
     Negative test to check exception by putting not numeric values in coordinates.
     """
     with self.assertRaises(ValueError) as raised_exception:
         triangle.Triangle((1, 2), (2, (3, )), ('c', 5))
     self.assertEqual(raised_exception.exception.args[0],
                      'Coordinate value must be number',
                      'Values of exception wrong')
示例#11
0
 def test_instace_of_triangle_with_coordinates_that_not_tuples_negative(
         self):
     """
     Negative test to check exception by putting not correct type in __init__.
     """
     with self.assertRaises(TypeError) as raised_exception:
         triangle.Triangle((1, 2), [2, 3], [3, 4])
     self.assertEqual(raised_exception.exception.args[0],
                      'Coordinates must be in tuple',
                      'Values of exception wrong')
示例#12
0
 def test_instance_of_triangle_with_coordinates_with_values_ne_2_negative(
         self):
     """
     Negative test to check exception by putting point with length not equal 2.
     """
     with self.assertRaises(TypeError) as raised_exception:
         triangle.Triangle((1, 2, 3), (2, (3, )), ('c', 5))
     self.assertEqual(raised_exception.exception.args[0],
                      'Coordinates must have only 2 values',
                      'Values of exception wrong')
示例#13
0
    def __init__(self, width, height, fps):
        game_mouse.Game.__init__(self, "Shapes", width, height, fps)

        self.sun = circle.Circle(0, 0, 150, (255, 255, 0))
        self.sky = rectangle.Rectangle(600, 400, 0, 0, (20, 160, 255))
        self.houseBody = rectangle.Rectangle(400, 250, 100, 200,
                                             (247, 210, 45))
        self.door = rectangle.Rectangle(70, 150, 265, 300, (64, 52, 12))
        self.roof = triangle.Triangle([(300, 50), (550, 200), (50, 200)],
                                      (117, 8, 8))
        return
示例#14
0
def test_simple2():

    # a single triangle
    t = triangle.Triangle()
    pts = [(0., 0.), (1., 0.), (1., 2.)]
    t.set_points(pts)
    seg = [(0, 1), (1, 2), (2, 0)]
    t.set_segments(seg)
    t.triangulate(area=0.5, mode='pzq27eQ')
    print('number of points/triangles: %d/%d' %
          (t.get_num_points(), t.get_num_triangles()))
示例#15
0
def crea_figura(tipus):
    if (tipus == 'C'):
        fig = cercle.Cercle()
    elif (tipus == 'T'):
        fig = triangle.Triangle()
    elif (tipus == 'R'):
        fig = rectangle.Rectangle()
    else:
        raise Exception('Tipus de figura no valid')
    fig.llegeix()
    return fig
示例#16
0
def readEdgesWithTextures(line):
    split = line.split()
    vertexes = []
    textures = []
    for i in range(1, len(split)):
        indexesBySlash = split[i].split('/')
        vertexes.append(indexesBySlash[0])
        textures.append(indexesBySlash[1])
    triangle = tr.Triangle(vertexes[0], vertexes[1], vertexes[2], vertexes[0],
                           vertexes[1], vertexes[2], textures[0], textures[1],
                           textures[2])
    return triangle
示例#17
0
 def test_instance_of_triangle_with_coordinates_that_do_not_form_triangle_negative(
         self):
     """
     Negative test to check exception by putting incorrect coordinetes to form a triangle.
     And check correct output.
     """
     with self.assertRaises(ValueError) as raised_exception:
         triangle.Triangle((3.0, 0.0), (4.0, 0.0), (5.0, 0.0))
     self.assertEqual(
         raised_exception.exception.args[0],
         'Points ((3.0, 0.0), (4.0, 0.0), (5.0, 0.0)) do not form a triangle',
         'Values of exception wrong')
示例#18
0
    def test_privat_method_of_triangle_length_calculate_with_2_or_more_same_points_negative(
            self):
        """
        Negative test to check exception by putting incorrect coordinates to form triangle.
        And check correct output.
        """
        with self.assertRaises(ValueError) as raised_exception:
            triangle.Triangle((3.0, 0.0), (0.0, 0.0), (0.0, 0.0))

        self.assertEqual(
            raised_exception.exception.args[0],
            'Cannot form triangle. Because coordinates '
            '((0.0, 0.0), (0.0, 0.0)) are the same',
            'Values of exception wrong')
示例#19
0
def main():

    #CREATE A SHAPE: red, border (1), name: Generic Shape
    my_shape = shape.Shape("red", 1, "Generic Shape")

    #CREATE A CIRCLE: blue, border (2), name: Circle
    my_circle = circle.Circle("blue", 2, "Circle")

    #CREATE A SQUARE: yellow, border (3), name: Square
    my_triangle = triangle.Triangle("yellow", 3, "Triangle")

    #CREATE A TRIANGLE: orange, border (4), name: Triangle
    my_square = square.Square("orange", 4, "Square")

    #ADD CODE TO SET THE APPROPRIATE ATTRIBUTES OF EACH SUBCLASS:
    #CIRCLE: RADIUS = 4
    #SQUARE: SIDE = 5
    #TRIANGLE: BASE = 4, HEIGHT = 10
    my_circle.set_radius(10)
    my_triangle.set_height(5)
    my_triangle.set_base(4)
    my_square.set_side(10)

    #ADD CODE TO PRINT THE VALUES OF EACH SHAPE, INCLUDING SHAPE
    shapes_list = []
    shapes_list.append(my_shape)
    shapes_list.append(my_circle)
    shapes_list.append(my_triangle)
    shapes_list.append(my_square)

    for shapes in shapes_list:
        print(shapes)

    #ADD CODE TO PRINT THE AREA OF THE CIRCLE, SQUARE, AND TRIANGLE

    for shapes in shapes_list:
        if isinstance(shapes, circle.Circle):
            print("Circle circumference is:", shapes.calc_circumference())
        elif isinstance(shapes, triangle.Triangle):
            print("Triangle area:", shapes.calc_area())
        elif isinstance(shapes, square.Square):
            print("Square perimeter:", shapes.calc_perimeter())

    print(my_circle.calc_area())
    print(my_square.calc_area())
    print(my_triangle.calc_area())
示例#20
0
def xtest_bad():

    pts = [(0.0, 0.0), (0.00012747326699555811, 0.0),
           (-0.0084667962363287295, 0.0035466702907514828),
           (-0.017061080350639229, 0.0070933376551251849),
           (-0.025655349853963515, 0.010640007945876669),
           (-0.034249619357287805, 0.014186678236628149),
           (-0.042843896166105191, 0.01773334706419074),
           (-0.042843896166105191, 0.01773334706419074),
           (-0.034275119855081401, 0.014186677066077038),
           (-0.025706336238564498, 0.010640008531152224),
           (-0.017137552622047594, 0.0070933399962274102),
           (-0.0085687836165169017, 0.0035466685349248139)]
    segs = [(i, (i + 1) % len(pts)) for i in range(len(pts))]
    t = triangle.Triangle()
    t.set_points(pts)
    t.set_segments(segs)
    t.triangulate(mode='pz', area=None)
示例#21
0
def triangulate_dt(vertices):
    triangles = []

    t = shewchuk_triangle.Triangle()

    points = [(sv.u, sv.v) for sv in vertices]
    markers = [1] * len(points)
    segments = [(i, (i + 1) % len(vertices)) for i in range(len(vertices))]

    t.set_points(points, markers=markers)
    t.set_segments(segments)

    t.triangulate(mode='pzQ')

    for triNode in t.get_triangles():
        ([i0, i1, i2], neighbors, attri) = triNode
        triangles.append((i0, i1, i2))

    return triangles
示例#22
0
def getTrinagles():
    f = open('result.txt')
    triangles = []
    for line in f.readlines():
        triangles.append([
            float(point)
            for point in line.replace('[', '').replace(']', '').split(',')
        ])

    newtriangle = []
    for triangle in triangles:
        point1 = gr.Point3d(*triangle[0:3])
        # point1.scale(scalex, scaley, scalez)
        point2 = gr.Point3d(*triangle[3:6])
        # point2.scale(scalex, scaley, scalez)
        point3 = gr.Point3d(*triangle[6:9])
        # point3.scale(scalex, scaley, scalez)
        newtriangle.append(gr.Triangle(point1, point2, point3))
    return newtriangle
示例#23
0
def triangulate(vertices):
    t = triangle.Triangle()

    pointsBoundary = vertices
    markersBoundary = [1] * len(pointsBoundary)
    pointsInner = []
    markersInner = [0] * len(pointsInner)

    points = pointsBoundary + pointsInner
    markers = markersBoundary + markersInner
    t.set_points(points, markers=markers)

    t.triangulate(mode='zQ')

    triangles = []
    for triNode in t.get_triangles():
        ([i0, i1, i2], neighbors, attri) = triNode
        triangles.append((i0, i1, i2))

    return triangles
示例#24
0
    def generateMap(self):
        y = self.posBegin[1]
        control = True
        posYCorrect = y
        contY = 0
        ## Percorre as linhas
        while contY < self.qtdHeigth:
            x = self.posBegin[0]
            contX = 0
            line = []
            ## Fica invertendo entre os dois tipos de triangulos (para cima e para baixo)
            if control == True:
                line.append(
                    triangle.Triangle((x, y), self.side, self.angle, 0,
                                      self.screen, (contY, contX)))
                first = 1
                second = 0

            else:
                line.append(
                    triangle.Triangle((x, y), self.side, self.angle, 1,
                                      self.screen, (contY, contX)))
                first = 0
                second = 1

            posYCorrect = line[-1].getP2()[1]
            x += self.baseTriangle
            contX = 1
            ## Percorre as colunas
            while contX < self.qtdWidth:
                """
                OBS: Como os triangulos tem seus lados com números não inteiros, se colocar pela posição sozinha, vai acabar ficando torto a linha.
                Por isso colocamos o próximo triangulo de acordo com o eixo X do anterior, para todos ficarem alinhados
                """
                line.append(
                    triangle.Triangle((line[-1].getP2()[0], posYCorrect),
                                      self.side, self.angle, first,
                                      self.screen, (contY, contX)))
                contX += 1
                if contX >= self.qtdWidth:
                    break
                line.append(
                    triangle.Triangle((line[-1].getP2()[0], y), self.side,
                                      self.angle, second, self.screen,
                                      (contY, contX)))
                x += (2 * self.baseTriangle)
                contX += 1
            self.listPlaces.append(line)
            ## Soma a base a cada dois triangulos
            if control == True:
                y += 2 * self.heightTriangle
            ## Inverte o tipo do triangulo que começa a linha
            control = not control
            contY += 1

        ##Faz o carregamento de um mapa salvo
        if self.load != False:
            ## Cria um objeto para armazenar cada informação
            things = {}
            ## Le o arquivo
            arq = open(
                os.path.join("pkg", "mesh", "loads", self.load + ".txt"), "r")
            for line in arq:
                ## O formato de cada linha é:
                ## Nome x,y x,y x,y
                values = line.split(" ")
                ## O primeiro dado é o nome do objeto, seguido por varias posicoes
                things[values.pop(0)] = values

            ## Percorre os elementos que foram definidos
            for i in things:
                for j in things[i]:
                    pos = j.split(",")
                    ## Define que naquela posicao vai ter determinado objeto
                    self.listPlaces[int(pos[0])][int(pos[1])].itemInside = i
                    ## Atualiza a cor do lugar
                    self.listPlaces[int(pos[0])][int(pos[1])].updateColor()

            ## Seta as posicoes do robo e do objetivo
            if "Robô" in things:
                pos = things["Robô"][0].split(",")
                self.posAgent = (int(pos[0]), int(pos[1]))
            if "Objetivo" in things:
                pos = things["Objetivo"][0].split(",")
                self.posGoal = (int(pos[0]), int(pos[1]))
示例#25
0
import triangle
import point

if __name__ == '__main__':
    x, y = [float(x) for x in input('Print x and y coordinates: ').split()]
    point1 = point.Point(x, y)
    x, y = [float(x) for x in input('Print x and y coordinates: ').split()]
    point2 = point.Point(x, y)
    x, y = [float(x) for x in input('Print x and y coordinates: ').split()]
    point3 = point.Point(x, y)
    user_triangle = triangle.Triangle(point1, point2, point3)
    if not user_triangle.is_triangle():
        print('This is not triangle')
    else:
        print('This is triangle')
        print('Perimeter is: ' + str(user_triangle.perimeter()))
        print('Area is: ' + str(user_triangle.area()))
示例#26
0
# list of boundary points, going anticlockwise
boundpts = [(i*dx, 0.) for i in range(nx)] + \
           [(lx, j*dy) for j in range(ny)] + \
           [(lx - i*dx, ly) for i in range(nx)] + \
           [(0., ly - j*dy) for j in range(ny)]

nbound = len(boundpts)

# tell the triangulation that these points are on the boundary
boundmarks = [1 for i in range(nbound)]

# generate segments, anticlockwise
boundsegs = [(i, i + 1) for i in range(nbound - 1)] + [(nbound - 1, 0)]

# triangulate the domain
mesh = triangle.Triangle()
mesh.set_points(boundpts, markers=boundmarks)
mesh.set_segments(boundsegs)
mesh.triangulate(area=0.5)

num_points = mesh.get_num_points()
num_cells = mesh.get_num_triangles()

nodes = mesh.get_points() # [[(x, y), marker], ...]
cells = mesh.get_triangles() # [[(i0, i1, i2), (), [a0, a1, ..]], ...]

#
# 2. create the elliptic solver
#

# cell arrays defining the PDE
    def load(self):
        # 3D Model Loader
        # load_model = models.Models("CornellBox-Original.obj")
        # self.create_model(load_model, glm.vec3(0.0, 0.0, -2.0))

        # First Scene: FOUR SPHERE
        # self.primitives.append(sphere.Sphere(glm.vec3(0.0, 0.0, 0.0), 0.2))
        # self.primitives.append(sphere.Sphere(glm.vec3(-0.5, 0.0, -1.0), 0.2))
        # self.primitives.append(sphere.Sphere(glm.vec3(0.0, -0.5, -2.0), 0.2))
        # self.primitives.append(sphere.Sphere(glm.vec3(0.0, 0.5, -3.0), 0.2))

        # Second Scene: TRIFORCE
        # self.primitives.append(triangle.Triangle(glm.vec3(0.0, 0.6, -2.0), glm.vec3(-0.2, 0.3, -2.0), glm.vec3(0.2, 0.3, -2.0)))
        # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -2.0), glm.vec3(-0.4, 0.0, -2.0), glm.vec3(0.0, 0.0, -2.0)))
        # self.primitives.append(triangle.Triangle(glm.vec3(0.2, 0.3, -2.0), glm.vec3(0.0, 0.0, -2.0), glm.vec3(0.4, 0.0, -2.0)))

        # Third Scene: THE WIZARD
        # self.primitives.append(sphere.Sphere(glm.vec3(0.0, 0.5, -3.0), 0.2))
        # self.primitives.append(triangle.Triangle(glm.vec3(0.0, 1.0, -0.5), glm.vec3(-1.0, -2.0, -3.0), glm.vec3(1.0, -2.0, -3.0)))

        # Forth Scene: TRIANGLES
        # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -1.0), glm.vec3(-0.4, 0.0, -1.0), glm.vec3(0.0, 0.0, -1.0)))
        # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -1.5), glm.vec3(-0.4, 0.0, -1.5), glm.vec3(0.0, 0.0, -1.5)))
        # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -2.0), glm.vec3(-0.4, 0.0, -2.0), glm.vec3(0.0, 0.0, -2.0)))
        # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -2.5), glm.vec3(-0.4, 0.0, -2.5), glm.vec3(0.0, 0.0, -2.5)))
        # self.primitives.append(triangle.Triangle(glm.vec3(-0.2, 0.3, -3.0), glm.vec3(-0.4, 0.0, -3.0), glm.vec3(0.0, 0.0, -3.0)))

        # Pathtracer Scene: CORNELL BOX WITH SPHERES
        # BACK
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(1.2, -1.2, -2.5), glm.vec3(-1.2, 1.2, -2.5),
                glm.vec3(-1.2, -1.2, -2.5),
                diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68))))
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(1.2, -1.2, -2.5), glm.vec3(1.2, 1.2, -2.5),
                glm.vec3(-1.2, 1.2, -2.5),
                diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68))))
        # FLOOR
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(-1.2, -1.2, -2.5), glm.vec3(1.2, -1.2, -2.5),
                glm.vec3(-1.2, -1.0, -1.0),
                diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68))))
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(-1.2, -1.0, -1.0), glm.vec3(1.2, -1.2, -2.5),
                glm.vec3(1.2, -1.0, -1.0),
                diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68))))
        # LEFT WALL
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(-1.2, -1.2, -2.5), glm.vec3(-1.2, -1.0, -1.0),
                glm.vec3(-1.2, 1.2, -2.5),
                diffuse.Diffuse(brdf=glm.vec3(0.14, 0.45, 0.091))))
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(-1.2, 1.2, -2.5), glm.vec3(-1.2, -1.0, -1.0),
                glm.vec3(-1.2, 1.2, -1.0),
                diffuse.Diffuse(brdf=glm.vec3(0.14, 0.45, 0.091))))
        # RIGHT WALL
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(1.2, 1.2, -1.0), glm.vec3(1.2, -1.0, -1.0),
                glm.vec3(1.2, 1.2, -2.5),
                diffuse.Diffuse(brdf=glm.vec3(0.63, 0.065, 0.05))))
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(1.2, 1.2, -2.5), glm.vec3(1.2, -1.0, -1.0),
                glm.vec3(1.2, -1.2, -2.5),
                diffuse.Diffuse(brdf=glm.vec3(0.63, 0.065, 0.05))))
        # CEILING
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(-1.2, 1.2, -1.0), glm.vec3(-1.2, 1.2, -2.5),
                glm.vec3(1.2, 1.2, -2.5),
                diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68))))
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(1.2, 1.2, -2.5), glm.vec3(1.2, 1.2, -1.0),
                glm.vec3(-1.2, 1.2, -1.0),
                diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68))))
        # LIGHT
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(-0.5, 1.19, -1.5), glm.vec3(-0.5, 1.19, -2.0),
                glm.vec3(0.5, 1.19, -2.0),
                light.Light(emittance=glm.vec3(30.0, 30.0, 30.0))))
        self.primitives.append(
            triangle.Triangle(
                glm.vec3(0.5, 1.19, -2.0), glm.vec3(0.5, 1.19, -1.5),
                glm.vec3(-0.5, 1.19, -1.5),
                light.Light(emittance=glm.vec3(30.0, 30.0, 30.0))))
        # SPHERES
        self.primitives.append(
            sphere.Sphere(glm.vec3(-0.5, -0.65, -1.5), 0.4, mirror.Mirror()))
        self.primitives.append(
            sphere.Sphere(glm.vec3(0.6, -0.65, -1.8), 0.4,
                          diffuse.Diffuse(brdf=glm.vec3(0.725, 0.71, 0.68))))
示例#28
0
    width, height = texture.size

    draw = ImageDraw.Draw(im)
    cam_position = (0, 0, -5)
    cam_direction = tr.Point(0, 0, 1)

    z_buffer = np.array(list(repeat(float(sys.maxsize), im.width * im.height)))

    z_buffer.shape = (im.width, im.height)

    vertex_list, edges_list_with_text, texture_coordinates,vectorNormal = getPointDraw('african_head.obj')
    vertex_list = rotate_object(vertex_list, (0,20, 0), cam_position)
    vectorNormal = newVectorNormal()

    trianglesWithCoords = [tr.Triangle(get_point(int(triangle.first) - 1),
                                       get_point(int(triangle.second) - 1),
                                       get_point(int(triangle.third) - 1),
                                       get_normal_point(int(triangle.normalFirst) - 1),
                                       get_normal_point(int(triangle.normalSecond) - 1),
                                       get_normal_point(int(triangle.normalThird) - 1),
                                       get_texture_point(int(triangle.textureFirst) - 1),
                                       get_texture_point(int(triangle.textureSecond) - 1),
                                       get_texture_point(int(triangle.textureThird) - 1)) for triangle in
                           edges_list_with_text]

    for triangle in filter(lambda polygon: polygon.direction().angle(cam_direction) > 0,
                           trianglesWithCoords):
        pt.paint_polygon(triangle, draw, texture, z_buffer)

    im.save('african_head.png')
示例#29
0
import triangle
import point

if __name__ == '__main__':
    triangle = triangle.Triangle(point.Point(1, 1), point.Point(3, 1), point.Point(2, 3))
    assert triangle.is_triangle()
    assert triangle.perimeter() == 6.47213595499958
    assert triangle.area() == 2.0
示例#30
0
# coding: utf8
import rectangles

square2 = rectangles.Square(2)

print(square2.summary())

import triangle

triangle = triangle.Triangle(2, 4, 4)
print(triangle.summary())