Debian Codegraph @

shiny/iconvg/encode.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package iconvg
6
7 import (
8 "errors"
9 "image/color"
10 "math"
11
12 "golang.org/x/image/math/f32"
13 )
14
15 var (
16 errCSELUsedAsBothGradientAndStop = errors.New("iconvg: CSEL used as both gradient and stop")
17 errDrawingOpsUsedInStylingMode = errors.New("iconvg: drawing ops used in styling mode")
18 errInvalidSelectorAdjustment = errors.New("iconvg: invalid selector adjustment")
19 errInvalidIncrementingAdjustment = errors.New("iconvg: invalid incrementing adjustment")
20 errStylingOpsUsedInDrawingMode = errors.New("iconvg: styling ops used in drawing mode")
21 errTooManyGradientStops = errors.New("iconvg: too many gradient stops")
22 )
23
24 type mode uint8
25
26 const (
27 modeInitial mode = iota
28 modeStyling
29 modeDrawing
30 )
31
32 // Encoder is an IconVG encoder.
33 //
34 // The zero value is usable. Calling Reset, which is optional, sets the
35 // Metadata for the subsequent encoded form. If Reset is not called before
36 // other Encoder methods, the default metadata is implied.
37 //
38 // It aims to emit byte-identical Bytes output for the same input, independent
39 // of the platform (and specifically its floating-point hardware).
40 type Encoder struct {
41 // HighResolutionCoordinates is whether the encoder should encode
42 // coordinate numbers for subsequent paths at the best possible resolution
43 // afforded by the underlying graphic format.
44 //
45 // By default (false), the encoder quantizes coordinates to 1/64th of a
46 // unit if possible (the default graphic size is 64 by 64 units, so
47 // 1/4096th of the default width or height). Each such coordinate can
48 // therefore be encoded in either 1 or 2 bytes. If true, some coordinates
49 // will be encoded in 4 bytes, giving greater accuracy but larger file
50 // sizes. On the Material Design icon set, the 950 or so icons take up
51 // around 40% more bytes (172K vs 123K) at high resolution.
52 //
53 // See the package documentation for more details on the coordinate number
54 // encoding format.
55 HighResolutionCoordinates bool
56
57 // highResolutionCoordinates is a local copy, copied during StartPath, to
58 // avoid having to specify the semantics of modifying the exported field
59 // while drawing.
60 highResolutionCoordinates bool
61
62 buf buffer
63 altBuf buffer
64 metadata Metadata
65 err error
66
67 lod0 float32
68 lod1 float32
69 cSel uint8
70 nSel uint8
71
72 mode mode
73 drawOp byte
74 drawArgs []float32
75
76 scratch [12]byte
77 }
78
79 // Bytes returns the encoded form.
80 func (e *Encoder) Bytes() ([]byte, error) {
81 if e.err != nil {
82 return nil, e.err
83 }
84 if e.mode == modeInitial {
85 e.appendDefaultMetadata()
86 }
87 return []byte(e.buf), nil
88 }
89
90 // Reset resets the Encoder for the given Metadata.
91 //
92 // This includes setting e.HighResolutionCoordinates to false.
93 func (e *Encoder) Reset(m Metadata) {
94 *e = Encoder{
95 buf: append(e.buf[:0], magic...),
96 metadata: m,
97 mode: modeStyling,
98 lod1: positiveInfinity,
99 }
100
101 nMetadataChunks := 0
102 mcViewBox := m.ViewBox != DefaultViewBox
103 if mcViewBox {
104 nMetadataChunks++
105 }
106 mcSuggestedPalette := m.Palette != DefaultPalette
107 if mcSuggestedPalette {
108 nMetadataChunks++
109 }
110 e.buf.encodeNatural(uint32(nMetadataChunks))
111
112 if mcViewBox {
113 e.altBuf = e.altBuf[:0]
114 e.altBuf.encodeNatural(midViewBox)
115 e.altBuf.encodeCoordinate(m.ViewBox.Min[0])
116 e.altBuf.encodeCoordinate(m.ViewBox.Min[1])
117 e.altBuf.encodeCoordinate(m.ViewBox.Max[0])
118 e.altBuf.encodeCoordinate(m.ViewBox.Max[1])
119
120 e.buf.encodeNatural(uint32(len(e.altBuf)))
121 e.buf = append(e.buf, e.altBuf...)
122 }
123
124 if mcSuggestedPalette {
125 n := 63
126 for ; n >= 0 && m.Palette[n] == (color.RGBA{0x00, 0x00, 0x00, 0xff}); n-- {
127 }
128
129 // Find the shortest encoding that can represent all of m.Palette's n+1
130 // explicit colors.
131 enc1, enc2, enc3 := true, true, true
132 for _, c := range m.Palette[:n+1] {
133 if enc1 && (!is1(c.R) || !is1(c.G) || !is1(c.B) || !is1(c.A)) {
134 enc1 = false
135 }
136 if enc2 && (!is2(c.R) || !is2(c.G) || !is2(c.B) || !is2(c.A)) {
137 enc2 = false
138 }
139 if enc3 && (c.A != 0xff) {
140 enc3 = false
141 }
142 }
143
144 e.altBuf = e.altBuf[:0]
145 e.altBuf.encodeNatural(midSuggestedPalette)
146 if enc1 {
147 e.altBuf = append(e.altBuf, byte(n)|0x00)
148 for _, c := range m.Palette[:n+1] {
149 x, _ := encodeColor1(RGBAColor(c))
150 e.altBuf = append(e.altBuf, x)
151 }
152 } else if enc2 {
153 e.altBuf = append(e.altBuf, byte(n)|0x40)
154 for _, c := range m.Palette[:n+1] {
155 x, _ := encodeColor2(RGBAColor(c))
156 e.altBuf = append(e.altBuf, x[0], x[1])
157 }
158 } else if enc3 {
159 e.altBuf = append(e.altBuf, byte(n)|0x80)
160 for _, c := range m.Palette[:n+1] {
161 e.altBuf = append(e.altBuf, c.R, c.G, c.B)
162 }
163 } else {
164 e.altBuf = append(e.altBuf, byte(n)|0xc0)
165 for _, c := range m.Palette[:n+1] {
166 e.altBuf = append(e.altBuf, c.R, c.G, c.B, c.A)
167 }
168 }
169
170 e.buf.encodeNatural(uint32(len(e.altBuf)))
171 e.buf = append(e.buf, e.altBuf...)
172 }
173 }
174
175 func (e *Encoder) appendDefaultMetadata() {
176 e.buf = append(e.buf[:0], magic...)
177 e.buf = append(e.buf, 0x00) // There are zero metadata chunks.
178 e.mode = modeStyling
179 }
180
181 func (e *Encoder) CSel() uint8 {
182 if e.mode == modeInitial {
183 e.appendDefaultMetadata()
184 }
185 return e.cSel
186 }
187
188 func (e *Encoder) NSel() uint8 {
189 if e.mode == modeInitial {
190 e.appendDefaultMetadata()
191 }
192 return e.nSel
193 }
194
195 func (e *Encoder) LOD() (lod0, lod1 float32) {
196 if e.mode == modeInitial {
197 e.appendDefaultMetadata()
198 }
199 return e.lod0, e.lod1
200 }
201
202 func (e *Encoder) checkModeStyling() {
203 if e.mode == modeStyling {
204 return
205 }
206 if e.mode == modeInitial {
207 e.appendDefaultMetadata()
208 return
209 }
210 e.err = errStylingOpsUsedInDrawingMode
211 }
212
213 func (e *Encoder) SetCSel(cSel uint8) {
214 e.checkModeStyling()
215 if e.err != nil {
216 return
217 }
218 e.cSel = cSel & 0x3f
219 e.buf = append(e.buf, e.cSel)
220 }
221
222 func (e *Encoder) SetNSel(nSel uint8) {
223 e.checkModeStyling()
224 if e.err != nil {
225 return
226 }
227 e.nSel = nSel & 0x3f
228 e.buf = append(e.buf, e.nSel|0x40)
229 }
230
231 func (e *Encoder) SetCReg(adj uint8, incr bool, c Color) {
232 e.checkModeStyling()
233 if e.err != nil {
234 return
235 }
236 if adj > 6 {
237 e.err = errInvalidSelectorAdjustment
238 return
239 }
240 if incr {
241 if adj != 0 {
242 e.err = errInvalidIncrementingAdjustment
243 }
244 adj = 7
245 }
246
247 if x, ok := encodeColor1(c); ok {
248 e.buf = append(e.buf, adj|0x80, x)
249 return
250 }
251 if x, ok := encodeColor2(c); ok {
252 e.buf = append(e.buf, adj|0x88, x[0], x[1])
253 return
254 }
255 if x, ok := encodeColor3Direct(c); ok {
256 e.buf = append(e.buf, adj|0x90, x[0], x[1], x[2])
257 return
258 }
259 if x, ok := encodeColor4(c); ok {
260 e.buf = append(e.buf, adj|0x98, x[0], x[1], x[2], x[3])
261 return
262 }
263 if x, ok := encodeColor3Indirect(c); ok {
264 e.buf = append(e.buf, adj|0xa0, x[0], x[1], x[2])
265 return
266 }
267 panic("unreachable")
268 }
269
270 func (e *Encoder) SetNReg(adj uint8, incr bool, f float32) {
271 e.checkModeStyling()
272 if e.err != nil {
273 return
274 }
275 if adj > 6 {
276 e.err = errInvalidSelectorAdjustment
277 return
278 }
279 if incr {
280 if adj != 0 {
281 e.err = errInvalidIncrementingAdjustment
282 }
283 adj = 7
284 }
285
286 // Try three different encodings and pick the shortest.
287 b := buffer(e.scratch[0:0])
288 opcode, iBest, nBest := uint8(0xa8), 0, b.encodeReal(f)
289
290 b = buffer(e.scratch[4:4])
291 if n := b.encodeCoordinate(f); n < nBest {
292 opcode, iBest, nBest = 0xb0, 4, n
293 }
294
295 b = buffer(e.scratch[8:8])
296 if n := b.encodeZeroToOne(f); n < nBest {
297 opcode, iBest, nBest = 0xb8, 8, n
298 }
299
300 e.buf = append(e.buf, adj|opcode)
301 e.buf = append(e.buf, e.scratch[iBest:iBest+nBest]...)
302 }
303
304 func (e *Encoder) SetLOD(lod0, lod1 float32) {
305 e.checkModeStyling()
306 if e.err != nil {
307 return
308 }
309 e.lod0 = lod0
310 e.lod1 = lod1
311 e.buf = append(e.buf, 0xc7)
312 e.buf.encodeReal(lod0)
313 e.buf.encodeReal(lod1)
314 }
315
316 // SetGradient sets CREG[CSEL] to encode the gradient whose colors defined by
317 // spread and stops. Its geometry is either linear or radial, depending on the
318 // radial argument, and the given affine transformation matrix maps from
319 // graphic coordinate space defined by the metadata's viewBox (e.g. from (-32,
320 // -32) to (+32, +32)) to gradient coordinate space. Gradient coordinate space
321 // is where a linear gradient ranges from x=0 to x=1, and a radial gradient has
322 // center (0, 0) and radius 1.
323 //
324 // The colors of the n stops are encoded at CREG[cBase+0], CREG[cBase+1], ...,
325 // CREG[cBase+n-1]. Similarly, the offsets of the n stops are encoded at
326 // NREG[nBase+0], NREG[nBase+1], ..., NREG[nBase+n-1]. Additional parameters
327 // are stored at NREG[nBase-4], NREG[nBase-3], NREG[nBase-2] and NREG[nBase-1].
328 //
329 // The CSEL and NSEL selector registers maintain the same values after the
330 // method returns as they had when the method was called.
331 //
332 // See the package documentation for more details on the gradient encoding
333 // format and the derivation of common transformation matrices.
334 func (e *Encoder) SetGradient(cBase, nBase uint8, radial bool, transform f32.Aff3, spread GradientSpread, stops []GradientStop) {
335 e.checkModeStyling()
336 if e.err != nil {
337 return
338 }
339 if len(stops) > 64-len(transform) {
340 e.err = errTooManyGradientStops
341 return
342 }
343 if x, y := e.cSel, e.cSel+64; (cBase <= x && x < cBase+uint8(len(stops))) ||
344 (cBase <= y && y < cBase+uint8(len(stops))) {
345 e.err = errCSELUsedAsBothGradientAndStop
346 return
347 }
348
349 oldCSel := e.cSel
350 oldNSel := e.nSel
351 cBase &= 0x3f
352 nBase &= 0x3f
353 bFlags := uint8(0x80)
354 if radial {
355 bFlags = 0xc0
356 }
357 e.SetCReg(0, false, RGBAColor(color.RGBA{
358 R: uint8(len(stops)),
359 G: cBase | uint8(spread<<6),
360 B: nBase | bFlags,
361 A: 0x00,
362 }))
363 e.SetCSel(cBase)
364 e.SetNSel(nBase)
365 for i, v := range transform {
366 e.SetNReg(uint8(len(transform)-i), false, v)
367 }
368 for _, s := range stops {
369 r, g, b, a := s.Color.RGBA()
370 e.SetCReg(0, true, RGBAColor(color.RGBA{
371 R: uint8(r >> 8),
372 G: uint8(g >> 8),
373 B: uint8(b >> 8),
374 A: uint8(a >> 8),
375 }))
376 e.SetNReg(0, true, s.Offset)
377 }
378 e.SetCSel(oldCSel)
379 e.SetNSel(oldNSel)
380 }
381
382 // SetLinearGradient is like SetGradient with radial=false except that the
383 // transformation matrix is implicitly defined by two boundary points (x1, y1)
384 // and (x2, y2).
385 func (e *Encoder) SetLinearGradient(cBase, nBase uint8, x1, y1, x2, y2 float32, spread GradientSpread, stops []GradientStop) {
386 // See the package documentation's appendix for a derivation of the
387 // transformation matrix.
388 dx, dy := x2-x1, y2-y1
389 d := dx*dx + dy*dy
390 ma := dx / d
391 mb := dy / d
392 e.SetGradient(cBase, nBase, false, f32.Aff3{
393 ma, mb, -ma*x1 - mb*y1,
394 0, 0, 0,
395 }, spread, stops)
396 }
397
398 // SetCircularGradient is like SetGradient with radial=true except that the
399 // transformation matrix is implicitly defined by a center (cx, cy) and a
400 // radius vector (rx, ry) such that (cx+rx, cy+ry) is on the circle.
401 func (e *Encoder) SetCircularGradient(cBase, nBase uint8, cx, cy, rx, ry float32, spread GradientSpread, stops []GradientStop) {
402 // See the package documentation's appendix for a derivation of the
403 // transformation matrix.
404 invR := float32(1 / math.Sqrt(float64(rx*rx+ry*ry)))
405 e.SetGradient(cBase, nBase, true, f32.Aff3{
406 invR, 0, -cx * invR,
407 0, invR, -cy * invR,
408 }, spread, stops)
409 }
410
411 // SetEllipticalGradient is like SetGradient with radial=true except that the
412 // transformation matrix is implicitly defined by a center (cx, cy) and two
413 // axis vectors (rx, ry) and (sx, sy) such that (cx+rx, cy+ry) and (cx+sx,
414 // cy+sy) are on the ellipse.
415 func (e *Encoder) SetEllipticalGradient(cBase, nBase uint8, cx, cy, rx, ry, sx, sy float32, spread GradientSpread, stops []GradientStop) {
416 // Explicitly disable FMA in the floating-point calculations below
417 // to get consistent results on all platforms, and in turn produce
418 // a byte-identical encoding.
419 // See https://golang.org/ref/spec#Floating_point_operators and issue 43219.
420
421 // See the package documentation's appendix for a derivation of the
422 // transformation matrix.
423 invRSSR := 1 / (float32(rx*sy) - float32(sx*ry))
424
425 ma := +sy * invRSSR
426 mb := -sx * invRSSR
427 mc := -float32(ma*cx) - float32(mb*cy)
428 md := -ry * invRSSR
429 me := +rx * invRSSR
430 mf := -float32(md*cx) - float32(me*cy)
431
432 e.SetGradient(cBase, nBase, true, f32.Aff3{
433 ma, mb, mc,
434 md, me, mf,
435 }, spread, stops)
436 }
437
438 func (e *Encoder) StartPath(adj uint8, x, y float32) {
439 e.checkModeStyling()
440 if e.err != nil {
441 return
442 }
443 if adj > 6 {
444 e.err = errInvalidSelectorAdjustment
445 return
446 }
447 e.highResolutionCoordinates = e.HighResolutionCoordinates
448 e.buf = append(e.buf, uint8(0xc0+adj))
449 e.buf.encodeCoordinate(quantize(x, e.highResolutionCoordinates))
450 e.buf.encodeCoordinate(quantize(y, e.highResolutionCoordinates))
451 e.mode = modeDrawing
452 }
453
454 func (e *Encoder) AbsHLineTo(x float32) { e.draw('H', x, 0, 0, 0, 0, 0) }
455 func (e *Encoder) RelHLineTo(x float32) { e.draw('h', x, 0, 0, 0, 0, 0) }
456 func (e *Encoder) AbsVLineTo(y float32) { e.draw('V', y, 0, 0, 0, 0, 0) }
457 func (e *Encoder) RelVLineTo(y float32) { e.draw('v', y, 0, 0, 0, 0, 0) }
458 func (e *Encoder) AbsLineTo(x, y float32) { e.draw('L', x, y, 0, 0, 0, 0) }
459 func (e *Encoder) RelLineTo(x, y float32) { e.draw('l', x, y, 0, 0, 0, 0) }
460 func (e *Encoder) AbsSmoothQuadTo(x, y float32) { e.draw('T', x, y, 0, 0, 0, 0) }
461 func (e *Encoder) RelSmoothQuadTo(x, y float32) { e.draw('t', x, y, 0, 0, 0, 0) }
462 func (e *Encoder) AbsQuadTo(x1, y1, x, y float32) { e.draw('Q', x1, y1, x, y, 0, 0) }
463 func (e *Encoder) RelQuadTo(x1, y1, x, y float32) { e.draw('q', x1, y1, x, y, 0, 0) }
464 func (e *Encoder) AbsSmoothCubeTo(x2, y2, x, y float32) { e.draw('S', x2, y2, x, y, 0, 0) }
465 func (e *Encoder) RelSmoothCubeTo(x2, y2, x, y float32) { e.draw('s', x2, y2, x, y, 0, 0) }
466 func (e *Encoder) AbsCubeTo(x1, y1, x2, y2, x, y float32) { e.draw('C', x1, y1, x2, y2, x, y) }
467 func (e *Encoder) RelCubeTo(x1, y1, x2, y2, x, y float32) { e.draw('c', x1, y1, x2, y2, x, y) }
468 func (e *Encoder) ClosePathEndPath() { e.draw('Z', 0, 0, 0, 0, 0, 0) }
469 func (e *Encoder) ClosePathAbsMoveTo(x, y float32) { e.draw('Y', x, y, 0, 0, 0, 0) }
470 func (e *Encoder) ClosePathRelMoveTo(x, y float32) { e.draw('y', x, y, 0, 0, 0, 0) }
471
472 func (e *Encoder) AbsArcTo(rx, ry, xAxisRotation float32, largeArc, sweep bool, x, y float32) {
473 e.arcTo('A', rx, ry, xAxisRotation, largeArc, sweep, x, y)
474 }
475
476 func (e *Encoder) RelArcTo(rx, ry, xAxisRotation float32, largeArc, sweep bool, x, y float32) {
477 e.arcTo('a', rx, ry, xAxisRotation, largeArc, sweep, x, y)
478 }
479
480 func (e *Encoder) arcTo(drawOp byte, rx, ry, xAxisRotation float32, largeArc, sweep bool, x, y float32) {
481 flags := uint32(0)
482 if largeArc {
483 flags |= 0x01
484 }
485 if sweep {
486 flags |= 0x02
487 }
488 e.draw(drawOp, rx, ry, xAxisRotation, float32(flags), x, y)
489 }
490
491 func (e *Encoder) draw(drawOp byte, arg0, arg1, arg2, arg3, arg4, arg5 float32) {
492 if e.err != nil {
493 return
494 }
495 if e.mode != modeDrawing {
496 e.err = errDrawingOpsUsedInStylingMode
497 return
498 }
499 if e.drawOp != drawOp {
500 e.flushDrawOps()
501 }
502 e.drawOp = drawOp
503 switch drawOps[drawOp].nArgs {
504 case 0:
505 // No-op.
506 case 1:
507 e.drawArgs = append(e.drawArgs, arg0)
508 case 2:
509 e.drawArgs = append(e.drawArgs, arg0, arg1)
510 case 4:
511 e.drawArgs = append(e.drawArgs, arg0, arg1, arg2, arg3)
512 case 6:
513 e.drawArgs = append(e.drawArgs, arg0, arg1, arg2, arg3, arg4, arg5)
514 default:
515 panic("unreachable")
516 }
517
518 switch drawOp {
519 case 'Z':
520 e.mode = modeStyling
521 fallthrough
522 case 'Y', 'y':
523 e.flushDrawOps()
524 }
525 }
526
527 func (e *Encoder) flushDrawOps() {
528 if e.drawOp == 0x00 {
529 return
530 }
531
532 if op := drawOps[e.drawOp]; op.nArgs == 0 {
533 e.buf = append(e.buf, op.opcodeBase)
534 } else {
535 n := len(e.drawArgs) / int(op.nArgs)
536 for i := 0; n > 0; {
537 m := n
538 if m > int(op.maxRepCount) {
539 m = int(op.maxRepCount)
540 }
541 e.buf = append(e.buf, op.opcodeBase+uint8(m)-1)
542
543 switch e.drawOp {
544 default:
545 for j := m * int(op.nArgs); j > 0; j-- {
546 e.buf.encodeCoordinate(quantize(e.drawArgs[i], e.highResolutionCoordinates))
547 i++
548 }
549 case 'A', 'a':
550 for j := m; j > 0; j-- {
551 e.buf.encodeCoordinate(quantize(e.drawArgs[i+0], e.highResolutionCoordinates))
552 e.buf.encodeCoordinate(quantize(e.drawArgs[i+1], e.highResolutionCoordinates))
553 e.buf.encodeAngle(e.drawArgs[i+2])
554 e.buf.encodeNatural(uint32(e.drawArgs[i+3]))
555 e.buf.encodeCoordinate(quantize(e.drawArgs[i+4], e.highResolutionCoordinates))
556 e.buf.encodeCoordinate(quantize(e.drawArgs[i+5], e.highResolutionCoordinates))
557 i += 6
558 }
559 }
560
561 n -= m
562 }
563 }
564
565 e.drawOp = 0x00
566 e.drawArgs = e.drawArgs[:0]
567 }
568
569 func quantize(coord float32, highResolutionCoordinates bool) float32 {
570 if !highResolutionCoordinates && (-128 <= coord && coord < 128) {
571 x := math.Floor(float64(coord*64 + 0.5))
572 return float32(x) / 64
573 }
574 return coord
575 }
576
577 var drawOps = [256]struct {
578 opcodeBase byte
579 maxRepCount uint8
580 nArgs uint8
581 }{
582 'L': {0x00, 32, 2},
583 'l': {0x20, 32, 2},
584 'T': {0x40, 16, 2},
585 't': {0x50, 16, 2},
586 'Q': {0x60, 16, 4},
587 'q': {0x70, 16, 4},
588 'S': {0x80, 16, 4},
589 's': {0x90, 16, 4},
590 'C': {0xa0, 16, 6},
591 'c': {0xb0, 16, 6},
592 'A': {0xc0, 16, 6},
593 'a': {0xd0, 16, 6},
594
595 // Z means close path and then end path.
596 'Z': {0xe1, 1, 0},
597 // Y/y means close path and then open a new path (with a MoveTo/moveTo).
598 'Y': {0xe2, 1, 2},
599 'y': {0xe3, 1, 2},
600
601 'H': {0xe6, 1, 1},
602 'h': {0xe7, 1, 1},
603 'V': {0xe8, 1, 1},
604 'v': {0xe9, 1, 1},
605 }