#!/usr/bin/env python
# Experimental python version of Uwe Grimm's mathematica code
# K M Briggs 2006 Mar 20,24
# mcopy -o -v pinwheel.py pinwheel.py.html pinwheel.png pinwheel.pdf a:

from sys   import exit
from math  import sqrt,pi
from cmath import atan

class T: # pinwheel tiling
  sf=1.0/sqrt(5)
  scale=lambda s,x0,x1,x2: (T.sf*x0,T.sf*x1,T.sf*x2)
  def __init__(s,v=(0.0+0.0j,2.0+0.0j,2.0+1.0j),depth=4):
    if depth==0: # don't dissect
      s.t=v
    else: # a tile is a 5-tuple of tiles
      dm1=depth-1
      v3=(v[0]+v[1])/2
      v4=(3*v[0]+2*v[2])/5
      v5=(v[0]+4*v[2])/5
      v6=v[0]/10+v[1]/2+2*v[2]/5
      s.t=(
        T(s.scale(v[0],v4, v3),  dm1),
        T(s.scale(v3,  v6, v[1]),dm1),
        T(s.scale(v3,  v6, v5),  dm1),
        T(s.scale(v5,  v4, v3),  dm1),
        T(s.scale(v[1],v5,v[2]), dm1)
      )
  def orientation(s): # guesswork!
    c=(-2*s.t[0]+s.t[1]+s.t[2])/3.0
    if c.real==0.0: return 0.0
    return int(2*pi+atan(c.imag/c.real).real) 
  def draw_tiles_png(s,draw):
    colors=('#000333','#00ff00','#999933','#ff3333','#660099','#330033','#ff6600','#cc0033','#3377ff')
    scale=14000
    if len(s.t)==3:
      draw.polygon([
        (scale*s.t[0].real,scale*s.t[0].imag),
        (scale*s.t[1].real,scale*s.t[1].imag),
        (scale*s.t[2].real,scale*s.t[2].imag)
      ],outline='#ffffff',fill=colors[s.orientation()])
    else:
      for t in s.t:
        t.draw_tiles_png(draw)
  def draw_tiles_pdf(s,cnvs):
    c=tuple([(i/10.0,i*i/100.0,i*i*i/100.0) for i in range(11)]) # hack
    scale=14000
    if len(s.t)==3:
      c=c[s.orientation()]
      cnvs.setFillColorRGB(c[0],c[1],c[2])
      path=cnvs.beginPath()
      path.moveTo(scale*s.t[0].real,scale*s.t[0].imag)
      path.lineTo(scale*s.t[1].real,scale*s.t[1].imag)
      path.lineTo(scale*s.t[2].real,scale*s.t[2].imag)
      path.lineTo(scale*s.t[0].real,scale*s.t[0].imag)
      path.close()
      cnvs.drawPath(path,stroke=1,fill=1)
    else:
      for t in s.t:
        t.draw_tiles_pdf(cnvs)

t=T() # make the tiling

try: # make png
  import Image,ImageDraw
  img=Image.new(mode='RGB',size=(1000,500))
  draw=ImageDraw.Draw(img)
  t.draw_tiles_png(draw)
  img.save('pinwheel.png')
except:
  print 'png drawing failed - Python Imaging Library (PIL) not installed?'

try: # make pdf
  from reportlab.pdfgen import canvas
  cnvs=canvas.Canvas('pinwheel.pdf',pagesize=(1000,500),bottomup=0)
  cnvs.setAuthor('Keith Briggs')
  cnvs.setTitle('pinwheel tiling')
  t.draw_tiles_pdf(cnvs)
  cnvs.showPage()
  cnvs.save()
except:
  print 'pdf drawing failed - reportlab not installed?'
