Last active
June 6, 2018 15:13
-
-
Save kusma/4695cf1ce27e13ab88c6a2ef8b869c21 to your computer and use it in GitHub Desktop.
A 2D SVG-rendering of the famous glxgears program
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 svgwrite | |
import math | |
def gear_outline(outer_radius, teeth, tooth_depth): | |
r1 = outer_radius - tooth_depth / 2.0 | |
r2 = outer_radius + tooth_depth / 2.0 | |
da = 2.0 * math.pi / teeth / 4.0 | |
polygon = [] | |
for i in range(teeth): | |
angle = i * 2.0 * math.pi / teeth | |
polygon.append((r1 * math.cos(angle + 0 * da), r1 * math.sin(angle + 0 * da))) | |
polygon.append((r2 * math.cos(angle + 1 * da), r2 * math.sin(angle + 1 * da))) | |
polygon.append((r2 * math.cos(angle + 2 * da), r2 * math.sin(angle + 2 * da))) | |
polygon.append((r1 * math.cos(angle + 3 * da), r1 * math.sin(angle + 3 * da))) | |
return polygon | |
def gear_inner(radius, teeth): | |
r0 = radius | |
polygon = [] | |
for i in range(teeth): | |
angle = i * 2.0 * math.pi / teeth | |
polygon.append((r0 * math.cos(angle), r0 * math.sin(angle))) | |
polygon.append((r0 * math.cos(angle), r0 * math.sin(angle))) | |
return polygon | |
dwg = svgwrite.Drawing('test.svg', profile='tiny') | |
dwg.viewbox(-7.35, -6.35, 13, 13) | |
red = dwg.add(dwg.g(id='red', fill='red')) | |
red.add(dwg.polygon(gear_outline(4.0, 20, 0.7))) | |
red.add(dwg.polygon(gear_inner(1.0, 20))) | |
red.translate(-3.0, -2.0) | |
red.rotate(0) | |
green = dwg.add(dwg.g(id='green', fill='green')) | |
green.add(dwg.polygon(gear_outline(2.0, 10, 0.7))) | |
green.add(dwg.polygon(gear_inner(0.5, 10))) | |
green.translate(3.1, -2.0) | |
green.rotate(-9) | |
blue = dwg.add(dwg.g(id='blue', fill='blue')) | |
blue.translate(-3.1, 4.2) | |
blue.add(dwg.polygon(gear_outline(2.0, 10, 0.7))) | |
blue.add(dwg.polygon(gear_inner(1.3, 10))) | |
blue.rotate(-25) | |
dwg.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment