Skip to content

Instantly share code, notes, and snippets.

@buhii
Created August 14, 2011 01:27
Show Gist options
  • Save buhii/1144466 to your computer and use it in GitHub Desktop.
Save buhii/1144466 to your computer and use it in GitHub Desktop.
cube graphics in nodebox with hidden surface removal
"""
classes for vertex, rectangle
"""
class Vertex(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
if isinstance(other, Vertex):
x, y, z = other.x, other.y, other.z
elif isinstance(other, tuple) or isinstance(other, list):
x, y, z = other
self.x += other.x
self.y += other.y
self.z += other.z
def __mul__(self, n):
self.x *= n
self.y *= n
self.z *= n
V = Vertex
class Polygon(object):
def __init__(self, *args):
if not args:
self.verts = []
else:
self.verts = args
def add_vertex(self, v):
self.verts.append(v)
def __getitem__(self, n):
return self.verts[n]
def __len__(self):
return len(self.verts)
def surface_normal(self):
v0, v1, v2 = self.verts[0:3]
return v1.x * (v2.y - v0.y) + v0.x * (v1.y - v2.y) + v2.x * (v0.y - v1.y)
R = Polygon
"""
main
"""
from math import sin, cos, pi
rad = pi / 180.0
L = 80
cube = [
R(V(0, L, 0), V(L, L, 0), V(L, 0, 0), V(0, 0, 0)),
R(V(L, L, 0), V(L, L, L), V(L, 0, L), V(L, 0, 0)),
R(V(0, L, L), V(L, L, L), V(L, L, 0), V(0, L, 0)),
R(V(0, L, L), V(0, L, 0), V(0, 0, 0), V(0, 0, L)),
R(V(L, 0, L), V(0, 0, L), V(0, 0, 0), V(L, 0, 0)),
R(V(L, L, L), V(0, L, L), V(0, 0, L), V(L, 0, L)),
]
size = (360, 360)
speed(60)
def setup():
global a, b
a, b = 0, rad * 0.3
def draw():
global a, b
a = (a + 0.02) % (2 * pi)
b = (b + 0.01) % (2 * pi)
translate(180, 180)
fill(0.7, 0.7, 1)
stroke(0, 0, 0)
for r in cube:
draw_rect(r, a, b)
def draw_rect(r, a, b):
moved_rect = Polygon()
for v in r:
x = v.x * cos(b) + v.z * sin(b)
z = -v.x * sin(b) + v.z * cos(b)
y = v.y * cos(a) - z * sin(a)
moved_rect.add_vertex(V(x, y, z))
if moved_rect.surface_normal() < 0:
return
for i, v in enumerate(moved_rect):
if i == 0:
beginpath(v.x, v.y)
lineto(v.x, v.y)
if i == (len(r) - 1):
endpath()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment