Debian Codegraph @

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

raw
1 //go:build !tinygo
2 // +build !tinygo
3
4 package gfx
5
6 import (
7 "image/color"
8 "math"
9 )
10
11 // IMDraw is an immediate-mode-like shape drawer and BasicTarget. IMDraw supports TrianglesPosition,
12 // TrianglesColor, TrianglesPicture and PictureColor.
13 //
14 // IMDraw, other than a regular BasicTarget, is used to draw shapes. To draw shapes, you first need
15 // to Push some points to IMDraw:
16 //
17 // imd := gfx.NewIMDraw(pic) // use nil pic if you only want to draw primitive shapes
18 // imd.Push(gfx.V(100, 100))
19 // imd.Push(gfx.V(500, 100))
20 //
21 // Once you have Pushed some points, you can use them to draw a shape, such as a line:
22 //
23 // imd.Line(20) // draws a 20 units thick line
24 //
25 // Set exported fields to change properties of Pushed points:
26 //
27 // imd.Color = gfx.RGB(1, 0, 0)
28 // imd.Push(gfx.V(200, 200))
29 // imd.Circle(400, 0)
30 //
31 // Here is the list of all available point properties (need to be set before Pushing a point):
32 // - Color - applies to all
33 // - Picture - coordinates, only applies to filled polygons
34 // - Intensity - picture intensity, only applies to filled polygons
35 // - Precision - curve drawing precision, only applies to circles and ellipses
36 // - EndShape - shape of the end of a line, only applies to lines and outlines
37 //
38 // And here's the list of all shapes that can be drawn (all, except for line, can be filled or
39 // outlined):
40 // - Line
41 // - Polygon
42 // - Circle
43 // - Circle arc
44 // - Ellipse
45 // - Ellipse arc
46 type IMDraw struct {
47 Color color.Color
48 Picture Vec
49 Intensity float64
50 Precision int
51 EndShape EndShape
52
53 points []point
54 pool [][]point
55 matrix Matrix
56
57 tri *TrianglesData
58 batch *Batch
59 }
60
61 var _ BasicTarget = (*IMDraw)(nil)
62
63 type point struct {
64 pos Vec
65 col color.NRGBA
66 pic Vec
67 in float64
68 precision int
69 endshape EndShape
70 }
71
72 // EndShape specifies the shape of an end of a line or a curve.
73 type EndShape int
74
75 const (
76 // NoEndShape leaves a line point with no special end shape.
77 NoEndShape EndShape = iota
78
79 // SharpEndShape is a sharp triangular end shape.
80 SharpEndShape
81
82 // RoundEndShape is a circular end shape.
83 RoundEndShape
84 )
85
86 // NewIMDraw creates a new empty IMDraw. An optional Picture can be used to draw with a Picture.
87 //
88 // If you just want to draw primitive shapes, pass nil as the Picture.
89 func NewIMDraw(pic Picture) *IMDraw {
90 tri := &TrianglesData{}
91 im := &IMDraw{
92 tri: tri,
93 batch: NewBatch(tri, pic),
94 }
95 im.SetMatrix(IM)
96 im.Reset()
97 return im
98 }
99
100 // Clear removes all drawn shapes from the IM. This does not remove Pushed points.
101 func (imd *IMDraw) Clear() {
102 imd.tri.SetLen(0)
103 imd.batch.Dirty()
104 }
105
106 // Reset restores all point properties to defaults and removes all Pushed points.
107 //
108 // This does not affect matrix set by SetMatrix.
109 func (imd *IMDraw) Reset() {
110 imd.points = imd.points[:0]
111 imd.Color = ColorOpaque
112 imd.Picture = ZV
113 imd.Intensity = 0
114 imd.Precision = 64
115 imd.EndShape = NoEndShape
116 }
117
118 // Draw draws all currently drawn shapes inside the IM onto another Target.
119 //
120 // Note, that IMDraw's matrix have no effect here.
121 func (imd *IMDraw) Draw(t Target) {
122 imd.batch.Draw(t)
123 }
124
125 // Push adds some points to the IM queue. All Pushed points will have the same properties except for
126 // the position.
127 func (imd *IMDraw) Push(pts ...Vec) {
128 opts := point{
129 col: imd.Color.(color.NRGBA),
130 pic: imd.Picture,
131 in: imd.Intensity,
132 precision: imd.Precision,
133 endshape: imd.EndShape,
134 }
135 for _, pt := range pts {
136 imd.pushPt(pt, opts)
137 }
138 }
139
140 func (imd *IMDraw) pushPt(pos Vec, pt point) {
141 pt.pos = pos
142 imd.points = append(imd.points, pt)
143 }
144
145 // SetMatrix sets a Matrix that all further points will be transformed by.
146 func (imd *IMDraw) SetMatrix(m Matrix) {
147 imd.matrix = m
148 imd.batch.SetMatrix(imd.matrix)
149 }
150
151 // MakeTriangles returns a specialized copy of the provided Triangles that draws onto this IMDraw.
152 func (imd *IMDraw) MakeTriangles(t Triangles) TargetTriangles {
153 return imd.batch.MakeTriangles(t)
154 }
155
156 // MakePicture returns a specialized copy of the provided Picture that draws onto this IMDraw.
157 func (imd *IMDraw) MakePicture(p Picture) TargetPicture {
158 return imd.batch.MakePicture(p)
159 }
160
161 // Line draws a polyline of the specified thickness between the Pushed points.
162 func (imd *IMDraw) Line(thickness float64) {
163 imd.polyline(thickness, false)
164 }
165
166 // Rectangle draws a rectangle between each two subsequent Pushed points. Drawing a rectangle
167 // between two points means drawing a rectangle with sides parallel to the axes of the coordinate
168 // system, where the two points specify it's two opposite corners.
169 //
170 // If the thickness is 0, rectangles will be filled, otherwise will be outlined with the given
171 // thickness.
172 func (imd *IMDraw) Rectangle(thickness float64) {
173 if thickness == 0 {
174 imd.fillRectangle()
175 } else {
176 imd.outlineRectangle(thickness)
177 }
178 }
179
180 // Polygon draws a polygon from the Pushed points. If the thickness is 0, the convex polygon will be
181 // filled. Otherwise, an outline of the specified thickness will be drawn. The outline does not have
182 // to be convex.
183 //
184 // Note, that the filled polygon does not have to be strictly convex. The way it's drawn is that a
185 // triangle is drawn between each two adjacent points and the first Pushed point. You can use this
186 // property to draw certain kinds of concave polygons.
187 func (imd *IMDraw) Polygon(thickness float64) {
188 if thickness == 0 {
189 imd.fillPolygon()
190 } else {
191 imd.polyline(thickness, true)
192 }
193 }
194
195 // Circle draws a circle of the specified radius around each Pushed point. If the thickness is 0,
196 // the circle will be filled, otherwise a circle outline of the specified thickness will be drawn.
197 func (imd *IMDraw) Circle(radius, thickness float64) {
198 if thickness == 0 {
199 imd.fillEllipseArc(V(radius, radius), 0, 2*math.Pi)
200 } else {
201 imd.outlineEllipseArc(V(radius, radius), 0, 2*math.Pi, thickness, false)
202 }
203 }
204
205 // CircleArc draws a circle arc of the specified radius around each Pushed point. If the thickness
206 // is 0, the arc will be filled, otherwise will be outlined. The arc starts at the low angle and
207 // continues to the high angle. If low<high, the arc will be drawn counterclockwise. Otherwise it
208 // will be clockwise. The angles are not normalized by any means.
209 //
210 // imd.CircleArc(40, 0, 8*math.Pi, 0)
211 //
212 // This line will fill the whole circle 4 times.
213 func (imd *IMDraw) CircleArc(radius, low, high, thickness float64) {
214 if thickness == 0 {
215 imd.fillEllipseArc(V(radius, radius), low, high)
216 } else {
217 imd.outlineEllipseArc(V(radius, radius), low, high, thickness, true)
218 }
219 }
220
221 // Ellipse draws an ellipse of the specified radius in each axis around each Pushed points. If the
222 // thickness is 0, the ellipse will be filled, otherwise an ellipse outline of the specified
223 // thickness will be drawn.
224 func (imd *IMDraw) Ellipse(radius Vec, thickness float64) {
225 if thickness == 0 {
226 imd.fillEllipseArc(radius, 0, 2*math.Pi)
227 } else {
228 imd.outlineEllipseArc(radius, 0, 2*math.Pi, thickness, false)
229 }
230 }
231
232 // EllipseArc draws an ellipse arc of the specified radius in each axis around each Pushed point. If
233 // the thickness is 0, the arc will be filled, otherwise will be outlined. The arc starts at the low
234 // angle and continues to the high angle. If low<high, the arc will be drawn counterclockwise.
235 // Otherwise it will be clockwise. The angles are not normalized by any means.
236 //
237 // imd.EllipseArc(gfx.V(100, 50), 0, 8*math.Pi, 0)
238 //
239 // This line will fill the whole ellipse 4 times.
240 func (imd *IMDraw) EllipseArc(radius Vec, low, high, thickness float64) {
241 if thickness == 0 {
242 imd.fillEllipseArc(radius, low, high)
243 } else {
244 imd.outlineEllipseArc(radius, low, high, thickness, true)
245 }
246 }
247
248 func (imd *IMDraw) getAndClearPoints() []point {
249 points := imd.points
250 // use one of the existing pools so we don't reallocate as often
251 if len(imd.pool) > 0 {
252 pos := len(imd.pool) - 1
253 imd.points = imd.pool[pos][:0]
254 imd.pool = imd.pool[:pos]
255 } else {
256 imd.points = nil
257 }
258 return points
259 }
260
261 func (imd *IMDraw) restorePoints(points []point) {
262 imd.pool = append(imd.pool, imd.points)
263 imd.points = points[:0]
264 }
265
266 func (imd *IMDraw) applyMatrix(off int) {
267 for i := range (*imd.tri)[off:] {
268 (*imd.tri)[off+i].Position = imd.matrix.Project((*imd.tri)[off+i].Position)
269 }
270 }
271
272 func (imd *IMDraw) fillRectangle() {
273 points := imd.getAndClearPoints()
274
275 if len(points) < 2 {
276 imd.restorePoints(points)
277 return
278 }
279
280 off := imd.tri.Len()
281 imd.tri.SetLen(imd.tri.Len() + 6*(len(points)-1))
282
283 for i, j := 0, off; i+1 < len(points); i, j = i+1, j+6 {
284 a, b := points[i], points[i+1]
285 c := point{
286 pos: V(a.pos.X, b.pos.Y),
287 //col: a.col.Add(b.col).Mul(Alpha(0.5)),
288 pic: V(a.pic.X, b.pic.Y),
289 in: (a.in + b.in) / 2,
290 }
291 d := point{
292 pos: V(b.pos.X, a.pos.Y),
293 //col: a.col.Add(b.col).Mul(Alpha(0.5)),
294 pic: V(b.pic.X, a.pic.Y),
295 in: (a.in + b.in) / 2,
296 }
297
298 for k, p := range [...]point{a, b, c, a, b, d} {
299 (*imd.tri)[j+k].Position = p.pos
300 (*imd.tri)[j+k].Color = p.col
301 (*imd.tri)[j+k].Picture = p.pic
302 (*imd.tri)[j+k].Intensity = p.in
303 }
304 }
305
306 imd.applyMatrix(off)
307 imd.batch.Dirty()
308
309 imd.restorePoints(points)
310 }
311
312 func (imd *IMDraw) outlineRectangle(thickness float64) {
313 points := imd.getAndClearPoints()
314
315 if len(points) < 2 {
316 imd.restorePoints(points)
317 return
318 }
319
320 for i := 0; i+1 < len(points); i++ {
321 a, b := points[i], points[i+1]
322 mid := a
323 mid.col = mixNRGBA(a.col, b.col)
324 mid.in = (a.in + b.in) / 2
325
326 imd.pushPt(a.pos, a)
327 imd.pushPt(V(a.pos.X, b.pos.Y), mid)
328 imd.pushPt(b.pos, b)
329 imd.pushPt(V(b.pos.X, a.pos.Y), mid)
330 imd.polyline(thickness, true)
331 }
332
333 imd.restorePoints(points)
334 }
335
336 func (imd *IMDraw) fillPolygon() {
337 points := imd.getAndClearPoints()
338
339 if len(points) < 3 {
340 imd.restorePoints(points)
341 return
342 }
343
344 off := imd.tri.Len()
345 imd.tri.SetLen(imd.tri.Len() + 3*(len(points)-2))
346
347 for i, j := 1, off; i+1 < len(points); i, j = i+1, j+3 {
348 for k, p := range [...]int{0, i, i + 1} {
349 tri := &(*imd.tri)[j+k]
350 tri.Position = points[p].pos
351 tri.Color = points[p].col
352 tri.Picture = points[p].pic
353 tri.Intensity = points[p].in
354 }
355 }
356
357 imd.applyMatrix(off)
358 imd.batch.Dirty()
359
360 imd.restorePoints(points)
361 }
362
363 func (imd *IMDraw) fillEllipseArc(radius Vec, low, high float64) {
364 points := imd.getAndClearPoints()
365
366 for _, pt := range points {
367 num := math.Ceil(math.Abs(high-low) / (2 * math.Pi) * float64(pt.precision))
368 delta := (high - low) / num
369
370 off := imd.tri.Len()
371 imd.tri.SetLen(imd.tri.Len() + 3*int(num))
372
373 for i := range (*imd.tri)[off:] {
374 (*imd.tri)[off+i].Color = pt.col
375 (*imd.tri)[off+i].Picture = ZV
376 (*imd.tri)[off+i].Intensity = 0
377 }
378
379 for i, j := 0.0, off; i < num; i, j = i+1, j+3 {
380 angle := low + i*delta
381 sin, cos := math.Sincos(angle)
382 a := pt.pos.Add(V(
383 radius.X*cos,
384 radius.Y*sin,
385 ))
386
387 angle = low + (i+1)*delta
388 sin, cos = math.Sincos(angle)
389 b := pt.pos.Add(V(
390 radius.X*cos,
391 radius.Y*sin,
392 ))
393
394 (*imd.tri)[j+0].Position = pt.pos
395 (*imd.tri)[j+1].Position = a
396 (*imd.tri)[j+2].Position = b
397 }
398
399 imd.applyMatrix(off)
400 imd.batch.Dirty()
401 }
402
403 imd.restorePoints(points)
404 }
405
406 func (imd *IMDraw) outlineEllipseArc(radius Vec, low, high, thickness float64, doEndShape bool) {
407 points := imd.getAndClearPoints()
408
409 for _, pt := range points {
410 num := math.Ceil(math.Abs(high-low) / (2 * math.Pi) * float64(pt.precision))
411 delta := (high - low) / num
412
413 off := imd.tri.Len()
414 imd.tri.SetLen(imd.tri.Len() + 6*int(num))
415
416 for i := range (*imd.tri)[off:] {
417 (*imd.tri)[off+i].Color = pt.col
418 (*imd.tri)[off+i].Picture = ZV
419 (*imd.tri)[off+i].Intensity = 0
420 }
421
422 for i, j := 0.0, off; i < num; i, j = i+1, j+6 {
423 angle := low + i*delta
424 sin, cos := math.Sincos(angle)
425 normalSin, normalCos := V(sin, cos).ScaledXY(radius).Unit().XY()
426 a := pt.pos.Add(V(
427 radius.X*cos-thickness/2*normalCos,
428 radius.Y*sin-thickness/2*normalSin,
429 ))
430 b := pt.pos.Add(V(
431 radius.X*cos+thickness/2*normalCos,
432 radius.Y*sin+thickness/2*normalSin,
433 ))
434
435 angle = low + (i+1)*delta
436 sin, cos = math.Sincos(angle)
437 normalSin, normalCos = V(sin, cos).ScaledXY(radius).Unit().XY()
438 c := pt.pos.Add(V(
439 radius.X*cos-thickness/2*normalCos,
440 radius.Y*sin-thickness/2*normalSin,
441 ))
442 d := pt.pos.Add(V(
443 radius.X*cos+thickness/2*normalCos,
444 radius.Y*sin+thickness/2*normalSin,
445 ))
446
447 (*imd.tri)[j+0].Position = a
448 (*imd.tri)[j+1].Position = b
449 (*imd.tri)[j+2].Position = c
450 (*imd.tri)[j+3].Position = c
451 (*imd.tri)[j+4].Position = b
452 (*imd.tri)[j+5].Position = d
453 }
454
455 imd.applyMatrix(off)
456 imd.batch.Dirty()
457
458 if doEndShape {
459 lowSin, lowCos := math.Sincos(low)
460 lowCenter := pt.pos.Add(V(
461 radius.X*lowCos,
462 radius.Y*lowSin,
463 ))
464 normalLowSin, normalLowCos := V(lowSin, lowCos).ScaledXY(radius).Unit().XY()
465 normalLow := V(normalLowCos, normalLowSin).Angle()
466
467 highSin, highCos := math.Sincos(high)
468 highCenter := pt.pos.Add(V(
469 radius.X*highCos,
470 radius.Y*highSin,
471 ))
472 normalHighSin, normalHighCos := V(highSin, highCos).ScaledXY(radius).Unit().XY()
473 normalHigh := V(normalHighCos, normalHighSin).Angle()
474
475 orientation := 1.0
476 if low > high {
477 orientation = -1.0
478 }
479
480 switch pt.endshape {
481 case NoEndShape:
482 // nothing
483 case SharpEndShape:
484 thick := V(thickness/2, 0).Rotated(normalLow)
485 imd.pushPt(lowCenter.Add(thick), pt)
486 imd.pushPt(lowCenter.Sub(thick), pt)
487 imd.pushPt(lowCenter.Sub(thick.Normal().Scaled(orientation)), pt)
488 imd.fillPolygon()
489 thick = V(thickness/2, 0).Rotated(normalHigh)
490 imd.pushPt(highCenter.Add(thick), pt)
491 imd.pushPt(highCenter.Sub(thick), pt)
492 imd.pushPt(highCenter.Add(thick.Normal().Scaled(orientation)), pt)
493 imd.fillPolygon()
494 case RoundEndShape:
495 imd.pushPt(lowCenter, pt)
496 imd.fillEllipseArc(V(thickness/2, thickness/2), normalLow, normalLow-math.Pi*orientation)
497 imd.pushPt(highCenter, pt)
498 imd.fillEllipseArc(V(thickness/2, thickness/2), normalHigh, normalHigh+math.Pi*orientation)
499 }
500 }
501 }
502
503 imd.restorePoints(points)
504 }
505
506 func (imd *IMDraw) polyline(thickness float64, closed bool) {
507 points := imd.getAndClearPoints()
508
509 if len(points) == 0 {
510 imd.restorePoints(points)
511 return
512 }
513 if len(points) == 1 {
514 // one point special case
515 points = append(points, points[0])
516 }
517
518 // first point
519 j := 0
520
521 ijNormal := points[0].pos.To(points[1].pos).Normal().Unit().Scaled(thickness / 2)
522
523 if !closed {
524 switch points[j].endshape {
525 case NoEndShape:
526 // nothing
527 case SharpEndShape:
528 imd.pushPt(points[j].pos.Add(ijNormal), points[j])
529 imd.pushPt(points[j].pos.Sub(ijNormal), points[j])
530 imd.pushPt(points[j].pos.Add(ijNormal.Normal()), points[j])
531 imd.fillPolygon()
532 case RoundEndShape:
533 imd.pushPt(points[j].pos, points[j])
534 imd.fillEllipseArc(V(thickness/2, thickness/2), ijNormal.Angle(), ijNormal.Angle()+math.Pi)
535 }
536 }
537
538 imd.pushPt(points[j].pos.Add(ijNormal), points[j])
539 imd.pushPt(points[j].pos.Sub(ijNormal), points[j])
540
541 // middle points
542 for i := 0; i < len(points); i++ {
543 j, k := i+1, i+2
544
545 closing := false
546 if j >= len(points) {
547 j %= len(points)
548 closing = true
549 }
550 if k >= len(points) {
551 if !closed {
552 break
553 }
554 k %= len(points)
555 }
556
557 jkNormal := points[j].pos.To(points[k].pos).Normal().Unit().Scaled(thickness / 2)
558
559 orientation := 1.0
560 if ijNormal.Cross(jkNormal) > 0 {
561 orientation = -1.0
562 }
563
564 imd.pushPt(points[j].pos.Sub(ijNormal), points[j])
565 imd.pushPt(points[j].pos.Add(ijNormal), points[j])
566 imd.fillPolygon()
567
568 switch points[j].endshape {
569 case NoEndShape:
570 // nothing
571 case SharpEndShape:
572 imd.pushPt(points[j].pos, points[j])
573 imd.pushPt(points[j].pos.Add(ijNormal.Scaled(orientation)), points[j])
574 imd.pushPt(points[j].pos.Add(jkNormal.Scaled(orientation)), points[j])
575 imd.fillPolygon()
576 case RoundEndShape:
577 imd.pushPt(points[j].pos, points[j])
578 imd.fillEllipseArc(V(thickness/2, thickness/2), ijNormal.Angle(), ijNormal.Angle()-math.Pi)
579 imd.pushPt(points[j].pos, points[j])
580 imd.fillEllipseArc(V(thickness/2, thickness/2), jkNormal.Angle(), jkNormal.Angle()+math.Pi)
581 }
582
583 if !closing {
584 imd.pushPt(points[j].pos.Add(jkNormal), points[j])
585 imd.pushPt(points[j].pos.Sub(jkNormal), points[j])
586 }
587 // "next" normal becomes previous normal
588 ijNormal = jkNormal
589 }
590
591 // last point
592 i := len(points) - 2
593 j = len(points) - 1
594
595 ijNormal = points[i].pos.To(points[j].pos).Normal().Unit().Scaled(thickness / 2)
596
597 imd.pushPt(points[j].pos.Sub(ijNormal), points[j])
598 imd.pushPt(points[j].pos.Add(ijNormal), points[j])
599 imd.fillPolygon()
600
601 if !closed {
602 switch points[j].endshape {
603 case NoEndShape:
604 // nothing
605 case SharpEndShape:
606 imd.pushPt(points[j].pos.Add(ijNormal), points[j])
607 imd.pushPt(points[j].pos.Sub(ijNormal), points[j])
608 imd.pushPt(points[j].pos.Add(ijNormal.Normal().Scaled(-1)), points[j])
609 imd.fillPolygon()
610 case RoundEndShape:
611 imd.pushPt(points[j].pos, points[j])
612 imd.fillEllipseArc(V(thickness/2, thickness/2), ijNormal.Angle(), ijNormal.Angle()-math.Pi)
613 }
614 }
615
616 imd.restorePoints(points)
617 }
618
619 func mixNRGBA(c1, c2 color.NRGBA) color.NRGBA {
620 return color.NRGBA{
621 c1.R/2 + c2.R/2,
622 c1.G/2 + c2.G/2,
623 c1.B/2 + c2.B/2,
624 c1.A/2 + c2.A/2,
625 }
626 }