Debian Codegraph @

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

raw
1 //go:build !tinygo
2 // +build !tinygo
3
4 package gfx
5
6 // Drawer glues all the fundamental interfaces (Target, Triangles, Picture) into a coherent and the
7 // only intended usage pattern.
8 //
9 // Drawer makes it possible to draw any combination of Triangles and Picture onto any Target
10 // efficiently.
11 //
12 // To create a Drawer, just assign it's Triangles and Picture fields:
13 //
14 // d := gfx.Drawer{Triangles: t, Picture: p}
15 //
16 // If Triangles is nil, nothing will be drawn. If Picture is nil, Triangles will be drawn without a
17 // Picture.
18 //
19 // Whenever you change the Triangles, call Dirty to notify Drawer that Triangles changed. You don't
20 // need to notify Drawer about a change of the Picture.
21 //
22 // Note, that Drawer caches the results of MakePicture from Targets it's drawn to for each Picture
23 // it's set to. What it means is that using a Drawer with an unbounded number of Pictures leads to a
24 // memory leak, since Drawer caches them and never forgets. In such a situation, create a new Drawer
25 // for each Picture.
26 type Drawer struct {
27 Triangles Triangles
28 Picture Picture
29
30 targets map[Target]*drawerTarget
31 inited bool
32 }
33
34 type drawerTarget struct {
35 tris TargetTriangles
36 pics map[Picture]TargetPicture
37 clean bool
38 }
39
40 func (d *Drawer) lazyInit() {
41 if !d.inited {
42 d.targets = make(map[Target]*drawerTarget)
43 d.inited = true
44 }
45 }
46
47 // Dirty marks the Triangles of this Drawer as changed. If not called, changes will not be visible
48 // when drawing.
49 func (d *Drawer) Dirty() {
50 d.lazyInit()
51
52 for _, t := range d.targets {
53 t.clean = false
54 }
55 }
56
57 // Draw efficiently draws Triangles with Picture onto the provided Target.
58 //
59 // If Triangles is nil, nothing will be drawn. If Picture is nil, Triangles will be drawn without a
60 // Picture.
61 func (d *Drawer) Draw(t Target) {
62 d.lazyInit()
63
64 if d.Triangles == nil {
65 return
66 }
67
68 dt := d.targets[t]
69 if dt == nil {
70 dt = &drawerTarget{
71 pics: make(map[Picture]TargetPicture),
72 }
73 d.targets[t] = dt
74 }
75
76 if dt.tris == nil {
77 dt.tris = t.MakeTriangles(d.Triangles)
78 dt.clean = true
79 }
80
81 if !dt.clean {
82 dt.tris.SetLen(d.Triangles.Len())
83 dt.tris.Update(d.Triangles)
84 dt.clean = true
85 }
86
87 if d.Picture == nil {
88 dt.tris.Draw()
89 return
90 }
91
92 pic := dt.pics[d.Picture]
93 if pic == nil {
94 pic = t.MakePicture(d.Picture)
95 dt.pics[d.Picture] = pic
96 }
97
98 pic.Draw(dt.tris)
99 }