Skip to content

Draw through a rendering API, and add PNG and PDF backends - #5

Merged
certik merged 6 commits into
mainfrom
backend1
Aug 15, 2026
Merged

certik merged 6 commits into
mainfrom
backend1

Conversation

@certik

@certik certik commented Aug 15, 2026

Copy link
Copy Markdown
Member

fplot could only produce SVG, and the code that produced it was the same code
that decided what a plot looks like: the layout logic wrote XML tags directly.
Adding a second output format meant either copying that logic or threading
format checks through it. This introduces a rendering API and puts three
backends behind it.

The API

src/fplot_render.f90 defines an abstract renderer_t. Everything above it
works in device coordinates and talks in primitives — paths, rectangles,
circles, markers, text, images — and nothing above it knows what a file
format is.

Two decisions are worth stating. The API is stateless: every call carries its
own paint and transform, so there is no save/restore stack to keep in sync
and no way for one drawing call to leak into the next. And it is purely
additive: calls arrive in paint order and a backend may act on each
immediately, which is what a rasterizer wants, while a vector backend is free
to buffer.

The primitive set is deliberately small but not minimal. A rectangle is
expressible as a path, but SVG wants to emit <rect> and PNG wants a
different code path for a circle than for a flattened polygon, so anything a
backend would special-case anyway is a primitive rather than a courtesy
wrapper over draw_path.

The backends

SVG reproduces the previous output. This was checked, not assumed: the
refactor was verified to emit the same drawing as before it.

PDF writes PDF 1.4 with base-14 Helvetica, so nothing is embedded and the
files stay small. Verified by rendering every test figure through poppler.

PNG has no external dependencies, which means everything underneath it is
here too: a deflate compressor and PNG container (fplot_png.f90), an
antialiased rasterizer (fplot_raster.f90), and DejaVu Sans outlines
extracted into Fortran data (fplot_glyphs.f90, generated by
tools/gen_glyphs.py).

The rasterizer uses signed-area accumulation rather than supersampling. Each
edge deposits the exact area it cuts from each pixel and a running sum along
the row gives coverage, so antialiasing is analytic rather than sampled, and
the running sum is the winding number — nonzero fill falls out of the
algorithm rather than being implemented on top of it. This is the same family
of algorithm matplotlib's Agg uses, which is the point: the goal was to
converge on matplotlib's output, and the surest way is to compute it the same
way.

Matching matplotlib also required its path snapping — axis-aligned paths get
rounded onto the pixel grid, offset by half a pixel for odd linewidths, so
gridlines land in one column instead of straddling two. That single change
halved the difference against matplotlib.

Results

Every test figure is compared against matplotlib's own output, pixel by
pixel: PNG 43/43 at mean 1.9/255, PDF 43/43 at mean 2.1/255. For
calibration, rendering fplot's own SVG through cairosvg differs from
matplotlib by 2.7 — the new rasterizer agrees with matplotlib more closely
than an established SVG renderer does. What remains is sub-pixel layout drift
and glyph hinting, since matplotlib hints through FreeType and fplot fills
outlines unhinted.

All 129 outputs are byte-identical between flang and LFortran.

Also fixed

The raster backend exposed two bugs that SVG had been silently absorbing:
transparent=.true. produced an opaque image, and savefig(dpi=) leaked into
subsequent calls. SVG ignores dpi and expresses transparency by drawing
nothing, so neither was visible before.

certik added 6 commits August 15, 2026 11:40
fplot built its SVG inline: two hundred odd calls appended angle brackets
and attributes from the middle of the drawing code, so the output format
was not a thing the library had, it was a thing the library was. Adding
PNG or PDF meant either writing a second copy of every drawing routine or
parsing back the SVG we had just written.

This introduces fplot_render, an abstract renderer_t that names the six
primitives a backend has to decide for itself, and moves the XML into
fplot_backend_svg behind it. A call earns a place in that contract only
when a backend has a real choice to make about it, which is why rectangles,
circles and marker sets are there while lines and polygons are not: no
format draws a polyline better than it draws a path.

Paint travels with each call instead of living in a state machine, so no
drawing operation can disturb another. Clipping rides along inside the
paint; the SVG backend coalesces runs of identical clips into one <g> as an
internal optimization, which is where the old hand-written clip groups went.
The pie wedge is now flattened to cubics here rather than emitted as an SVG
arc, since the arc was the one piece of geometry no other format could take.

Two things follow that are worth having on their own. Each axes is now
wrapped in <g id="axes_N">, matching matplotlib, so a figure opened in
Inkscape or Illustrator can be picked apart by eye; a colorbar counts as an
axes of its own, as it does in matplotlib. And markers are emitted once in
<defs> and instanced with <use>, again as matplotlib does, so a scatter plot
no longer repeats its outline at every point.

The comparison script previously counted fplot's clip paths as a stand-in
for matplotlib's axes groups, and passed the colorbar cases only because
fplot emitted a clip path there that nothing ever referenced. Both sides now
match on <g id="axes_N">, which is a stricter check than the one it replaces.

Verified by rasterizing every test figure before and after with cairosvg:
39 of the 43 are pixel identical, and the remaining four differ by between
two and fifteen pixels of antialiasing where marker circles are now four
cubics and the pie rim is flattened. All 43 structural comparisons against
matplotlib pass, and lfortran and flang produce byte-identical output.
The front end ran every string through xml_escape_to on its way to
draw_text, so what reached the renderer was not the caller's text but one
format's spelling of it. A PDF or PostScript backend would have printed
"A &amp; B" literally, and the API's promise that text stays text was only
true by accident.

The SVG backend now escapes on the way out. Verified that a title of
"A & B < C > D" still arrives as "A &amp; B &lt; C &gt; D"; the test corpus
happens to contain no markup characters at all, which is why this survived
this long.
savefig now picks the backend from the file extension, as matplotlib does,
so the same figure that renders to SVG renders to PDF with no other change.
The refactor onto renderer_t did the real work here; this backend is only
another implementation of that contract.

Text is the one place PDF is not a straight translation of SVG. PDF has no
text-anchor, so centred and right-aligned strings have to be positioned by
measuring them, and that means the backend needs font metrics. It uses the
base-14 Helvetica AFM widths, which keeps the file self-contained and free
of any embedded font. The cost is that fplot lays out to DejaVu metrics, so
a centred label can sit a fraction of a point off true centre. Embedding
DejaVu would fix it and is what matplotlib does; it is worth doing once the
glyph tables exist for the PNG backend, which needs them anyway.

Rasterised against the SVG of the same figure at 100dpi the two agree to a
mean absolute difference of 2/255, with the remaining difference confined
to glyph shapes and antialiasing. Output is byte-identical under flang and
LFortran.
This is the format the backend API was really for. SVG and PDF describe the
drawing and leave the appearance to a viewer; PNG has to decide what colour
every pixel is, and none of that machinery existed. It is three modules, kept
apart because they have nothing to say to each other: fplot_raster turns paths
into coverage, fplot_png turns pixels into a file, and fplot_backend_png is
the thin translation between the rendering API and the other two. No zlib, no
libpng, no font library; a PNG is still a plain Fortran build.

Coverage is computed by signed-area accumulation rather than supersampling.
Every edge deposits the exact area it cuts from each pixel and a running sum
along the row turns those deltas into coverage, which is analytic
antialiasing rather than a fixed number of sample levels, and which makes the
running sum the winding number, so the nonzero fill rule falls out of the
algorithm instead of needing sorted crossing lists. That is the same class of
rasterizer as Agg, which matters because Agg is what we are trying to match.
It gives nonzero only; fplot never asks for even-odd.

Everything else reduces to filling a path. Strokes are converted to outlines
by piling up a quad per segment and a wedge per corner, all wound the same
way so that nonzero unions them, which is far shorter and more robust than
offsetting a polygon. Text is filled with the same code, from DejaVu Sans
outlines compiled in by tools/gen_glyphs.py: DejaVu is matplotlib's own face,
so text lands in the same place rather than merely a similar one.

Two details matter more than they look. Row filtering and a real deflate,
rather than stored blocks, are what keep a figure around 50kB instead of a
megabyte. And paths made only of horizontal and vertical segments are snapped
to the pixel grid exactly as matplotlib snaps them; without that, gridlines
and spines straddle two columns and read as blurred. Snapping alone halved
the difference from matplotlib.

Measured against matplotlib's own PNGs across all 43 test figures, the mean
absolute difference is 1.9/255. For comparison, the same figures rasterized
from fplot's SVG by cairosvg differ by 2.7, so the new rasterizer agrees with
matplotlib more closely than an established SVG renderer does. What is left
is sub-pixel layout differences, which exist in the SVG output too, and glyph
hinting: matplotlib hints through FreeType and this fills outlines unhinted.
Closing that gap is worth doing but is not what makes the format usable.

tests/compare_pngs.py checks the pixels against matplotlib on every case, and
output is byte-identical under flang and LFortran.
Two things the vector backends were able to ignore.

A figure drawn with transparent=True reaches the backend as an open_canvas
with no background colour at all. SVG and PDF express that by drawing no
figure patch, so they needed no special case and the omission was invisible;
a raster has no way to draw nothing, and was filling opaque white instead.
It now reads a missing background as alpha zero, which is the same statement
in the only vocabulary a pixel buffer has.

savefig(dpi=) was also being written into the figure and left there. That was
harmless while every format ignored dpi, but it now decides how many pixels a
PNG gets, so one call asking for 200 quietly rescaled every later save.
Matplotlib treats savefig's dpi as belonging to that call, and so does this
now; figure(dpi=) still sets the figure's own and outlives it.
The test figures were being written as SVG and PNG but not PDF, so the one
backend with no regression coverage was the one whose output nobody had
looked at since it was written. All 43 now save as PDF too.

Comparing them needs a different method again. Bytes are meaningless and
structure nearly so, because two files can describe the same page with
entirely different operators, so both sides are handed to pdftoppm and the
resulting images compared: the only question worth asking is whether the page
looks the same. Rendering both with one rasterizer also means the comparison
cannot be fooled by a viewer's quirks.

That the reference renders at all is itself most of the value here. A PDF
with a miscounted xref offset or a broken object opens as nothing, and no
structural check I could write would be as convincing as poppler agreeing to
read all 43.

The 43 cases come out at a mean absolute difference of 2.1/255. The residual
is text, and it is honest: matplotlib embeds a DejaVu subset while fplot
refers to base-14 Helvetica, so the file needs no embedded font but the
glyphs are a different typeface spaced by different widths. The limit is set
loose enough to allow that and tight enough to catch anything structural.

poppler is now a declared dependency rather than something that happened to
be on my PATH, and CI runs the PNG and PDF comparisons alongside the SVG one.
The three shared a long setup command copied three times; that is now a
depends-on so it is stated once and CI does not build the library three times
to run three checks.
@certik
certik merged commit 408b803 into main Aug 15, 2026
1 check passed
@certik
certik deleted the backend1 branch August 15, 2026 21:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant