Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_Torus_Knot_3_in_7.py
- import tkinter as tk
- import math
- import random
- import array
- import struct
- WIDTH, HEIGHT = 600, 600
- P, Q = 3, 7
- STEPS = 600
- N = STEPS + 1
- LINEWIDTH = 7
- ANGLE_STEPS = 1440
- _step = 2 * math.pi / ANGLE_STEPS
- x_cache = [(math.cos(i * _step), math.sin(i * _step)) for i in range(ANGLE_STEPS)]
- y_cache = x_cache
- z_cache = x_cache
- color_cache = [
- f'#{int(128 * (0.15 + 0.85 * (i / 255))):02x}00{int(200 * (0.15 + 0.85 * (i / 255))):02x}'
- for i in range(256)
- ]
- root = tk.Tk()
- root.title("Torus Knot")
- root.geometry("+-5+0")
- root.resizable(False, False)
- canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="black", highlightthickness=0)
- canvas.pack()
- _raw = array.array('d')
- for i in range(N):
- t = 2 * math.pi * i / STEPS
- r = math.cos(Q * t) + 2
- _raw.extend((r * math.cos(P * t), r * math.sin(P * t), -math.sin(Q * t)))
- RAW_FMT = f'{N * 3}d'
- _px = array.array('d', bytes(N * 8))
- _py = array.array('d', bytes(N * 8))
- _dep = array.array('B', bytes(N))
- lines = [
- canvas.create_line(0, 0, 1, 1, fill=color_cache[128], width=LINEWIDTH, capstyle=tk.ROUND)
- for _ in range(STEPS)
- ]
- ix = random.randrange(ANGLE_STEPS)
- iy = random.randrange(ANGLE_STEPS)
- iz = random.randrange(ANGLE_STEPS)
- _coords = canvas.coords
- _config = canvas.itemconfig
- _after = root.after
- _unpack = struct.unpack
- _randint = random.randint
- W2 = WIDTH * 0.5
- H2 = HEIGHT * 0.5
- FOV = 600.0
- SCALE = 110.0
- MASK = ANGLE_STEPS - 1
- def rotate():
- return _randint(18, 32)
- def draw_frame():
- global ix, iy, iz
- ix = (ix + rotate()) % ANGLE_STEPS
- iy = (iy + rotate()) % ANGLE_STEPS
- iz = (iz + rotate()) % ANGLE_STEPS
- cx, sx = x_cache[ix]
- cy, sy = y_cache[iy]
- cz, sz = z_cache[iz]
- m00 = cy*cz; m01 = cz*sx*sy - cx*sz; m02 = cx*cz*sy + sx*sz
- m10 = cy*sz; m11 = cx*cz + sx*sy*sz; m12 = cx*sy*sz - cz*sx
- m20 = -sy; m21 = cy*sx; m22 = cx*cy
- pts = _unpack(RAW_FMT, _raw)
- px_arr = _px
- py_arr = _py
- dep_arr = _dep
- j = 0
- for i in range(N):
- x = pts[j]; y = pts[j + 1]; z = pts[j + 2]; j += 3
- rx = m00*x + m01*y + m02*z
- ry = m10*x + m11*y + m12*z
- rz = m20*x + m21*y + m22*z
- f = FOV / (rz + FOV) * SCALE
- px_arr[i] = rx * f + W2
- py_arr[i] = -ry * f + H2
- d = int((rz + 4.0) * 31.875)
- dep_arr[i] = 255 if d > 255 else (0 if d < 0 else d)
- ccache = color_cache
- lns = lines
- for i in range(STEPS):
- i1 = i + 1
- _coords(lns[i], px_arr[i], py_arr[i], px_arr[i1], py_arr[i1])
- _config(lns[i], fill=ccache[(dep_arr[i] + dep_arr[i1]) >> 1])
- _after(1, draw_frame)
- draw_frame()
- root.mainloop()
Advertisement