Debian Codegraph @

vendor/github.com/xyproto/gfx/turtle.go

raw
1 package gfx
2
3 import (
4 "image"
5 "image/color"
6 "image/draw"
7 )
8
9 // Turtle keeps track of the state of the Turtle.
10 type Turtle struct {
11 Position Vec
12 Direction Vec
13 Width float64
14 Color color.Color
15 ops turtleOperations
16 }
17
18 // NewTurtle creates a new turtle used for drawing.
19 func NewTurtle(p Vec, options ...func(*Turtle)) *Turtle {
20 t := &Turtle{
21 Position: p,
22 Direction: V(0, -1),
23 }
24
25 for _, option := range options {
26 option(t)
27 }
28
29 return t
30 }
31
32 // Bounds return the bounds of the drawing.
33 func (t *Turtle) Bounds() image.Rectangle {
34 if len(t.ops) == 0 {
35 return image.ZR
36 }
37
38 return t.ops.Bounds()
39 }
40
41 // Draw all of the operations to the given image.
42 func (t *Turtle) Draw(m draw.Image) {
43 for _, op := range t.ops {
44 op.Draw(m)
45 }
46 }
47
48 // Resize scaled to the given value.
49 func (t *Turtle) Resize(s float64) {
50 t.Direction = t.Direction.Scaled(s)
51 }
52
53 // Turn the given number of arc degrees
54 func (t *Turtle) Turn(d Degrees) {
55 t.Direction = t.Direction.Rotated(d.Radians())
56 }
57
58 // Move the given number of steps without drawing.
59 func (t *Turtle) Move(steps float64) {
60 t.Position = t.Position.Add(t.Direction.Scaled(steps))
61 }
62
63 // Forward the given number of steps.
64 func (t *Turtle) Forward(steps float64) {
65 from := t.Position
66
67 t.Move(steps)
68
69 to := t.Position
70
71 if t.Width <= 0 {
72 t.Width = 1
73 }
74
75 if t.Color == nil {
76 t.Color = color.Black
77 }
78
79 t.addOp(lineOp{
80 From: from,
81 To: to,
82 Thickness: t.Width * t.Direction.Len(),
83 Color: t.Color,
84 })
85 }
86
87 func (t *Turtle) addOp(top turtleOperation) {
88 t.ops = append(t.ops, top)
89 }
90
91 type turtleOperation interface {
92 turtleDrawer
93 Bounds() image.Rectangle
94 }
95
96 type turtleDrawer interface {
97 Draw(draw.Image)
98 }
99
100 type turtleOperations []turtleOperation
101
102 func (tops turtleOperations) Bounds() image.Rectangle {
103 switch len(tops) {
104 case 0:
105 return image.ZR
106 case 1:
107 return tops[0].Bounds()
108 default:
109 r := tops[0].Bounds()
110
111 for _, top := range tops[1:] {
112 r = r.Union(top.Bounds())
113 }
114
115 return r
116 }
117 }
118
119 type lineOp struct {
120 From Vec
121 To Vec
122 Thickness float64
123 Color color.Color
124 }
125
126 func (lo lineOp) Draw(m draw.Image) {
127 DrawLine(m, lo.From, lo.To, lo.Thickness, lo.Color)
128 }
129
130 func (lo lineOp) Rect() Rect {
131 switch lo.Thickness {
132 case 1:
133 return NewRect(lo.From, lo.To)
134 default:
135 return polylineFromTo(lo.From, lo.To, lo.Thickness).Rect()
136 }
137 }
138
139 func (lo lineOp) Bounds() image.Rectangle {
140 return lo.Rect().Bounds()
141 }