Sun, 10 Dec 2017 15:45:50 +0200
Parsing function complete
0 | 1 | class Vertex: |
2 | def __init__(self, x, y, z): | |
3 | self.x, self.y, self.z = x, y, z | |
4 | def __repr__(self): | |
5 | return str.format('Vertex({!r}, {!r}, {!r})', self.x, self.y, self.z) | |
6 | def distance_to(self, other): | |
7 | # can't use hypot because of 3 arguments | |
8 | from math import sqrt | |
9 | return sqrt( | |
10 | (self.x - other.x) ** 2 + | |
11 | (self.y - other.y) ** 2 + | |
12 | (self.z - other.z) ** 2 | |
13 | ) | |
14 | ||
15 | class LineSegment: | |
16 | def __init__(self, v1, v2): | |
17 | self.v1, self.v2 = v1, v2 | |
18 | def __repr__(self): | |
19 | return str.format('LineSegment({!r}, {!r})', self.v1, self.v2) | |
20 | ||
1 | 21 | class Polygon: |
22 | def __init__(self, vertices): | |
23 | self.vertices = vertices | |
24 | def __repr__(self): | |
25 | return str.format('Polygon({!r})', self.vertices) | |
26 | ||
0 | 27 | def is_real(number): |
28 | return isinstance(number, int) or isinstance(number, float) | |
29 | ||
30 | class TransformationMatrix: | |
31 | ''' | |
32 | A 3×3 matrix forming the top-left portion of a full 4×4 transformation | |
33 | matrix. | |
34 | ''' | |
35 | def __init__(self, values): | |
36 | assert(all(is_real(x) for x in values)) | |
37 | assert len(values) == 9 | |
38 | self.values = values | |
39 | def __repr__(self): | |
40 | return str.format('TransformationMatrix({!r})', self.values) | |
41 | def __getitem__(self, index): | |
42 | return self.values[index] | |
43 | ||
44 | def complete_matrix(matrix, anchor): | |
45 | ''' | |
46 | Combines a 3×3 matrix and an anchor vertex into a full 4×4 | |
47 | transformation matrix. | |
48 | ''' | |
49 | return [ | |
50 | matrix[0], matrix[1], matrix[2], anchor.x, | |
51 | matrix[3], matrix[4], matrix[5], anchor.y, | |
52 | matrix[6], matrix[7], matrix[8], anchor.z, | |
53 | 0, 0, 0, 1, | |
54 | ] | |
55 | ||
56 | def transform(vertex, transformation_matrix): | |
57 | ''' | |
58 | Transforms a vertex by a 4×4 transformation matrix. | |
59 | ''' | |
60 | u = transformation_matrix[0] * vertex.x \ | |
61 | + transformation_matrix[1] * vertex.y \ | |
62 | + transformation_matrix[2] * vertex.z \ | |
63 | + transformation_matrix[3] | |
64 | v = transformation_matrix[4] * vertex.x \ | |
65 | + transformation_matrix[5] * vertex.y \ | |
66 | + transformation_matrix[6] * vertex.z \ | |
67 | + transformation_matrix[7] | |
68 | w = transformation_matrix[8] * vertex.x \ | |
69 | + transformation_matrix[9] * vertex.y \ | |
70 | + transformation_matrix[10] * vertex.z \ | |
71 | + transformation_matrix[11] | |
72 | return Vertex(u, v, w) |