Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/build_flang.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ $FLANG -c "$ROOT/src/fplot_cmap.f90"
$FLANG -c "$ROOT/src/fplot_ticks.f90"
$FLANG -c "$ROOT/src/fplot_contour.f90"
$FLANG -c "$ROOT/src/fplot_svg.f90"
$FLANG -c "$ROOT/src/fplot_png.f90"
$FLANG -c "$ROOT/src/fplot_backend_svg.f90"
$FLANG -c "$ROOT/src/fplot_glyphs.f90"
$FLANG -c "$ROOT/src/fplot_png.f90"
$FLANG -c "$ROOT/src/fplot_raster.f90"
$FLANG -c "$ROOT/src/fplot_backend_pdf.f90"
$FLANG -c "$ROOT/src/fplot_backend_png.f90"
Expand Down
2 changes: 1 addition & 1 deletion scripts/build_lfortran.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ $LFORTRAN -c "$ROOT/src/fplot_cmap.f90"
$LFORTRAN -c "$ROOT/src/fplot_ticks.f90"
$LFORTRAN -c "$ROOT/src/fplot_contour.f90"
$LFORTRAN -c "$ROOT/src/fplot_svg.f90"
$LFORTRAN -c "$ROOT/src/fplot_png.f90"
$LFORTRAN -c "$ROOT/src/fplot_backend_svg.f90"
$LFORTRAN -c "$ROOT/src/fplot_glyphs.f90"
$LFORTRAN -c "$ROOT/src/fplot_png.f90"
$LFORTRAN -c "$ROOT/src/fplot_raster.f90"
$LFORTRAN -c "$ROOT/src/fplot_backend_pdf.f90"
$LFORTRAN -c "$ROOT/src/fplot_backend_png.f90"
Expand Down
88 changes: 84 additions & 4 deletions src/fplot.f90
Original file line number Diff line number Diff line change
Expand Up @@ -2955,10 +2955,89 @@ pure subroutine cell_triangle(z, i, j, gx, gy, tri, tx, ty, tv)
end if
end subroutine cell_triangle

! One <rect> per sample. SVG has no raster primitive we can reach without
! embedding an encoded image, and nearest-neighbour cells are what
! matplotlib's default interpolation looks like at these sizes anyway.
! An image is one draw_image call. Every format has a way to place a
! raster, and using it costs one object in the file where a rectangle per
! sample costs nr*nc: a 200x200 image is 40000 elements the other way.
!
! A blit assumes the samples are evenly spaced on the canvas, which is
! true only while both axes are linear, so a log axis keeps the per-cell
! path below.
subroutine append_image(b, a, xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h, xsc, ysc)
class(renderer_t), intent(inout) :: b
type(axes_t), intent(in) :: a
real(dp), intent(in) :: xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h
type(scale_t), intent(in) :: xsc, ysc
integer :: nr, nc, i, j, si, sj, fx, fy
integer, allocatable :: rgba(:, :, :)
real(dp) :: px0, px1, py0, py1, t
type(paint_t) :: p
logical :: flip_x, flip_y

if (xsc%kind /= SCALE_LINEAR .or. ysc%kind /= SCALE_LINEAR) then
call append_image_cells(b, a, xmin, xmax, ymin, ymax, &
ax_l, ax_w, ax_b, ax_h, xsc, ysc)
return
end if

nr = size(a%img, 1)
nc = size(a%img, 2)
px0 = map_x(a%img_ext(1), xmin, xmax, ax_l, ax_w, xsc)
px1 = map_x(a%img_ext(2), xmin, xmax, ax_l, ax_w, xsc)
py0 = map_y(a%img_ext(3), ymin, ymax, ax_b, ax_h, ysc)
py1 = map_y(a%img_ext(4), ymin, ymax, ax_b, ax_h, ysc)

! draw_image wants its rows from the top of the canvas down, and the
! image's own rows run up the extent, so whichever end of the extent
! lands at the top decides where row 1 goes. This is how origin=
! "upper" reaches the file: it descends the y axis, which is what
! puts the first row at the top.
flip_x = px1 < px0
flip_y = py0 > py1

! The raster is sent at roughly the size it will be drawn, which is
! what matplotlib does and for the same reason: a backend or a viewer
! asked to enlarge a 16x12 image will often interpolate it, and these
! images are small enough that interpolating turns the data into a
! blur. Repeating each sample a whole number of times is exactly
! nearest neighbour, so no value is invented by doing it.
fx = fill_factor(abs(px1 - px0), nc)
fy = fill_factor(abs(py1 - py0), nr)

allocate (rgba(4, nc*fx, nr*fy))
do i = 1, nr*fy
si = (i - 1)/fy + 1
if (flip_y) si = nr - si + 1
do j = 1, nc*fx
sj = (j - 1)/fx + 1
if (flip_x) sj = nc - sj + 1
t = (a%img(si, sj) - a%img_vmin) / (a%img_vmax - a%img_vmin)
rgba(1:3, j, i) = hex_rgb(cmap_color(a%img_cmap, t))
rgba(4, j, i) = 255
end do
end do

p%clip = g_clip
call b%draw_image(min(px0, px1), min(py0, py1), abs(px1 - px0), &
abs(py1 - py0), rgba, nc*fx, nr*fy, p)
end subroutine append_image

! How many times to repeat each sample so the raster covers the space it
! is drawn in, bounded so that a large image is left as it is rather than
! grown into something the file has to carry.
pure function fill_factor(extent, n) result(f)
real(dp), intent(in) :: extent
integer, intent(in) :: n
integer :: f
integer, parameter :: MAX_SAMPLES = 2048

f = max(1, ceiling(extent/real(max(n, 1), dp)))
f = min(f, max(1, MAX_SAMPLES/max(n, 1)))
end function fill_factor

! One rectangle per sample. Correct whatever the axes do to the spacing,
! and so the answer when a scale is not linear and a blit would put the
! samples in the wrong places.
subroutine append_image_cells(b, a, xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h, xsc, ysc)
class(renderer_t), intent(inout) :: b
type(axes_t), intent(in) :: a
real(dp), intent(in) :: xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h
Expand Down Expand Up @@ -2987,10 +3066,11 @@ subroutine append_image(b, a, xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h, xs
cmap_color(a%img_cmap, t))
end do
end do
end subroutine append_image
end subroutine append_image_cells

! Cells are grown by a hairline so that neighbours overlap; without it the
! renderer leaves visible seams between abutting rectangles.
! renderer leaves visible seams between abutting rectangles.
subroutine append_cell(b, x, y, w, h, color)
class(renderer_t), intent(inout) :: b
real(dp), intent(in) :: x, y, w, h
Expand Down
113 changes: 109 additions & 4 deletions src/fplot_backend_pdf.f90
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,26 @@ module fplot_backend_pdf
use fplot_render
use fplot_svg, only: svg_builder, builder_init, builder_append, &
builder_get, fmt_num
use fplot_png, only: zlib_compress
implicit none
private

public :: pdf_renderer_t

integer, parameter :: MAX_OBJ = 64
integer, parameter :: MAX_ALPHA = 64
integer, parameter :: MAX_IMG = 16

! An image already compressed and ready to become an XObject. The samples
! are kept as the deflated stream rather than as pixels because that is
! the only form the file wants them in.
type :: pdf_image_t
integer :: w = 0, h = 0
character(len=:), allocatable :: rgb
! Empty unless some sample is transparent, since a fully opaque
! image needs no soft mask.
character(len=:), allocatable :: alpha
end type pdf_image_t

type, extends(renderer_t) :: pdf_renderer_t
! The page content stream. The file itself is assembled in
Expand All @@ -50,6 +63,8 @@ module fplot_backend_pdf
real(dp) :: alpha_stroke(MAX_ALPHA) = 1.0_dp
logical :: clip_open = .false.
type(clip_t) :: cur_clip
integer :: n_img = 0
type(pdf_image_t) :: img(MAX_IMG)
contains
procedure :: open_canvas => pdf_open_canvas
procedure :: close_canvas => pdf_close_canvas
Expand Down Expand Up @@ -247,6 +262,7 @@ subroutine pdf_open_canvas(self, width, height, bg_rgb, bg_alpha, x0, y0)
if (present(x0)) self%x0 = x0
if (present(y0)) self%y0 = y0
self%n_alpha = 0
self%n_img = 0
call builder_init(self%c)

! One matrix for the whole page turns the API's top-left origin with
Expand Down Expand Up @@ -411,23 +427,66 @@ subroutine pdf_draw_text(self, x, y, s, font, paint, anchor, baseline, angle)
call put(self, "Q"//new_line("a"))
end subroutine pdf_draw_text

! imshow currently reaches every backend as a grid of rectangles, so no
! figure fplot can draw needs this yet.
! The image itself is registered for later; what goes in the content
! stream is a matrix and one Do. PDF draws an image into the unit square
! with the first row at the top of it, so the matrix that lands it on the
! API's rectangle is a flip: v = 1 is the top edge, and the page is
! already flipped underneath.
subroutine pdf_draw_image(self, x, y, w, h, rgba, nx, ny, paint)
class(pdf_renderer_t), intent(inout) :: self
real(dp), intent(in) :: x, y, w, h
integer, intent(in) :: nx, ny
integer, intent(in) :: rgba(4, nx, ny)
type(paint_t), intent(in) :: paint
integer, allocatable :: rgb(:), a(:)
integer :: i, j, k, id
logical :: opaque

if (nx < 1 .or. ny < 1 .or. self%n_img >= MAX_IMG) return

allocate (rgb(3*nx*ny), a(nx*ny))
k = 0
opaque = .true.
do j = 1, ny
do i = 1, nx
rgb(3*k + 1:3*k + 3) = rgba(1:3, i, j)
a(k + 1) = rgba(4, i, j)
if (rgba(4, i, j) < 255) opaque = .false.
k = k + 1
end do
end do

self%n_img = self%n_img + 1
id = self%n_img
self%img(id)%w = nx
self%img(id)%h = ny
self%img(id)%rgb = zlib_compress(rgb)
if (opaque) then
self%img(id)%alpha = ""
else
self%img(id)%alpha = zlib_compress(a)
end if

call begin_paint(self, paint)
call put_num(self, w)
call put_num(self, 0.0_dp)
call put_num(self, 0.0_dp)
call put_num(self, -h)
call put_num(self, x)
call put_num(self, y + h)
call put(self, "cm"//new_line("a"))
call put(self, "/Im"//int_str(id)//" Do"//new_line("a"))
call put(self, "Q"//new_line("a"))
end subroutine pdf_draw_image

! Assemble the file. Objects have to be byte-counted as they are written
! because the trailing xref table records where each one starts.
subroutine pdf_close_canvas(self)
class(pdf_renderer_t), intent(inout) :: self
type(svg_builder) :: f
character(len=:), allocatable :: content, res, gs
character(len=:), allocatable :: content, res, gs, xo
integer :: off(MAX_OBJ), nobj, i, pos, xref_pos
integer :: img_obj(MAX_IMG), mask_obj(MAX_IMG)
character(len=1) :: eol

eol = new_line("a")
Expand All @@ -440,13 +499,29 @@ subroutine pdf_close_canvas(self)
//num_str(self%alpha_fill(i))//" /CA " &
//num_str(self%alpha_stroke(i))//" >> "
end do

! Images follow the five fixed objects, one object each and a second
! for a soft mask where one is needed.
nobj = 5
xo = ""
do i = 1, self%n_img
nobj = nobj + 1
img_obj(i) = nobj
mask_obj(i) = 0
if (len(self%img(i)%alpha) > 0) then
nobj = nobj + 1
mask_obj(i) = nobj
end if
xo = xo//"/Im"//int_str(i)//" "//int_str(img_obj(i))//" 0 R "
end do

res = "<< /Font << /F1 5 0 R >>"
if (len(gs) > 0) res = res//" /ExtGState << "//gs//">>"
if (len(xo) > 0) res = res//" /XObject << "//xo//">>"
res = res//" >>"

call builder_init(f)
pos = 0
nobj = 5

call emit(f, pos, "%PDF-1.4"//eol)
! A comment with high bytes marks the file as binary for tools that
Expand Down Expand Up @@ -477,6 +552,36 @@ subroutine pdf_close_canvas(self)
//"/BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"//eol &
//"endobj"//eol)

do i = 1, self%n_img
off(img_obj(i)) = pos
call emit(f, pos, int_str(img_obj(i))//" 0 obj"//eol &
//"<< /Type /XObject /Subtype /Image /Width " &
//int_str(self%img(i)%w)//" /Height "//int_str(self%img(i)%h) &
//" /ColorSpace /DeviceRGB /BitsPerComponent 8" &
//" /Filter /FlateDecode")
if (mask_obj(i) > 0) then
call emit(f, pos, " /SMask "//int_str(mask_obj(i))//" 0 R")
end if
call emit(f, pos, " /Length "//int_str(len(self%img(i)%rgb))//" >>" &
//eol//"stream"//eol)
call emit(f, pos, self%img(i)%rgb)
call emit(f, pos, eol//"endstream"//eol//"endobj"//eol)

! The mask is the alpha channel as a greyscale image of the same
! size, which is how PDF spells per-sample transparency.
if (mask_obj(i) > 0) then
off(mask_obj(i)) = pos
call emit(f, pos, int_str(mask_obj(i))//" 0 obj"//eol &
//"<< /Type /XObject /Subtype /Image /Width " &
//int_str(self%img(i)%w)//" /Height "//int_str(self%img(i)%h) &
//" /ColorSpace /DeviceGray /BitsPerComponent 8" &
//" /Filter /FlateDecode /Length " &
//int_str(len(self%img(i)%alpha))//" >>"//eol//"stream"//eol)
call emit(f, pos, self%img(i)%alpha)
call emit(f, pos, eol//"endstream"//eol//"endobj"//eol)
end if
end do

xref_pos = pos
call emit(f, pos, "xref"//eol//"0 "//int_str(nobj + 1)//eol)
call emit(f, pos, "0000000000 65535 f "//eol)
Expand Down
64 changes: 61 additions & 3 deletions src/fplot_backend_svg.f90
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ module fplot_backend_svg
use fplot_render
use fplot_svg, only: svg_builder, builder_init, builder_append, &
builder_get, fmt_num, xml_escape_to
use fplot_png, only: png_encode
implicit none
private

Expand Down Expand Up @@ -485,17 +486,74 @@ subroutine svg_draw_text(self, x, y, s, font, paint, anchor, baseline, angle)
call put_eol(self)
end subroutine svg_draw_text

! A raster block becomes a base64 data URI holding a PNG. Left until the
! PNG backend exists, since that is where the encoder will live; fplot
! currently draws imshow as a grid of rectangles instead.
! A raster becomes a PNG in a base64 data URI, which is what matplotlib
! emits and what lets the whole image be one element. Smoothing is turned
! off: the samples are the data, and interpolating them would show the
! reader values that were never measured.
subroutine svg_draw_image(self, x, y, w, h, rgba, nx, ny, paint)
class(svg_renderer_t), intent(inout) :: self
real(dp), intent(in) :: x, y, w, h
integer, intent(in) :: nx, ny
integer, intent(in) :: rgba(4, nx, ny)
type(paint_t), intent(in) :: paint

if (nx < 1 .or. ny < 1) return
call sync_clip(self, paint%clip)
call put(self, '<image x="')
call put_num(self, x)
call put(self, '" y="')
call put_num(self, y)
call put(self, '" width="')
call put_num(self, w)
call put(self, '" height="')
call put_num(self, h)
call put(self, '" preserveAspectRatio="none" image-rendering="pixelated"')
if (paint%fill_alpha < 1.0_dp) then
call put(self, ' opacity="')
call put_num(self, paint%fill_alpha)
call put(self, '"')
end if
call put(self, ' xlink:href="data:image/png;base64,')
call put_base64(self, png_encode(nx, ny, rgba))
call put(self, '"/>')
call put_eol(self)
end subroutine svg_draw_image

! Three bytes become four characters; a short final group is padded with
! "=" so the length still divides by four.
subroutine put_base64(self, s)
class(svg_renderer_t), intent(inout) :: self
character(len=*), intent(in) :: s
character(len=64), parameter :: TBL = &
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
character(len=:), allocatable :: out
integer :: i, n, k, v, b(3), have

n = len(s)
allocate (character(len=4*((n + 2)/3)) :: out)
k = 0
do i = 1, n, 3
have = min(3, n - i + 1)
b = 0
b(1:have) = [(iachar(s(i + v - 1:i + v - 1)), v=1, have)]
v = ishft(b(1), 16) + ishft(b(2), 8) + b(3)
out(k + 1:k + 1) = TBL(iand(ishft(v, -18), 63) + 1:iand(ishft(v, -18), 63) + 1)
out(k + 2:k + 2) = TBL(iand(ishft(v, -12), 63) + 1:iand(ishft(v, -12), 63) + 1)
if (have > 1) then
out(k + 3:k + 3) = TBL(iand(ishft(v, -6), 63) + 1:iand(ishft(v, -6), 63) + 1)
else
out(k + 3:k + 3) = "="
end if
if (have > 2) then
out(k + 4:k + 4) = TBL(iand(v, 63) + 1:iand(v, 63) + 1)
else
out(k + 4:k + 4) = "="
end if
k = k + 4
end do
call put(self, out)
end subroutine put_base64

subroutine svg_begin_group(self, name)
class(svg_renderer_t), intent(inout) :: self
character(len=*), intent(in) :: name
Expand Down
Loading
Loading