Skip to content

Commit 97fae13

Browse files
authored
Merge pull request #6 from certik/backend2
Send an image to the backend as an image
2 parents 408b803 + c5fd1a2 commit 97fae13

8 files changed

Lines changed: 356 additions & 186 deletions

File tree

‎scripts/build_flang.sh‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ $FLANG -c "$ROOT/src/fplot_cmap.f90"
2222
$FLANG -c "$ROOT/src/fplot_ticks.f90"
2323
$FLANG -c "$ROOT/src/fplot_contour.f90"
2424
$FLANG -c "$ROOT/src/fplot_svg.f90"
25+
$FLANG -c "$ROOT/src/fplot_png.f90"
2526
$FLANG -c "$ROOT/src/fplot_backend_svg.f90"
2627
$FLANG -c "$ROOT/src/fplot_glyphs.f90"
27-
$FLANG -c "$ROOT/src/fplot_png.f90"
2828
$FLANG -c "$ROOT/src/fplot_raster.f90"
2929
$FLANG -c "$ROOT/src/fplot_backend_pdf.f90"
3030
$FLANG -c "$ROOT/src/fplot_backend_png.f90"

‎scripts/build_lfortran.sh‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ $LFORTRAN -c "$ROOT/src/fplot_cmap.f90"
1919
$LFORTRAN -c "$ROOT/src/fplot_ticks.f90"
2020
$LFORTRAN -c "$ROOT/src/fplot_contour.f90"
2121
$LFORTRAN -c "$ROOT/src/fplot_svg.f90"
22+
$LFORTRAN -c "$ROOT/src/fplot_png.f90"
2223
$LFORTRAN -c "$ROOT/src/fplot_backend_svg.f90"
2324
$LFORTRAN -c "$ROOT/src/fplot_glyphs.f90"
24-
$LFORTRAN -c "$ROOT/src/fplot_png.f90"
2525
$LFORTRAN -c "$ROOT/src/fplot_raster.f90"
2626
$LFORTRAN -c "$ROOT/src/fplot_backend_pdf.f90"
2727
$LFORTRAN -c "$ROOT/src/fplot_backend_png.f90"

‎src/fplot.f90‎

Lines changed: 84 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2955,10 +2955,89 @@ pure subroutine cell_triangle(z, i, j, gx, gy, tri, tx, ty, tv)
29552955
end if
29562956
end subroutine cell_triangle
29572957

2958-
! One <rect> per sample. SVG has no raster primitive we can reach without
2959-
! embedding an encoded image, and nearest-neighbour cells are what
2960-
! matplotlib's default interpolation looks like at these sizes anyway.
2958+
! An image is one draw_image call. Every format has a way to place a
2959+
! raster, and using it costs one object in the file where a rectangle per
2960+
! sample costs nr*nc: a 200x200 image is 40000 elements the other way.
2961+
!
2962+
! A blit assumes the samples are evenly spaced on the canvas, which is
2963+
! true only while both axes are linear, so a log axis keeps the per-cell
2964+
! path below.
29612965
subroutine append_image(b, a, xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h, xsc, ysc)
2966+
class(renderer_t), intent(inout) :: b
2967+
type(axes_t), intent(in) :: a
2968+
real(dp), intent(in) :: xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h
2969+
type(scale_t), intent(in) :: xsc, ysc
2970+
integer :: nr, nc, i, j, si, sj, fx, fy
2971+
integer, allocatable :: rgba(:, :, :)
2972+
real(dp) :: px0, px1, py0, py1, t
2973+
type(paint_t) :: p
2974+
logical :: flip_x, flip_y
2975+
2976+
if (xsc%kind /= SCALE_LINEAR .or. ysc%kind /= SCALE_LINEAR) then
2977+
call append_image_cells(b, a, xmin, xmax, ymin, ymax, &
2978+
ax_l, ax_w, ax_b, ax_h, xsc, ysc)
2979+
return
2980+
end if
2981+
2982+
nr = size(a%img, 1)
2983+
nc = size(a%img, 2)
2984+
px0 = map_x(a%img_ext(1), xmin, xmax, ax_l, ax_w, xsc)
2985+
px1 = map_x(a%img_ext(2), xmin, xmax, ax_l, ax_w, xsc)
2986+
py0 = map_y(a%img_ext(3), ymin, ymax, ax_b, ax_h, ysc)
2987+
py1 = map_y(a%img_ext(4), ymin, ymax, ax_b, ax_h, ysc)
2988+
2989+
! draw_image wants its rows from the top of the canvas down, and the
2990+
! image's own rows run up the extent, so whichever end of the extent
2991+
! lands at the top decides where row 1 goes. This is how origin=
2992+
! "upper" reaches the file: it descends the y axis, which is what
2993+
! puts the first row at the top.
2994+
flip_x = px1 < px0
2995+
flip_y = py0 > py1
2996+
2997+
! The raster is sent at roughly the size it will be drawn, which is
2998+
! what matplotlib does and for the same reason: a backend or a viewer
2999+
! asked to enlarge a 16x12 image will often interpolate it, and these
3000+
! images are small enough that interpolating turns the data into a
3001+
! blur. Repeating each sample a whole number of times is exactly
3002+
! nearest neighbour, so no value is invented by doing it.
3003+
fx = fill_factor(abs(px1 - px0), nc)
3004+
fy = fill_factor(abs(py1 - py0), nr)
3005+
3006+
allocate (rgba(4, nc*fx, nr*fy))
3007+
do i = 1, nr*fy
3008+
si = (i - 1)/fy + 1
3009+
if (flip_y) si = nr - si + 1
3010+
do j = 1, nc*fx
3011+
sj = (j - 1)/fx + 1
3012+
if (flip_x) sj = nc - sj + 1
3013+
t = (a%img(si, sj) - a%img_vmin) / (a%img_vmax - a%img_vmin)
3014+
rgba(1:3, j, i) = hex_rgb(cmap_color(a%img_cmap, t))
3015+
rgba(4, j, i) = 255
3016+
end do
3017+
end do
3018+
3019+
p%clip = g_clip
3020+
call b%draw_image(min(px0, px1), min(py0, py1), abs(px1 - px0), &
3021+
abs(py1 - py0), rgba, nc*fx, nr*fy, p)
3022+
end subroutine append_image
3023+
3024+
! How many times to repeat each sample so the raster covers the space it
3025+
! is drawn in, bounded so that a large image is left as it is rather than
3026+
! grown into something the file has to carry.
3027+
pure function fill_factor(extent, n) result(f)
3028+
real(dp), intent(in) :: extent
3029+
integer, intent(in) :: n
3030+
integer :: f
3031+
integer, parameter :: MAX_SAMPLES = 2048
3032+
3033+
f = max(1, ceiling(extent/real(max(n, 1), dp)))
3034+
f = min(f, max(1, MAX_SAMPLES/max(n, 1)))
3035+
end function fill_factor
3036+
3037+
! One rectangle per sample. Correct whatever the axes do to the spacing,
3038+
! and so the answer when a scale is not linear and a blit would put the
3039+
! samples in the wrong places.
3040+
subroutine append_image_cells(b, a, xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h, xsc, ysc)
29623041
class(renderer_t), intent(inout) :: b
29633042
type(axes_t), intent(in) :: a
29643043
real(dp), intent(in) :: xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h
@@ -2987,10 +3066,11 @@ subroutine append_image(b, a, xmin, xmax, ymin, ymax, ax_l, ax_w, ax_b, ax_h, xs
29873066
cmap_color(a%img_cmap, t))
29883067
end do
29893068
end do
2990-
end subroutine append_image
3069+
end subroutine append_image_cells
29913070

29923071
! Cells are grown by a hairline so that neighbours overlap; without it the
29933072
! renderer leaves visible seams between abutting rectangles.
3073+
! renderer leaves visible seams between abutting rectangles.
29943074
subroutine append_cell(b, x, y, w, h, color)
29953075
class(renderer_t), intent(inout) :: b
29963076
real(dp), intent(in) :: x, y, w, h

‎src/fplot_backend_pdf.f90‎

Lines changed: 109 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,26 @@ module fplot_backend_pdf
2929
use fplot_render
3030
use fplot_svg, only: svg_builder, builder_init, builder_append, &
3131
builder_get, fmt_num
32+
use fplot_png, only: zlib_compress
3233
implicit none
3334
private
3435

3536
public :: pdf_renderer_t
3637

3738
integer, parameter :: MAX_OBJ = 64
3839
integer, parameter :: MAX_ALPHA = 64
40+
integer, parameter :: MAX_IMG = 16
41+
42+
! An image already compressed and ready to become an XObject. The samples
43+
! are kept as the deflated stream rather than as pixels because that is
44+
! the only form the file wants them in.
45+
type :: pdf_image_t
46+
integer :: w = 0, h = 0
47+
character(len=:), allocatable :: rgb
48+
! Empty unless some sample is transparent, since a fully opaque
49+
! image needs no soft mask.
50+
character(len=:), allocatable :: alpha
51+
end type pdf_image_t
3952

4053
type, extends(renderer_t) :: pdf_renderer_t
4154
! The page content stream. The file itself is assembled in
@@ -50,6 +63,8 @@ module fplot_backend_pdf
5063
real(dp) :: alpha_stroke(MAX_ALPHA) = 1.0_dp
5164
logical :: clip_open = .false.
5265
type(clip_t) :: cur_clip
66+
integer :: n_img = 0
67+
type(pdf_image_t) :: img(MAX_IMG)
5368
contains
5469
procedure :: open_canvas => pdf_open_canvas
5570
procedure :: close_canvas => pdf_close_canvas
@@ -247,6 +262,7 @@ subroutine pdf_open_canvas(self, width, height, bg_rgb, bg_alpha, x0, y0)
247262
if (present(x0)) self%x0 = x0
248263
if (present(y0)) self%y0 = y0
249264
self%n_alpha = 0
265+
self%n_img = 0
250266
call builder_init(self%c)
251267

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

414-
! imshow currently reaches every backend as a grid of rectangles, so no
415-
! figure fplot can draw needs this yet.
430+
! The image itself is registered for later; what goes in the content
431+
! stream is a matrix and one Do. PDF draws an image into the unit square
432+
! with the first row at the top of it, so the matrix that lands it on the
433+
! API's rectangle is a flip: v = 1 is the top edge, and the page is
434+
! already flipped underneath.
416435
subroutine pdf_draw_image(self, x, y, w, h, rgba, nx, ny, paint)
417436
class(pdf_renderer_t), intent(inout) :: self
418437
real(dp), intent(in) :: x, y, w, h
419438
integer, intent(in) :: nx, ny
420439
integer, intent(in) :: rgba(4, nx, ny)
421440
type(paint_t), intent(in) :: paint
441+
integer, allocatable :: rgb(:), a(:)
442+
integer :: i, j, k, id
443+
logical :: opaque
444+
445+
if (nx < 1 .or. ny < 1 .or. self%n_img >= MAX_IMG) return
446+
447+
allocate (rgb(3*nx*ny), a(nx*ny))
448+
k = 0
449+
opaque = .true.
450+
do j = 1, ny
451+
do i = 1, nx
452+
rgb(3*k + 1:3*k + 3) = rgba(1:3, i, j)
453+
a(k + 1) = rgba(4, i, j)
454+
if (rgba(4, i, j) < 255) opaque = .false.
455+
k = k + 1
456+
end do
457+
end do
458+
459+
self%n_img = self%n_img + 1
460+
id = self%n_img
461+
self%img(id)%w = nx
462+
self%img(id)%h = ny
463+
self%img(id)%rgb = zlib_compress(rgb)
464+
if (opaque) then
465+
self%img(id)%alpha = ""
466+
else
467+
self%img(id)%alpha = zlib_compress(a)
468+
end if
469+
470+
call begin_paint(self, paint)
471+
call put_num(self, w)
472+
call put_num(self, 0.0_dp)
473+
call put_num(self, 0.0_dp)
474+
call put_num(self, -h)
475+
call put_num(self, x)
476+
call put_num(self, y + h)
477+
call put(self, "cm"//new_line("a"))
478+
call put(self, "/Im"//int_str(id)//" Do"//new_line("a"))
479+
call put(self, "Q"//new_line("a"))
422480
end subroutine pdf_draw_image
423481

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

433492
eol = new_line("a")
@@ -440,13 +499,29 @@ subroutine pdf_close_canvas(self)
440499
//num_str(self%alpha_fill(i))//" /CA " &
441500
//num_str(self%alpha_stroke(i))//" >> "
442501
end do
502+
503+
! Images follow the five fixed objects, one object each and a second
504+
! for a soft mask where one is needed.
505+
nobj = 5
506+
xo = ""
507+
do i = 1, self%n_img
508+
nobj = nobj + 1
509+
img_obj(i) = nobj
510+
mask_obj(i) = 0
511+
if (len(self%img(i)%alpha) > 0) then
512+
nobj = nobj + 1
513+
mask_obj(i) = nobj
514+
end if
515+
xo = xo//"/Im"//int_str(i)//" "//int_str(img_obj(i))//" 0 R "
516+
end do
517+
443518
res = "<< /Font << /F1 5 0 R >>"
444519
if (len(gs) > 0) res = res//" /ExtGState << "//gs//">>"
520+
if (len(xo) > 0) res = res//" /XObject << "//xo//">>"
445521
res = res//" >>"
446522

447523
call builder_init(f)
448524
pos = 0
449-
nobj = 5
450525

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

555+
do i = 1, self%n_img
556+
off(img_obj(i)) = pos
557+
call emit(f, pos, int_str(img_obj(i))//" 0 obj"//eol &
558+
//"<< /Type /XObject /Subtype /Image /Width " &
559+
//int_str(self%img(i)%w)//" /Height "//int_str(self%img(i)%h) &
560+
//" /ColorSpace /DeviceRGB /BitsPerComponent 8" &
561+
//" /Filter /FlateDecode")
562+
if (mask_obj(i) > 0) then
563+
call emit(f, pos, " /SMask "//int_str(mask_obj(i))//" 0 R")
564+
end if
565+
call emit(f, pos, " /Length "//int_str(len(self%img(i)%rgb))//" >>" &
566+
//eol//"stream"//eol)
567+
call emit(f, pos, self%img(i)%rgb)
568+
call emit(f, pos, eol//"endstream"//eol//"endobj"//eol)
569+
570+
! The mask is the alpha channel as a greyscale image of the same
571+
! size, which is how PDF spells per-sample transparency.
572+
if (mask_obj(i) > 0) then
573+
off(mask_obj(i)) = pos
574+
call emit(f, pos, int_str(mask_obj(i))//" 0 obj"//eol &
575+
//"<< /Type /XObject /Subtype /Image /Width " &
576+
//int_str(self%img(i)%w)//" /Height "//int_str(self%img(i)%h) &
577+
//" /ColorSpace /DeviceGray /BitsPerComponent 8" &
578+
//" /Filter /FlateDecode /Length " &
579+
//int_str(len(self%img(i)%alpha))//" >>"//eol//"stream"//eol)
580+
call emit(f, pos, self%img(i)%alpha)
581+
call emit(f, pos, eol//"endstream"//eol//"endobj"//eol)
582+
end if
583+
end do
584+
480585
xref_pos = pos
481586
call emit(f, pos, "xref"//eol//"0 "//int_str(nobj + 1)//eol)
482587
call emit(f, pos, "0000000000 65535 f "//eol)

‎src/fplot_backend_svg.f90‎

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ module fplot_backend_svg
1616
use fplot_render
1717
use fplot_svg, only: svg_builder, builder_init, builder_append, &
1818
builder_get, fmt_num, xml_escape_to
19+
use fplot_png, only: png_encode
1920
implicit none
2021
private
2122

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

488-
! A raster block becomes a base64 data URI holding a PNG. Left until the
489-
! PNG backend exists, since that is where the encoder will live; fplot
490-
! currently draws imshow as a grid of rectangles instead.
489+
! A raster becomes a PNG in a base64 data URI, which is what matplotlib
490+
! emits and what lets the whole image be one element. Smoothing is turned
491+
! off: the samples are the data, and interpolating them would show the
492+
! reader values that were never measured.
491493
subroutine svg_draw_image(self, x, y, w, h, rgba, nx, ny, paint)
492494
class(svg_renderer_t), intent(inout) :: self
493495
real(dp), intent(in) :: x, y, w, h
494496
integer, intent(in) :: nx, ny
495497
integer, intent(in) :: rgba(4, nx, ny)
496498
type(paint_t), intent(in) :: paint
499+
500+
if (nx < 1 .or. ny < 1) return
501+
call sync_clip(self, paint%clip)
502+
call put(self, '<image x="')
503+
call put_num(self, x)
504+
call put(self, '" y="')
505+
call put_num(self, y)
506+
call put(self, '" width="')
507+
call put_num(self, w)
508+
call put(self, '" height="')
509+
call put_num(self, h)
510+
call put(self, '" preserveAspectRatio="none" image-rendering="pixelated"')
511+
if (paint%fill_alpha < 1.0_dp) then
512+
call put(self, ' opacity="')
513+
call put_num(self, paint%fill_alpha)
514+
call put(self, '"')
515+
end if
516+
call put(self, ' xlink:href="data:image/png;base64,')
517+
call put_base64(self, png_encode(nx, ny, rgba))
518+
call put(self, '"/>')
519+
call put_eol(self)
497520
end subroutine svg_draw_image
498521

522+
! Three bytes become four characters; a short final group is padded with
523+
! "=" so the length still divides by four.
524+
subroutine put_base64(self, s)
525+
class(svg_renderer_t), intent(inout) :: self
526+
character(len=*), intent(in) :: s
527+
character(len=64), parameter :: TBL = &
528+
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
529+
character(len=:), allocatable :: out
530+
integer :: i, n, k, v, b(3), have
531+
532+
n = len(s)
533+
allocate (character(len=4*((n + 2)/3)) :: out)
534+
k = 0
535+
do i = 1, n, 3
536+
have = min(3, n - i + 1)
537+
b = 0
538+
b(1:have) = [(iachar(s(i + v - 1:i + v - 1)), v=1, have)]
539+
v = ishft(b(1), 16) + ishft(b(2), 8) + b(3)
540+
out(k + 1:k + 1) = TBL(iand(ishft(v, -18), 63) + 1:iand(ishft(v, -18), 63) + 1)
541+
out(k + 2:k + 2) = TBL(iand(ishft(v, -12), 63) + 1:iand(ishft(v, -12), 63) + 1)
542+
if (have > 1) then
543+
out(k + 3:k + 3) = TBL(iand(ishft(v, -6), 63) + 1:iand(ishft(v, -6), 63) + 1)
544+
else
545+
out(k + 3:k + 3) = "="
546+
end if
547+
if (have > 2) then
548+
out(k + 4:k + 4) = TBL(iand(v, 63) + 1:iand(v, 63) + 1)
549+
else
550+
out(k + 4:k + 4) = "="
551+
end if
552+
k = k + 4
553+
end do
554+
call put(self, out)
555+
end subroutine put_base64
556+
499557
subroutine svg_begin_group(self, name)
500558
class(svg_renderer_t), intent(inout) :: self
501559
character(len=*), intent(in) :: name

0 commit comments

Comments
 (0)