Last active
August 29, 2015 14:07
-
-
Save nati/9b17ac842bb16dbbc43f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import time | |
import sys | |
HEIGHT = 50 | |
WIDTH = 200 | |
SCALE = 7 | |
X = 0 | |
Y = 1 | |
Z = 2 | |
points = [ | |
[-1, -1, 1], | |
[-1, 1, 1], | |
[1, 1, 1], | |
[1, -1, 1], | |
[-1, -1, -1], | |
[-1, 1, -1], | |
[1, 1, -1], | |
[1, -1, -1] | |
] | |
lines = [ | |
[0, 1], | |
[1, 2], | |
[2, 3], | |
[0, 3], | |
[4, 5], | |
[5, 6], | |
[6, 7], | |
[7, 4], | |
[0, 4], | |
[1, 5], | |
[2, 6], | |
[3, 7], | |
] | |
def matrix_rotate_x(a): | |
return [[1, 0, 0], | |
[0, math.cos(a), -math.sin(a)], | |
[0, math.sin(a), math.cos(a)]] | |
def matrix_rotate_y(a): | |
return [[math.cos(a), 0, math.sin(a)], | |
[0, 1, 0], | |
[-math.sin(a), 0, math.cos(a)]] | |
def mult_m_p(m, p): | |
x, y, z = p | |
r1 = sum([m[0][0] * x, m[0][1] * y, m[0][2] * z]) | |
r2 = sum([m[1][0] * x, m[1][1] * y, m[1][2] * z]) | |
r3 = sum([m[2][0] * x, m[2][1] * y, m[2][2] * z]) | |
return [r1, r2, r3] | |
def projection(p): | |
cx, cy = WIDTH/2, HEIGHT/2 | |
p = p[X]*SCALE, p[Y]*SCALE, p[Z]*SCALE | |
p = [int(p[X] + cx), int(p[Y] + cy)] | |
return p | |
def draw_point(p, char="#"): | |
sys.stdout.write("\033[%i;%iH%s" % (p[Y], p[X], char)) | |
def draw_line(p1, p2): | |
steep = abs(p2[Y] - p1[Y]) > abs(p2[X] - p1[X]) | |
if steep: | |
p1[X], p1[Y] = p1[Y], p1[X] | |
p2[X], p2[Y] = p2[Y], p2[X] | |
if p1[X] > p2[X]: | |
p1[X], p2[X] = p2[X], p1[X] | |
p1[Y], p2[Y] = p2[Y], p1[Y] | |
dx = p2[X] - p1[X] | |
dy = abs(p2[Y] - p1[Y]) | |
error = dx / 2.0 | |
y = p1[Y] | |
if p1[Y] < p2[Y]: | |
ystep = 1 | |
else: | |
ystep = -1 | |
for x in range(p1[X], p2[X]): | |
if steep: | |
draw_point([y, x]) | |
else: | |
draw_point([x, y]) | |
error = error - dy | |
if error < 0: | |
y = y + ystep | |
error = error + dx | |
def clear_screen(): | |
sys.stdout.write("\033[2J") | |
clear_screen() | |
i = 0.0 | |
while True: | |
clear_screen() | |
mx = matrix_rotate_x(i) | |
my = matrix_rotate_y(i*10) | |
cur_points = [mult_m_p(mx, p) for p in points] | |
cur_points = [mult_m_p(my, p) for p in cur_points] | |
index = 0 | |
for point in cur_points: | |
draw_point(projection(point), index) | |
index += 1 | |
for line in lines: | |
draw_line(projection(cur_points[line[0]]), projection(cur_points[line[1]])) | |
sys.stdout.flush() | |
i += math.pi / 100.0 | |
time.sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment