diff --git a/README.md b/README.md index 8cabc7d..04b8661 100644 --- a/README.md +++ b/README.md @@ -298,7 +298,9 @@ PNGs, measured vs headless Chrome) is in [`FIDELITY.md`](FIDELITY.md) and install typefaces of its own with **`Engine.FontFaces`** (built with `ParseFontFace`), as a browser's system fonts; parsed fonts are shared across renders, so a page set in the same faces as the last one does not - parse them again. The raster painter draws text at the exact size with a + parse them again, and so are the static instances a vector export builds + of a variable font (one per family and weight, a bounded process-wide + cache), so a 100-page export builds each once, not once per page. The raster painter draws text at the exact size with a fractional pen and quarter-pixel glyph origins, so word positions and widths agree with Chrome to within half a pixel (v0.45.12). A **variable font** (an `fvar` `wght` axis) is drawn at each `font-weight` the page asks for, in raster and PDF alike, and so are the diff --git a/paint/fonts.go b/paint/fonts.go index fad1fad..e4e892b 100644 --- a/paint/fonts.go +++ b/paint/fonts.go @@ -80,7 +80,8 @@ type Fonts struct { // styleAxes caches, per style, the weight axis of the font font() answers // with ({min, max, 1} when it has one); register clears it. styleAxes map[styleKey]weightAxis - // instances caches the static instances glyphFont builds. + // instances is this render's lock-free view of the process-wide + // sharedInstances cache glyphFont draws from. instances map[instanceKey]*opentype.Font } @@ -404,7 +405,7 @@ func (f *Fonts) glyphFont(style styleKey, weight int) *opentype.Font { if inst, hit := f.instances[key]; hit { return inst } - inst, err := instantiate(ft, map[string]float64{"wght": float64(w)}) + inst, err := sharedInstance(ft, w) if err != nil { inst = ft // an instance that cannot be built draws as the default master } @@ -419,11 +420,6 @@ func (f *Fonts) glyphFont(style styleKey, weight int) *opentype.Font { // can make it fail. var instantiate = (*opentype.Font).Instance -type instanceKey struct { - font *opentype.Font - wght int -} - // styleFace maps a CSS weight/italic to the concrete face. func (f *Fonts) styleFace(fam css.FontFamily, sizePx float64, weight int, italic bool) *opentype.Face { return f.face(fam, sizePx, weight, italic) diff --git a/paint/sharedinstances.go b/paint/sharedinstances.go new file mode 100644 index 0000000..40fca41 --- /dev/null +++ b/paint/sharedinstances.go @@ -0,0 +1,87 @@ +// Copyright (c) the go-webengine/engine authors. +// SPDX-License-Identifier: BSD-3-Clause + +package paint + +import ( + "sync" + + "github.com/go-opentype/opentype" +) + +// maxSharedInstances bounds the process-wide instance cache. An instance is a +// whole re-serialised font, so the bound is small; a deck draws a handful of +// (family, weight) pairs, and the entries beyond it are the oldest ones. +const maxSharedInstances = 64 + +// instanceKey names a static instance of a variable font: the parsed font +// (identity: the bundled fonts, and a font registered once, are shared across +// every Fonts) and the weight, already clamped to the font's own axis. +type instanceKey struct { + font *opentype.Font + wght int +} + +// instanceEntry is one cached build; once makes concurrent renders wait for +// a single build instead of each running Instance. +type instanceEntry struct { + once sync.Once + font *opentype.Font + err error +} + +// sharedInstances is the process-wide cache of static instances, shared by +// every Fonts so a vector export (one Fonts per page) builds each instance +// once instead of once per page. A failed build is not kept: the next caller +// retries, as a per-render cache would have. +var sharedInstances = struct { + mu sync.Mutex + m map[instanceKey]*instanceEntry + order []instanceKey // insertion order, oldest first +}{m: map[instanceKey]*instanceEntry{}} + +// sharedInstance returns the static instance of ft at weight w, building it +// on first use. +func sharedInstance(ft *opentype.Font, w int) (*opentype.Font, error) { + key := instanceKey{ft, w} + s := &sharedInstances + s.mu.Lock() + e, ok := s.m[key] + if !ok { + if len(s.order) >= maxSharedInstances { + delete(s.m, s.order[0]) + s.order = s.order[1:] + } + e = &instanceEntry{} + s.m[key] = e + s.order = append(s.order, key) + } + s.mu.Unlock() + + e.once.Do(func() { + e.font, e.err = instantiate(ft, map[string]float64{"wght": float64(w)}) + }) + if e.err != nil { + s.mu.Lock() + if s.m[key] == e { + delete(s.m, key) + for i, k := range s.order { + if k == key { + s.order = append(s.order[:i], s.order[i+1:]...) + break + } + } + } + s.mu.Unlock() + return nil, e.err + } + return e.font, nil +} + +// resetSharedInstances empties the cache (tests). +func resetSharedInstances() { + s := &sharedInstances + s.mu.Lock() + s.m, s.order = map[instanceKey]*instanceEntry{}, nil + s.mu.Unlock() +} diff --git a/paint/sharedinstances_bench_test.go b/paint/sharedinstances_bench_test.go new file mode 100644 index 0000000..2944191 --- /dev/null +++ b/paint/sharedinstances_bench_test.go @@ -0,0 +1,40 @@ +// Copyright (c) the go-webengine/engine authors. +// SPDX-License-Identifier: BSD-3-Clause + +package paint + +import ( + "os" + "testing" + + "github.com/go-opentype/opentype" + "github.com/go-webengine/engine/css" +) + +// BenchmarkGlyphFontPages is a vector export: one NewFonts per page, each +// asking for the instances of a variable font at a few weights +// (go-webengine/engine#443). One op is a cold 20-page export. +func BenchmarkGlyphFontPages(b *testing.B) { + raw, err := os.ReadFile("../testdata/fonts/Outfit-wght.ttf") + if err != nil { + b.Fatal(err) + } + ft, err := opentype.Parse(raw) + if err != nil { + b.Fatal(err) + } + style := styleKey{css.FontFamily{Names: "v", Generic: css.GenericSans}, false, false} + b.ReportAllocs() + for b.Loop() { + resetSharedInstances() // a cold cache: one document's export + for range 20 { + f := NewFonts() + if err := f.RegisterFont("v", 100, false, ft); err != nil { + b.Fatal(err) + } + for _, w := range []int{300, 400, 500, 700} { + f.glyphFont(style, w) + } + } + } +} diff --git a/paint/sharedinstances_test.go b/paint/sharedinstances_test.go new file mode 100644 index 0000000..1eab587 --- /dev/null +++ b/paint/sharedinstances_test.go @@ -0,0 +1,122 @@ +// Copyright (c) the go-webengine/engine authors. +// SPDX-License-Identifier: BSD-3-Clause + +package paint + +import ( + "os" + "sync" + "sync/atomic" + "testing" + + "github.com/go-opentype/opentype" + "github.com/go-webengine/engine/css" +) + +// countBuilds swaps the instantiate seam for a counting wrapper. +func countBuilds(t *testing.T) *atomic.Int64 { + t.Helper() + var n atomic.Int64 + old := instantiate + instantiate = func(f *opentype.Font, c map[string]float64) (*opentype.Font, error) { + n.Add(1) + return old(f, c) + } + t.Cleanup(func() { instantiate = old }) + return &n +} + +func sharedVariableFont(t *testing.T) *opentype.Font { + t.Helper() + b, err := os.ReadFile("../testdata/fonts/Outfit-wght.ttf") + if err != nil { + t.Fatal(err) + } + ft, err := opentype.Parse(b) + if err != nil { + t.Fatal(err) + } + return ft +} + +// Two Fonts (one per vector page) drawing the same family at the same weight +// build the static instance once (go-webengine/engine#443). +func TestNewFontsShareInstances(t *testing.T) { + ft := sharedVariableFont(t) + n := countBuilds(t) + a, b := NewFonts(), NewFonts() + for _, f := range []*Fonts{a, b} { + if err := f.RegisterFont("v", 100, false, ft); err != nil { + t.Fatal(err) + } + } + style := styleKey{css.FontFamily{Names: "v", Generic: css.GenericSans}, false, false} + ia, ib := a.glyphFont(style, 700), b.glyphFont(style, 700) + if ia != ib || ia == ft { + t.Error("two Fonts did not share one instance") + } + if got := n.Load(); got != 1 { + t.Errorf("instance built %d times, want 1", got) + } + // Another weight is another instance; a weight past the axis end shares + // the clamped one. + if b.glyphFont(style, 300) == ia { + t.Error("two weights share one instance") + } + if b.glyphFont(style, 1000) != a.glyphFont(style, 900) || n.Load() != 3 { + t.Errorf("clamped weight not shared (builds %d, want 3)", n.Load()) + } +} + +// Concurrent pages wait for one build. +func TestSharedInstancesConcurrent(t *testing.T) { + ft := sharedVariableFont(t) + n := countBuilds(t) + const pages = 16 + got := make([]*opentype.Font, pages) + var wg sync.WaitGroup + for i := range pages { + wg.Add(1) + go func() { + defer wg.Done() + f := NewFonts() + if err := f.RegisterFont("v", 100, false, ft); err != nil { + t.Error(err) + return + } + got[i] = f.glyphFont(styleKey{css.FontFamily{Names: "v", Generic: css.GenericSans}, false, false}, 800) + }() + } + wg.Wait() + for _, g := range got { + if g != got[0] { + t.Fatal("concurrent pages got different instances") + } + } + if c := n.Load(); c != 1 { + t.Errorf("instance built %d times under concurrency, want 1", c) + } +} + +// The cache is bounded, and a failed build is not kept. +func TestSharedInstancesBounded(t *testing.T) { + ft := sharedVariableFont(t) + resetSharedInstances() + t.Cleanup(resetSharedInstances) + n := countBuilds(t) + for w := 1; w <= maxSharedInstances+10; w++ { + if _, err := sharedInstance(ft, 100+w); err != nil { + t.Fatal(err) + } + } + sharedInstances.mu.Lock() + size, order := len(sharedInstances.m), len(sharedInstances.order) + sharedInstances.mu.Unlock() + if size != maxSharedInstances || order != maxSharedInstances { + t.Errorf("cache holds %d/%d entries, want %d", size, order, maxSharedInstances) + } + before := n.Load() + if _, err := sharedInstance(ft, 100+1); err != nil || n.Load() != before+1 { + t.Error("an evicted instance was not rebuilt") + } +}