-
-
Notifications
You must be signed in to change notification settings - Fork 635
/
path.go
685 lines (605 loc) · 17.8 KB
/
path.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
// Copyright 2019 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package vector provides functions for vector graphics rendering.
//
// This package is under experiments and the API might be changed with breaking backward compatibility.
package vector
import (
"math"
"github.com/hajimehoshi/ebiten/v2"
)
// Direction represents clockwise or counterclockwise.
type Direction int
const (
Clockwise Direction = iota
CounterClockwise
)
func abs(x float32) float32 {
if x < 0 {
return -x
}
return x
}
type point struct {
x float32
y float32
}
type subpath struct {
points []point
closed bool
}
func (s *subpath) currentPosition() (point, bool) {
if len(s.points) == 0 {
return point{}, false
}
if s.closed {
return point{}, false
}
return s.points[len(s.points)-1], true
}
func (s *subpath) pointCount() int {
return len(s.points)
}
func (s *subpath) lastPoint() point {
return s.points[len(s.points)-1]
}
func (s *subpath) appendPoint(pt point) {
if s.closed {
panic("vector: a closed subpathment cannot append a new point")
}
// Do not add a too close point to the last point.
// This can cause unexpected rendering results.
if lp := s.lastPoint(); abs(lp.x-pt.x) < 1e-2 && abs(lp.y-pt.y) < 1e-2 {
return
}
s.points = append(s.points, pt)
}
func (s *subpath) close() {
if s.closed {
return
}
s.appendPoint(s.points[0])
s.closed = true
}
// Path represents a collection of path subpathments.
type Path struct {
subpaths []*subpath
}
// MoveTo starts a new subpath with the given position (x, y) without adding a subpath,
func (p *Path) MoveTo(x, y float32) {
p.subpaths = append(p.subpaths, &subpath{
points: []point{
{x: x, y: y},
},
})
}
// LineTo adds a line segment to the path, which starts from the last position of the current subpath
// and ends to the given position (x, y).
// If p doesn't have any subpaths or the last subpath is closed, LineTo sets (x, y) as the start position of a new subpath.
func (p *Path) LineTo(x, y float32) {
if len(p.subpaths) == 0 || p.subpaths[len(p.subpaths)-1].closed {
p.subpaths = append(p.subpaths, &subpath{
points: []point{
{x: x, y: y},
},
})
return
}
p.subpaths[len(p.subpaths)-1].appendPoint(point{x: x, y: y})
}
// QuadTo adds a quadratic Bézier curve to the path.
// (x1, y1) is the control point, and (x2, y2) is the destination.
func (p *Path) QuadTo(x1, y1, x2, y2 float32) {
p.quadTo(point{x: x1, y: y1}, point{x: x2, y: y2}, 0)
}
// lineForTwoPoints returns parameters for a line passing through p0 and p1.
func lineForTwoPoints(p0, p1 point) (a, b, c float32) {
// Line passing through p0 and p1 in the form of ax + by + c = 0
a = p1.y - p0.y
b = -(p1.x - p0.x)
c = (p1.x-p0.x)*p0.y - (p1.y-p0.y)*p0.x
return
}
// isPointCloseToSegment detects the distance between a segment (x0, y0)-(x1, y1) and a point (x, y) is less than allow.
func isPointCloseToSegment(p, p0, p1 point, allow float32) bool {
a, b, c := lineForTwoPoints(p0, p1)
// The distance between a line ax+by+c=0 and (x0, y0) is
// |ax0 + by0 + c| / √(a² + b²)
return allow*allow*(a*a+b*b) > (a*p.x+b*p.y+c)*(a*p.x+b*p.y+c)
}
// crossingPointForTwoLines returns a crossing point for two lines.
func crossingPointForTwoLines(p00, p01, p10, p11 point) point {
a0, b0, c0 := lineForTwoPoints(p00, p01)
a1, b1, c1 := lineForTwoPoints(p10, p11)
det := a0*b1 - a1*b0
return point{
x: (b0*c1 - b1*c0) / det,
y: (a1*c0 - a0*c1) / det,
}
}
func (p *Path) currentPosition() (point, bool) {
if len(p.subpaths) == 0 {
return point{}, false
}
return p.subpaths[len(p.subpaths)-1].currentPosition()
}
func (p *Path) quadTo(p1, p2 point, level int) {
if level > 10 {
return
}
p0, ok := p.currentPosition()
if !ok {
p0 = p1
}
if isPointCloseToSegment(p1, p0, p2, 0.5) {
p.LineTo(p2.x, p2.y)
return
}
p01 := point{
x: (p0.x + p1.x) / 2,
y: (p0.y + p1.y) / 2,
}
p12 := point{
x: (p1.x + p2.x) / 2,
y: (p1.y + p2.y) / 2,
}
p012 := point{
x: (p01.x + p12.x) / 2,
y: (p01.y + p12.y) / 2,
}
p.quadTo(p01, p012, level+1)
p.quadTo(p12, p2, level+1)
}
// CubicTo adds a cubic Bézier curve to the path.
// (x1, y1) and (x2, y2) are the control points, and (x3, y3) is the destination.
func (p *Path) CubicTo(x1, y1, x2, y2, x3, y3 float32) {
p.cubicTo(point{x: x1, y: y1}, point{x: x2, y: y2}, point{x: x3, y: y3}, 0)
}
func (p *Path) cubicTo(p1, p2, p3 point, level int) {
if level > 10 {
return
}
p0, ok := p.currentPosition()
if !ok {
p0 = p1
}
if isPointCloseToSegment(p1, p0, p3, 0.5) && isPointCloseToSegment(p2, p0, p3, 0.5) {
p.LineTo(p3.x, p3.y)
return
}
p01 := point{
x: (p0.x + p1.x) / 2,
y: (p0.y + p1.y) / 2,
}
p12 := point{
x: (p1.x + p2.x) / 2,
y: (p1.y + p2.y) / 2,
}
p23 := point{
x: (p2.x + p3.x) / 2,
y: (p2.y + p3.y) / 2,
}
p012 := point{
x: (p01.x + p12.x) / 2,
y: (p01.y + p12.y) / 2,
}
p123 := point{
x: (p12.x + p23.x) / 2,
y: (p12.y + p23.y) / 2,
}
p0123 := point{
x: (p012.x + p123.x) / 2,
y: (p012.y + p123.y) / 2,
}
p.cubicTo(p01, p012, p0123, level+1)
p.cubicTo(p123, p23, p3, level+1)
}
func normalize(p point) point {
len := float32(math.Hypot(float64(p.x), float64(p.y)))
return point{x: p.x / len, y: p.y / len}
}
func cross(p0, p1 point) float32 {
return p0.x*p1.y - p1.x*p0.y
}
// ArcTo adds an arc curve to the path.
// (x1, y1) is the first control point, and (x2, y2) is the second control point.
func (p *Path) ArcTo(x1, y1, x2, y2, radius float32) {
p0, ok := p.currentPosition()
if !ok {
p0 = point{x: x1, y: y1}
}
d0 := point{
x: p0.x - x1,
y: p0.y - y1,
}
d1 := point{
x: x2 - x1,
y: y2 - y1,
}
if d0 == (point{}) || d1 == (point{}) {
p.LineTo(x1, y1)
return
}
d0 = normalize(d0)
d1 = normalize(d1)
// theta is the angle between two vectors d0 and d1.
theta := math.Acos(float64(d0.x*d1.x + d0.y*d1.y))
// TODO: When theta is bigger than π/2, the arc should be split into two.
// dist is the distance between the control point and the arc's beginning and ending points.
dist := radius / float32(math.Tan(theta/2))
// TODO: What if dist is too big?
// (ax0, ay0) is the start of the arc.
ax0 := x1 + d0.x*dist
ay0 := y1 + d0.y*dist
var cx, cy, a0, a1 float32
var dir Direction
if cross(d0, d1) >= 0 {
cx = ax0 - d0.y*radius
cy = ay0 + d0.x*radius
a0 = float32(math.Atan2(float64(-d0.x), float64(d0.y)))
a1 = float32(math.Atan2(float64(d1.x), float64(-d1.y)))
dir = CounterClockwise
} else {
cx = ax0 + d0.y*radius
cy = ay0 - d0.x*radius
a0 = float32(math.Atan2(float64(d0.x), float64(-d0.y)))
a1 = float32(math.Atan2(float64(-d1.x), float64(d1.y)))
dir = Clockwise
}
p.Arc(cx, cy, radius, a0, a1, dir)
}
// Arc adds an arc to the path.
// (x, y) is the center of the arc.
func (p *Path) Arc(x, y, radius, startAngle, endAngle float32, dir Direction) {
// Adjust the angles.
var da float64
if dir == Clockwise {
for startAngle > endAngle {
endAngle += 2 * math.Pi
}
da = float64(endAngle - startAngle)
} else {
for startAngle < endAngle {
startAngle += 2 * math.Pi
}
da = float64(startAngle - endAngle)
}
if da >= 2*math.Pi {
da = 2 * math.Pi
if dir == Clockwise {
endAngle = startAngle + 2*math.Pi
} else {
startAngle = endAngle + 2*math.Pi
}
}
// If the angle is big, splict this into multiple Arc calls.
if da > math.Pi/2 {
const delta = math.Pi / 3
a := float64(startAngle)
if dir == Clockwise {
for {
p.Arc(x, y, radius, float32(a), float32(math.Min(a+delta, float64(endAngle))), dir)
if a+delta >= float64(endAngle) {
break
}
a += delta
}
} else {
for {
p.Arc(x, y, radius, float32(a), float32(math.Max(a-delta, float64(endAngle))), dir)
if a-delta <= float64(endAngle) {
break
}
a -= delta
}
}
return
}
sin0, cos0 := math.Sincos(float64(startAngle))
x0 := x + radius*float32(cos0)
y0 := y + radius*float32(sin0)
sin1, cos1 := math.Sincos(float64(endAngle))
x1 := x + radius*float32(cos1)
y1 := y + radius*float32(sin1)
p.LineTo(x0, y0)
// Calculate the control points for an approximated Bézier curve.
// See https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/curves/beziers.
l := radius * float32(math.Tan(da/4)*4/3)
var cx0, cy0, cx1, cy1 float32
if dir == Clockwise {
cx0 = x0 + l*float32(-sin0)
cy0 = y0 + l*float32(cos0)
cx1 = x1 + l*float32(sin1)
cy1 = y1 + l*float32(-cos1)
} else {
cx0 = x0 + l*float32(sin0)
cy0 = y0 + l*float32(-cos0)
cx1 = x1 + l*float32(-sin1)
cy1 = y1 + l*float32(cos1)
}
p.CubicTo(cx0, cy0, cx1, cy1, x1, y1)
}
// Close adds a new line from the last position of the current subpath to the first position of the current subpath,
// and marks the current subpath closed.
// Following operations for this path will start with a new subpath.
func (p *Path) Close() {
if len(p.subpaths) == 0 {
return
}
subpath := p.subpaths[len(p.subpaths)-1]
subpath.close()
}
// AppendVerticesAndIndicesForFilling appends vertices and indices to fill this path and returns them.
// AppendVerticesAndIndicesForFilling works in a similar way to the built-in append function.
// If the arguments are nils, AppendVerticesAndIndicesForFilling returns new slices.
//
// The returned vertice's SrcX and SrcY are 0, and ColorR, ColorG, ColorB, and ColorA are 1.
//
// The returned values are intended to be passed to DrawTriangles or DrawTrianglesShader with the fill rule NonZero or EvenOdd
// in order to render a complex polygon like a concave polygon, a polygon with holes, or a self-intersecting polygon.
//
// The returned vertices and indices should be rendered with a solid (non-transparent) color with the default Blend (source-over).
// Otherwise, there is no guarantee about the rendering result.
func (p *Path) AppendVerticesAndIndicesForFilling(vertices []ebiten.Vertex, indices []uint16) ([]ebiten.Vertex, []uint16) {
// TODO: Add tests.
base := uint16(len(vertices))
for _, subpath := range p.subpaths {
if subpath.pointCount() < 3 {
continue
}
for i, pt := range subpath.points {
vertices = append(vertices, ebiten.Vertex{
DstX: pt.x,
DstY: pt.y,
SrcX: 0,
SrcY: 0,
ColorR: 1,
ColorG: 1,
ColorB: 1,
ColorA: 1,
})
if i < 2 {
continue
}
indices = append(indices, base, base+uint16(i-1), base+uint16(i))
}
base += uint16(subpath.pointCount())
}
return vertices, indices
}
// LineCap represents the way in which how the ends of the stroke are rendered.
type LineCap int
const (
LineCapButt LineCap = iota
LineCapRound
LineCapSquare
)
// LineJoin represents the way in which how two segments are joined.
type LineJoin int
const (
LineJoinMiter LineJoin = iota
LineJoinBevel
LineJoinRound
)
// StrokeOptions is options to render a stroke.
type StrokeOptions struct {
// Width is the stroke width in pixels.
//
// The default (zero) value is 0.
Width float32
// LineCap is the way in which how the ends of the stroke are rendered.
// Line caps are not rendered when the subpath is marked as closed.
//
// The default (zero) value is LineCapButt.
LineCap LineCap
// LineJoin is the way in which how two segments are joined.
//
// The default (zero) value is LineJoiMiter.
LineJoin LineJoin
// MiterLimit is the miter limit for LineJoinMiter.
// For details, see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit.
//
// The default (zero) value is 0.
MiterLimit float32
}
// AppendVerticesAndIndicesForStroke appends vertices and indices to render a stroke of this path and returns them.
// AppendVerticesAndIndicesForStroke works in a similar way to the built-in append function.
// If the arguments are nils, AppendVerticesAndIndicesForStroke returns new slices.
//
// The returned vertice's SrcX and SrcY are 0, and ColorR, ColorG, ColorB, and ColorA are 1.
//
// The returned values are intended to be passed to DrawTriangles or DrawTrianglesShader with a solid (non-transparent) color
// with FillAll or NonZero fill rule, not EvenOdd fill rule.
func (p *Path) AppendVerticesAndIndicesForStroke(vertices []ebiten.Vertex, indices []uint16, op *StrokeOptions) ([]ebiten.Vertex, []uint16) {
if op == nil {
return vertices, indices
}
for _, subpath := range p.subpaths {
if subpath.pointCount() < 2 {
continue
}
var rects [][4]point
for i := 0; i < subpath.pointCount()-1; i++ {
pt := subpath.points[i]
nextPt := subpath.points[i+1]
dx := nextPt.x - pt.x
dy := nextPt.y - pt.y
dist := float32(math.Sqrt(float64(dx*dx + dy*dy)))
extX := (dy) * op.Width / 2 / dist
extY := (-dx) * op.Width / 2 / dist
rects = append(rects, [4]point{
{
x: pt.x + extX,
y: pt.y + extY,
},
{
x: nextPt.x + extX,
y: nextPt.y + extY,
},
{
x: pt.x - extX,
y: pt.y - extY,
},
{
x: nextPt.x - extX,
y: nextPt.y - extY,
},
})
}
for i, rect := range rects {
idx := uint16(len(vertices))
for _, pt := range rect {
vertices = append(vertices, ebiten.Vertex{
DstX: pt.x,
DstY: pt.y,
SrcX: 0,
SrcY: 0,
ColorR: 1,
ColorG: 1,
ColorB: 1,
ColorA: 1,
})
}
// All the triangles are rendered in clockwise order to enable NonZero filling rule (#2833).
indices = append(indices, idx, idx+1, idx+2, idx+1, idx+3, idx+2)
// Add line joints.
var nextRect [4]point
if i < len(rects)-1 {
nextRect = rects[i+1]
} else if subpath.closed {
nextRect = rects[0]
} else {
continue
}
// c is the center of the 'end' edge of the current rect (= the second point of the segment).
c := point{
x: (rect[1].x + rect[3].x) / 2,
y: (rect[1].y + rect[3].y) / 2,
}
// Note that the Y direction and the angle direction are opposite from math's.
a0 := float32(math.Atan2(float64(rect[1].y-c.y), float64(rect[1].x-c.x)))
a1 := float32(math.Atan2(float64(nextRect[0].y-c.y), float64(nextRect[0].x-c.x)))
da := a1 - a0
for da < 0 {
da += 2 * math.Pi
}
if da == 0 {
continue
}
switch op.LineJoin {
case LineJoinMiter:
delta := math.Pi - da
exceed := float32(math.Abs(1/math.Sin(float64(delta/2)))) > op.MiterLimit
var quad Path
quad.MoveTo(c.x, c.y)
if da < math.Pi {
quad.LineTo(rect[1].x, rect[1].y)
if !exceed {
pt := crossingPointForTwoLines(rect[0], rect[1], nextRect[0], nextRect[1])
quad.LineTo(pt.x, pt.y)
}
quad.LineTo(nextRect[0].x, nextRect[0].y)
} else {
quad.LineTo(rect[3].x, rect[3].y)
if !exceed {
pt := crossingPointForTwoLines(rect[2], rect[3], nextRect[2], nextRect[3])
quad.LineTo(pt.x, pt.y)
}
quad.LineTo(nextRect[2].x, nextRect[2].y)
}
vertices, indices = quad.AppendVerticesAndIndicesForFilling(vertices, indices)
case LineJoinBevel:
var tri Path
tri.MoveTo(c.x, c.y)
if da < math.Pi {
tri.LineTo(rect[1].x, rect[1].y)
tri.LineTo(nextRect[0].x, nextRect[0].y)
} else {
tri.LineTo(rect[3].x, rect[3].y)
tri.LineTo(nextRect[2].x, nextRect[2].y)
}
vertices, indices = tri.AppendVerticesAndIndicesForFilling(vertices, indices)
case LineJoinRound:
var arc Path
arc.MoveTo(c.x, c.y)
if da < math.Pi {
arc.Arc(c.x, c.y, op.Width/2, a0, a1, Clockwise)
} else {
arc.Arc(c.x, c.y, op.Width/2, a0+math.Pi, a1+math.Pi, CounterClockwise)
}
vertices, indices = arc.AppendVerticesAndIndicesForFilling(vertices, indices)
}
}
if len(rects) == 0 {
continue
}
// If the subpath is closed, do not render line caps.
if subpath.closed {
continue
}
switch op.LineCap {
case LineCapButt:
// Do nothing.
case LineCapRound:
startR, endR := rects[0], rects[len(rects)-1]
{
c := point{
x: (startR[0].x + startR[2].x) / 2,
y: (startR[0].y + startR[2].y) / 2,
}
a := float32(math.Atan2(float64(startR[0].y-startR[2].y), float64(startR[0].x-startR[2].x)))
var arc Path
arc.MoveTo(startR[0].x, startR[0].y)
arc.Arc(c.x, c.y, op.Width/2, a, a+math.Pi, CounterClockwise)
vertices, indices = arc.AppendVerticesAndIndicesForFilling(vertices, indices)
}
{
c := point{
x: (endR[1].x + endR[3].x) / 2,
y: (endR[1].y + endR[3].y) / 2,
}
a := float32(math.Atan2(float64(endR[1].y-endR[3].y), float64(endR[1].x-endR[3].x)))
var arc Path
arc.MoveTo(endR[1].x, endR[1].y)
arc.Arc(c.x, c.y, op.Width/2, a, a+math.Pi, Clockwise)
vertices, indices = arc.AppendVerticesAndIndicesForFilling(vertices, indices)
}
case LineCapSquare:
startR, endR := rects[0], rects[len(rects)-1]
{
a := math.Atan2(float64(startR[0].y-startR[1].y), float64(startR[0].x-startR[1].x))
s, c := math.Sincos(a)
dx, dy := float32(c)*op.Width/2, float32(s)*op.Width/2
var quad Path
quad.MoveTo(startR[0].x, startR[0].y)
quad.LineTo(startR[0].x+dx, startR[0].y+dy)
quad.LineTo(startR[2].x+dx, startR[2].y+dy)
quad.LineTo(startR[2].x, startR[2].y)
vertices, indices = quad.AppendVerticesAndIndicesForFilling(vertices, indices)
}
{
a := math.Atan2(float64(endR[1].y-endR[0].y), float64(endR[1].x-endR[0].x))
s, c := math.Sincos(a)
dx, dy := float32(c)*op.Width/2, float32(s)*op.Width/2
var quad Path
quad.MoveTo(endR[1].x, endR[1].y)
quad.LineTo(endR[1].x+dx, endR[1].y+dy)
quad.LineTo(endR[3].x+dx, endR[3].y+dy)
quad.LineTo(endR[3].x, endR[3].y)
vertices, indices = quad.AppendVerticesAndIndicesForFilling(vertices, indices)
}
}
}
return vertices, indices
}