chalk-diagrams / chalk

A declarative drawing API in Python
MIT License
282 stars 13 forks source link

Trails replace paths #102

Closed srush closed 2 years ago

srush commented 2 years ago

This PR replaces the functionality of Paths with a better Trail object. The idea of the trail is that it holds Translation Invariant segments. This is implemented for now by wrapping the segments we have in 0 centered versions. (although we probably can get rid of the Located* versions, these aren't used). All the path drawing is now moved to trails, which compose a bit nicer since they have a well defined monoid.

Changes:

image

image

(This is probably my last big core PR, semester starting up again :( I'll try to fix my bugs though. )

danoneata commented 2 years ago

This is awesome! Great job!

I've played a bit with the code and it was a reasonably smooth experience :+1: I've tried to recreate the Haskell example that allows for multiple interpretations using various monoid instances:

ts = mconcat . iterateN 3 (rotateBy (1/9)) $ triangle 1
example = (ts ||| strokeP ts ||| strokeLine ts ||| fromVertices ts) # fc red

As expected it is more verbose and explicit in our case, but I think it does the job:

from colour import Color
from chalk import *
from toolz import iterate, take

def centroid(t):
    points = t.points()[1:]
    return sum(points, P2(0, 0)) / len(points)

red = Color("red")

t = Trail.regular_polygon(3, 1)
t_loc = t.at(-centroid(t))

dia1 = concat(take(3, iterate(lambda d: d.rotate_by(1 / 9), t_loc.stroke()))).fill_color(red)
dia2 = Path.concat(take(3, iterate(lambda d: d.rotate_by(1 / 9), t_loc.to_path()))).stroke().fill_color(red)
dia3 = Trail.concat(take(3, iterate(lambda d: d.rotate_by(1 / 9), t))).stroke().center_xy()

dia_all = hcat([dia1, dia2, dia3], sep=0.2)
dia_all

o

I'm going to leave some initial comments and see if I find anything else in the next couple of days.

Edit: I've just noticed that you have already defined a centered method, which can replace the t.at(-centroid(t)) part.

danoneata commented 2 years ago

I think these are all the comments from my side. I'm very happy with the PR, so feel free to merge it on the main branch!