diff --git a/internal/platform/grid_columns.go b/internal/platform/grid_columns.go index 16a74bb50..efb85bd32 100644 --- a/internal/platform/grid_columns.go +++ b/internal/platform/grid_columns.go @@ -19,6 +19,17 @@ func GridColumns(left, span float64, width int) (from, to int) { return from, max(to, from) } +// ShiftGridSpans moves the columns the runs of a grid line own, planned in the line's +// own device columns, onto a texture width columns wide that starts skip columns into +// the line: a line wider than a texture holds is rasterized from a window of it. A +// run's columns are cut to the texture, and a run outside it owns none. +func ShiftGridSpans(spans []GridSpan, skip, width int) { + for index, span := range spans { + from := min(max(span.From-skip, 0), width) + spans[index] = GridSpan{From: from, To: min(max(span.To-skip, from), width)} + } +} + func roundColumn(edge float64) int { return int(math.Floor(edge + 0.5)) } diff --git a/internal/platform/grid_columns_test.go b/internal/platform/grid_columns_test.go index 9f54be5ba..131319d0e 100644 --- a/internal/platform/grid_columns_test.go +++ b/internal/platform/grid_columns_test.go @@ -45,3 +45,16 @@ func TestGridColumnsOfAnEmptyRunAreEmpty(t *testing.T) { t.Errorf("a run without cells = %d,%d", from, to) } } + +// Columns planned along a whole line land on the window of it a texture holds: a run that +// straddles the window's edge keeps the part inside, and a run outside owns nothing. +func TestShiftGridSpansMovesTheColumnsOntoTheWindow(t *testing.T) { + spans := []GridSpan{{From: 0, To: 100}, {From: 100, To: 300}, {From: 300, To: 500}, {From: 500, To: 520}, {From: 700, To: 700}} + ShiftGridSpans(spans, 200, 300) + want := []GridSpan{{From: 0, To: 0}, {From: 0, To: 100}, {From: 100, To: 300}, {From: 300, To: 300}, {From: 300, To: 300}} + for index := range want { + if spans[index] != want[index] { + t.Errorf("span %d = %+v, want %+v", index, spans[index], want[index]) + } + } +} diff --git a/internal/platform/label_pixels.go b/internal/platform/label_pixels.go index 9373de64d..723ee419a 100644 --- a/internal/platform/label_pixels.go +++ b/internal/platform/label_pixels.go @@ -19,13 +19,114 @@ func DeviceExtent(logical, length, scale float32) int { return DevicePosition(logical+length, 0, scale) - DevicePosition(logical, 0, scale) } +// LabelTextureLimit is the widest and tallest texture a label is rasterized into, in +// device pixels: the 2D texture limit of the Direct3D 11 and Vulkan devices Viva runs +// on, and the limit native.m keeps for Metal. LabelTexturePixels bounds the pixels of +// one such texture. +const ( + LabelTextureLimit = 16384 + LabelTexturePixels = 16 * 1024 * 1024 +) + +// LabelTextureWidth is the widest texture a label height device pixels high is +// rasterized into: LabelTextureLimit, narrowed for a tall label so that its texture +// stays within LabelTexturePixels. It is 0 for a label too tall for any texture, +// which is not drawn. +func LabelTextureWidth(height int) int { + if height <= 0 || height > LabelTextureLimit { + return 0 + } + return min(LabelTextureLimit, LabelTexturePixels/height) +} + +// LabelTextureFits reports whether a label texture width by height device pixels is +// one a backend allocates: width is at most LabelTextureWidth(height). It is tested +// without a division, as renderers ask it of every label every frame. +func LabelTextureFits(width, height int) bool { + return width > 0 && height > 0 && width <= LabelTextureLimit && height <= LabelTextureLimit && width*height <= LabelTexturePixels +} + +// LabelVisibleColumns is the part of a label full device pixels wide, drawn at device +// column origin, that the device columns from left to right show: the columns from +// first to last, counted from the label's left edge. ok is false when they show none. +func LabelVisibleColumns(origin, full, left, right int) (first, last int, ok bool) { + first = min(max(left-origin, 0), full) + last = min(max(right-origin, 0), full) + return first, last, last > first +} + +// WideLabelWindow chooses the device columns that the texture of a label full columns +// wide, more than one texture of limit columns holds, is rasterized from: the columns +// from skip to skip+width of the label. The columns from left to right, with left +// below right, are the ones that can be seen, and haveSkip and haveWidth the window of +// the texture the label has, or a width of 0 when it has none. +// +// A texture that still holds every column that can be seen is kept, so a scroll inside +// it does not rasterize the line again. Otherwise the visible columns are kept with as +// much margin on both sides as they are wide, so a scroll of up to their width keeps +// the new texture; at an end of the label the margin goes to the other side. This is +// the window viva_label_window in native.m chooses. Visible columns wider than limit +// keep their first limit columns: these backends draw one texture per label, and a +// viewport is wider than limit only for a label so tall that its limit is narrowed. +func WideLabelWindow(full, limit, left, right, haveSkip, haveWidth int) (skip, width int) { + if haveWidth > 0 && haveWidth <= limit && haveSkip <= left && right <= haveSkip+haveWidth && haveSkip+haveWidth <= full { + return haveSkip, haveWidth + } + span := right - left + if span >= limit { + return left, limit + } + margin := min(span, (limit-span)/2) + width = span + 2*margin + skip = max(left-margin, 0) + if skip+width > full { + skip = full - width + } + return skip, width +} + +// WideTextLabelWindow is the window a text label's texture is rasterized from when one +// texture cannot hold the whole label. The label is full device columns wide and height +// high, drawn at the device column DevicePosition puts it at, on a target viewport device +// columns wide, or 0 when the caller has none. The columns that can be seen are the +// viewport's, cut to the label's clip; haveSkip and haveWidth are the window of the +// texture the label has, a width of 0 when it has none (see WideLabelWindow). wide is +// false for a label one texture holds whole, which is left to the caller. A wide label +// is not drawn, ok false, when none of it can be seen or it is too tall for any texture: +// an error for it would stop the window drawing anything. +func WideTextLabelWindow(label TextLabel, scale float32, full, height, viewport, haveSkip, haveWidth int) (skip, width int, wide, ok bool) { + limit := LabelTextureWidth(height) + if full <= limit { + return 0, full, false, full > 0 + } + if limit <= 0 { + return 0, 0, true, false + } + origin := DevicePosition(label.X, label.OriginX, scale) + left, right := 0, origin+full + if viewport > 0 { + right = min(right, viewport) + } + if label.Clipped { + left = max(left, int(math.Floor(float64(label.Clip.X*scale)))) + right = min(right, int(math.Ceil(float64((label.Clip.X+label.Clip.Width)*scale)))) + } + first, last, visible := LabelVisibleColumns(origin, full, left, right) + if !visible { + return 0, 0, true, false + } + skip, width = WideLabelWindow(full, limit, first, last, haveSkip, haveWidth) + return skip, width, true, true +} + // LabelWindow is the part of a label's texture that a clip can show, in device // pixels: the columns from skip to skip+width of a texture drawn at origin, whose // whole width is full, when the clip covers left to right. A clip that starts left // of the label keeps the whole texture. One that starts inside it skips the columns // it cuts, so a long scrolled line costs its visible width, not its whole width, // without moving the text by a fraction of a device pixel. ok is false when the -// clip shows none of those columns. +// clip shows none of those columns. It is for a label no wider than its texture +// limit; a wider one takes the window WideLabelWindow chooses. func LabelWindow(origin, full, left, right int) (skip, width int, ok bool) { if full <= 0 || right <= left { return 0, 0, false diff --git a/internal/platform/label_pixels_test.go b/internal/platform/label_pixels_test.go index 86aaa28b0..c33616899 100644 --- a/internal/platform/label_pixels_test.go +++ b/internal/platform/label_pixels_test.go @@ -1,6 +1,10 @@ package platform -import "testing" +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) // A layout position half a device pixel either way snaps to the nearest pixel, and // the remainder the painter took off is part of it. @@ -97,3 +101,123 @@ func TestBitmapTextureFollowsTheDrawnSize(t *testing.T) { t.Errorf("an image drawn larger than stored is %dx%d, want the stored size", width, height) } } + +// A label texture is held to the device limit across and to the pixel budget overall, so a +// tall label gets a narrower texture, and one taller than the limit gets none. +func TestLabelTextureWidthKeepsTheTextureBounded(t *testing.T) { + cases := []struct{ height, width int }{ + {0, 0}, + {-3, 0}, + {24, LabelTextureLimit}, + {1024, LabelTextureLimit}, + {2048, LabelTexturePixels / 2048}, + {LabelTextureLimit, LabelTexturePixels / LabelTextureLimit}, + {LabelTextureLimit + 1, 0}, + } + for _, c := range cases { + if got := LabelTextureWidth(c.height); got != c.width { + t.Errorf("LabelTextureWidth(%d) = %d, want %d", c.height, got, c.width) + } + } + if !LabelTextureFits(LabelTextureLimit, 24) || LabelTextureFits(LabelTextureLimit+1, 24) || LabelTextureFits(0, 24) { + t.Error("a short label's texture is not bounded by the device limit") + } + if LabelTextureFits(LabelTexturePixels/2048+1, 2048) { + t.Error("a tall label's texture is not bounded by the pixel budget") + } + // LabelTextureFits tests without a division what LabelTextureWidth bounds, at each edge. + for _, height := range []int{-1, 0, 1, 24, 1023, 1024, 1025, 2047, 2048, 3000, LabelTextureLimit - 1, LabelTextureLimit, LabelTextureLimit + 1} { + limit := LabelTextureWidth(height) + for _, width := range []int{-1, 0, 1, limit - 1, limit, limit + 1, LabelTextureLimit, LabelTextureLimit + 1} { + if got, want := LabelTextureFits(width, height), width > 0 && width <= limit; got != want { + t.Errorf("LabelTextureFits(%d, %d) = %v; LabelTextureWidth is %d", width, height, got, limit) + } + } + } +} + +// The columns a clip shows are counted from the label's left edge and cut to the label. +func TestLabelVisibleColumnsCutsTheClipToTheLabel(t *testing.T) { + cases := []struct { + name string + origin, full, left, right int + first, last int + ok bool + }{ + {"label inside", 100, 200, 0, 1000, 0, 200, true}, + {"label starts left of the clip", -5000, 40000, 0, 1920, 5000, 6920, true}, + {"label ends inside the clip", -39000, 40000, 0, 1920, 39000, 40000, true}, + {"clip left of the label", 2000, 100, 0, 1920, 100, 100, false}, + {"clip right of the label", -500, 100, 0, 1920, 100, 100, false}, + } + for _, c := range cases { + first, last, ok := LabelVisibleColumns(c.origin, c.full, c.left, c.right) + if ok != c.ok || ok && (first != c.first || last != c.last) { + t.Errorf("%s: LabelVisibleColumns(%d, %d, %d, %d) = %d, %d, %v; want %d, %d, %v", + c.name, c.origin, c.full, c.left, c.right, first, last, ok, c.first, c.last, c.ok) + } + } +} + +// A line wider than a texture holds is rasterized around what can be seen, with a margin of +// the visible width on each side, shifted inward at the ends of the line; a texture that +// still holds what can be seen is kept, and one that does not is replaced. +func TestWideLabelWindowKeepsTheVisibleColumnsWithAMargin(t *testing.T) { + const full, limit = 60000, LabelTextureLimit + cases := []struct { + name string + left, right int + haveSkip, haveWidth int + skip, width int + }{ + {"start of the line", 0, 2000, 0, 0, 0, 6000}, + {"middle of the line", 20000, 22000, 0, 0, 18000, 6000}, + {"end of the line", 58000, 60000, 0, 0, 54000, 6000}, + {"wide span", 10000, 20000, 0, 0, 10000 - 3192, 10000 + 2*3192}, + {"span wider than a texture", 1000, 1000 + limit + 10, 0, 0, 1000, limit}, + {"scroll inside the texture", 19000, 21000, 18000, 6000, 18000, 6000}, + {"scroll past the texture", 23000, 25000, 18000, 6000, 21000, 6000}, + {"texture past the end of the line", 0, 2000, 59000, 6000, 0, 6000}, + {"texture wider than the limit", 0, 2000, 0, limit + 1, 0, 6000}, + } + for _, c := range cases { + skip, width := WideLabelWindow(full, limit, c.left, c.right, c.haveSkip, c.haveWidth) + if skip != c.skip || width != c.width { + t.Errorf("%s: WideLabelWindow(%d, %d, %d, %d, %d, %d) = %d, %d; want %d, %d", + c.name, full, limit, c.left, c.right, c.haveSkip, c.haveWidth, skip, width, c.skip, c.width) + continue + } + if width > limit || skip < 0 || skip+width > full || skip > c.left || skip+width < min(c.right, skip+limit) { + t.Errorf("%s: window %d+%d does not hold the visible columns %d..%d within the limit", c.name, skip, width, c.left, c.right) + } + } +} + +// A text label wider than a texture is windowed to the columns the viewport shows, cut to +// its clip; one the viewport does not show, or too tall for any texture, is not drawn, and +// one a texture holds whole is left to its backend. +func TestWideTextLabelWindowFollowsTheViewportAndTheClip(t *testing.T) { + const scale, full, height, viewport = 1.5, 49164, 27, 600 + label := TextLabel{X: -20000} // 30000 device columns off the left of the viewport + cases := []struct { + name string + label TextLabel + full, height int + haveSkip, haveWidth int + skip, width int + wide, ok bool + }{ + {"viewport", label, full, height, 0, 0, 29400, 1800, true, true}, + {"clip", TextLabel{X: -20000, Clipped: true, Clip: gfx.Rect{X: 100, Width: 200}}, full, height, 0, 0, 29850, 900, true, true}, + {"kept texture", label, full, height, 29000, 2000, 29000, 2000, true, true}, + {"scrolled out", TextLabel{X: -40000}, full, height, 0, 0, 0, 0, true, false}, + {"too tall", label, full, LabelTextureLimit + 1, 0, 0, 0, 0, true, false}, + {"one texture holds it", label, 2000, height, 0, 0, 0, 2000, false, true}, + } + for _, c := range cases { + skip, width, wide, ok := WideTextLabelWindow(c.label, scale, c.full, c.height, viewport, c.haveSkip, c.haveWidth) + if skip != c.skip || width != c.width || wide != c.wide || ok != c.ok { + t.Errorf("%s: window = %d, %d, %v, %v; want %d, %d, %v, %v", c.name, skip, width, wide, ok, c.skip, c.width, c.wide, c.ok) + } + } +} diff --git a/internal/platform/linux/cpu_lcd_linux_test.go b/internal/platform/linux/cpu_lcd_linux_test.go index 5c188b237..3ce2aa7fe 100644 --- a/internal/platform/linux/cpu_lcd_linux_test.go +++ b/internal/platform/linux/cpu_lcd_linux_test.go @@ -62,7 +62,7 @@ func TestCPUGridLCDLabelKeepsItsRunColors(t *testing.T) { {Column: 1, Bytes: 1, Cells: 1, Color: gfx.RGB(0, 0, 255)}, }, } - image, ok, err := rasterizeLabel(services, label, 1, true) + image, ok, err := rasterizeLabel(services, label, 1, 0, labelImage{}, true) if err != nil || !ok { t.Fatalf("rasterize: ok=%v err=%v", ok, err) } diff --git a/internal/platform/linux/cpu_offscreen_linux.go b/internal/platform/linux/cpu_offscreen_linux.go index 0dcd5ed1b..61b5b2d7d 100644 --- a/internal/platform/linux/cpu_offscreen_linux.go +++ b/internal/platform/linux/cpu_offscreen_linux.go @@ -100,7 +100,7 @@ func (offscreen *CPUOffscreen) Close() { // device pixel (platform.DevicePosition), a clip takes every device pixel it touches. ok is false // when the label draws nothing. func prepareLabel(services *textServices, l platform.TextLabel, scale float32, canvasWidth, canvasHeight int, allowLCD bool) (label raster.Label, ok bool, err error) { - image, ok, err := rasterizeLabel(services, l, scale, allowLCD) + image, ok, err := rasterizeLabel(services, l, scale, canvasWidth, labelImage{}, allowLCD) if err != nil || !ok { return raster.Label{}, false, err } @@ -114,16 +114,41 @@ func prepareLabel(services *textServices, l platform.TextLabel, scale float32, c type labelImage struct { pixels []byte width, height int - lcd bool - spans []raster.Span + // skip is the device column of a text label the picture starts at: a line wider than a + // texture holds, wide, is drawn from the window of it the canvas shows (textWindow). It + // is 0 for every other label. + skip int + wide bool + lcd bool + spans []raster.Span +} + +// textWindow is the part of a text label drawn into its picture at scale on a canvas +// canvasWidth device pixels wide: the device columns from skip to skip+width of the label, +// height high. A label one texture holds is drawn whole. A wider one, wide, is drawn from +// the columns of it the canvas and its clip show, keeping have, the picture it has, while +// that still holds them (platform.WideTextLabelWindow); the Vulkan backend draws the same +// window. ok is false when nothing is drawn: none of a wide line can be seen, or no +// texture holds the label. +func textWindow(l platform.TextLabel, scale float32, canvasWidth int, have labelImage) (skip, width, height int, wide, ok bool) { + full := int(math.Ceil(float64(l.Width * scale))) + height = int(math.Ceil(float64(l.Height * scale))) + haveSkip, haveWidth := 0, 0 + if have.wide { + haveSkip, haveWidth = have.skip, have.width + } + skip, width, wide, ok = platform.WideTextLabelWindow(l, scale, full, height, canvasWidth, haveSkip, haveWidth) + return skip, width, height, wide, ok && platform.LabelTextureFits(width, height) } // rasterizeLabel draws a label's text, or resamples its image to the device pixels it covers. ok is // false when it draws nothing. The picture does not depend on where the label is, except that an -// image smaller than its bitmap does, through the fraction of a pixel it starts at. With allowLCD, -// and the desktop asking for subpixel antialiasing, text comes back as per-channel coverage for the +// image smaller than its bitmap does, through the fraction of a pixel it starts at, and a line +// wider than a texture holds is drawn from the window of it a canvas canvasWidth device pixels +// wide shows, kept from have, the picture the label has (textWindow). With allowLCD, and the +// desktop asking for subpixel antialiasing, text comes back as per-channel coverage for the // rasterizer to tint, the same way the Vulkan LCD shader reads it. -func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, allowLCD bool) (image labelImage, ok bool, err error) { +func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, canvasWidth int, have labelImage, allowLCD bool) (image labelImage, ok bool, err error) { if l.Width <= 0 || l.Height <= 0 || (l.Value == "" && len(l.Bitmap) == 0) { return labelImage{}, false, nil } @@ -138,13 +163,15 @@ func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, } return labelImage{pixels: tightBitmap(l.Bitmap, width, height, l.BitmapStride), width: width, height: height}, true, nil } - width := int(math.Ceil(float64(l.Width * scale))) - height := int(math.Ceil(float64(l.Height * scale))) - pixels, lcd, err := services.rasterize(l, scale, width, height, allowLCD) + skip, width, height, wide, shown := textWindow(l, scale, canvasWidth, have) + if !shown { + return labelImage{}, false, nil + } + pixels, lcd, err := services.rasterizeWindow(l, scale, skip, width, height, allowLCD) if err != nil { return labelImage{}, false, err } - image = labelImage{pixels: pixels, width: width, height: height, lcd: lcd} + image = labelImage{pixels: pixels, width: width, height: height, skip: skip, wide: wide, lcd: lcd} if lcd && len(services.spans) > 0 { image.spans = make([]raster.Span, len(services.spans)) for index, span := range services.spans { @@ -161,7 +188,7 @@ func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, // clip, if a canvas clip cuts it, on the device pixels the clip touches. ok is false when the clip // leaves nothing. func placeLabel(l platform.TextLabel, scale float32, image labelImage, canvasWidth, canvasHeight int) (label raster.Label, ok bool) { - x, y := platform.DevicePosition(l.X, l.OriginX, scale), platform.DevicePosition(l.Y, l.OriginY, scale) + x, y := platform.DevicePosition(l.X, l.OriginX, scale)+image.skip, platform.DevicePosition(l.Y, l.OriginY, scale) if len(l.Bitmap) > 0 { x, y = platform.DevicePosition(l.X, 0, scale), platform.DevicePosition(l.Y, 0, scale) } diff --git a/internal/platform/linux/soft_scene_linux.go b/internal/platform/linux/soft_scene_linux.go index 651f57f1e..368c5c560 100644 --- a/internal/platform/linux/soft_scene_linux.go +++ b/internal/platform/linux/soft_scene_linux.go @@ -176,11 +176,19 @@ func (s *softScene) setLabel(slot *softLabel, next platform.TextLabel) error { previous := slot.placed wasVisible := slot.visible redraw := !slot.hasImage || slot.imageScale != s.scale || labelContentChanged(slot.label, next) || (len(next.Bitmap) > 0 && bitmapShownChanged(slot.label, next, s.scale)) + var have labelImage + if !redraw && slot.image.wide { + // A line wider than a texture holds is drawn again when its picture, a window of + // it, no longer holds the part of it the canvas shows. + have = slot.image + skip, width, _, _, ok := textWindow(next, s.scale, s.canvas.Width, have) + redraw = !ok || skip != have.skip || width != have.width + } slot.runs = append(slot.runs[:0], next.Runs...) slot.label = next slot.label.Runs = slot.runs if redraw { - image, ok, err := rasterizeLabel(s.services, slot.label, s.scale, s.clear.Alpha >= 1) + image, ok, err := rasterizeLabel(s.services, slot.label, s.scale, s.canvas.Width, have, s.clear.Alpha >= 1) if err != nil { return err } diff --git a/internal/platform/linux/text_engine_linux.go b/internal/platform/linux/text_engine_linux.go index aa33822a6..639915104 100644 --- a/internal/platform/linux/text_engine_linux.go +++ b/internal/platform/linux/text_engine_linux.go @@ -108,7 +108,7 @@ func (engine *textEngine) RasterizeText(value string, style gfx.TextStyle, scale Red: float64(style.Color.Red), Green: float64(style.Color.Green), Blue: float64(style.Color.Blue), Alpha: float64(style.Color.Alpha), }, - }, scale, width, height, false) + }, scale, 0, width, height, false) if err != nil { return gfx.Bitmap{}, err } diff --git a/internal/platform/linux/text_linux.go b/internal/platform/linux/text_linux.go index 6be23c2bd..a1b481ac1 100644 --- a/internal/platform/linux/text_linux.go +++ b/internal/platform/linux/text_linux.go @@ -483,6 +483,15 @@ func NewTextMeasurer() (text.MeasureFunc, func(), error) { // the renderer to blend with the label's color, and lcd is true. Otherwise the pixels are // premultiplied BGRA in the label's color. func (services *textServices) rasterize(label platform.TextLabel, scale float32, width, height int, allowLCD bool) (pixels []byte, lcd bool, err error) { + return services.rasterizeWindow(label, scale, 0, width, height, allowLCD) +} + +// rasterizeWindow draws the device columns from skip to skip+width of the label, as +// rasterize draws the whole of it: a line wider than a texture holds is drawn from a +// window of it (platform.WideTextLabelWindow). skip is a whole number of device +// columns, so every glyph keeps the phase it has in the whole line, and the columns +// of services.spans are the window's. +func (services *textServices) rasterizeWindow(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) (pixels []byte, lcd bool, err error) { settings := systemFonts() services.spans = services.spans[:0] // A fixed-pitch label is LCD text too, unless it holds a color glyph, which has no @@ -493,12 +502,15 @@ func (services *textServices) rasterize(label platform.TextLabel, scale float32, settings = settings.grayscale() } services.useFonts(settings) - pixels, err = services.draw(label, scale, width, height, lcd) + pixels, err = services.draw(label, scale, skip, width, height, lcd) return pixels, lcd && err == nil, err } -func (services *textServices) draw(label platform.TextLabel, scale float32, width, height int, lcd bool) ([]byte, error) { - if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 { +// draw draws the device columns from skip to skip+width of the label into pixels width +// by height. The renderers do not ask for a texture larger than platform.LabelTextureFits +// allows: they window a wide line and leave a label no texture holds undrawn. +func (services *textServices) draw(label platform.TextLabel, scale float32, skip, width, height int, lcd bool) ([]byte, error) { + if !platform.LabelTextureFits(width, height) || skip < 0 { return nil, fmt.Errorf("linux: label texture exceeds bounded size") } if !validFontSize(label.FontSize) || scale <= 0 || math.IsNaN(float64(scale)) || math.IsInf(float64(scale), 0) { @@ -525,6 +537,10 @@ func (services *textServices) draw(label platform.TextLabel, scale float32, widt return nil, fmt.Errorf("linux: create Cairo text context") } defer services.cairoDestroy(context) + if skip > 0 { + // The line is drawn where it stands; the surface is the window of it. + services.cairoTranslate(context, -float64(skip), 0) + } if label.Value != "" { if len(label.Runs) == 0 { family := proportionalFamily @@ -553,7 +569,7 @@ func (services *textServices) draw(label platform.TextLabel, scale float32, widt return nil, err } } - } else if err := services.drawRuns(context, label, scale, width, height, lcd); err != nil { + } else if err := services.drawRuns(context, label, scale, skip, width, height, lcd); err != nil { return nil, err } } @@ -614,8 +630,10 @@ type colorSpan struct { } // drawRuns draws a fixed-pitch label's runs. With lcd they are drawn white, for their coverage, -// and the color of each run is recorded in services.spans instead. -func (services *textServices) drawRuns(context uintptr, label platform.TextLabel, scale float32, width, height int, lcd bool) error { +// and the color of each run is recorded in services.spans instead. The surface is the device +// columns from skip to skip+width of the line, translated onto them: a run outside them is not +// drawn, and the columns of its spans are the surface's. +func (services *textServices) drawRuns(context uintptr, label platform.TextLabel, scale float32, skip, width, height int, lcd bool) error { pitch := float64(label.CellWidth * scale) if pitch <= 0 || math.IsNaN(pitch) || math.IsInf(pitch, 0) { return fmt.Errorf("linux: invalid fixed-pitch cell width") @@ -626,7 +644,8 @@ func (services *textServices) drawRuns(context uintptr, label platform.TextLabel return err } baseline := float64(platform.TextBaseline(label, height, scale)) - columns := services.ownedColumns(label, family, scale, pitch, width) + columns := services.ownedColumns(label, family, scale, pitch, skip+width) + shownLeft, shownRight := float64(skip), float64(skip+width) offset := 0 for index, run := range label.Runs { end := offset + int(run.Bytes) @@ -643,6 +662,9 @@ func (services *textServices) drawRuns(context uintptr, label platform.TextLabel // The run draws in the columns it owns, which are its cells and the blank cells its // ink reaches into, and nowhere else. owned := columns[index] + if min(float64(owned.From), left) >= shownRight || max(float64(owned.To), left+span) <= shownLeft { + continue // the run is outside the window of the line + } services.cairoSave(context) services.cairoRectangle(context, float64(owned.From), 0, float64(owned.To-owned.From), float64(height)) services.cairoClip(context) @@ -654,8 +676,7 @@ func (services *textServices) drawRuns(context uintptr, label platform.TextLabel } } source() - if lcd && run.Cells > 0 && piece != "" && owned.To > owned.From { - from, to := owned.From, owned.To + if from, to := min(max(owned.From-skip, 0), width), min(max(owned.To-skip, 0), width); lcd && run.Cells > 0 && piece != "" && to > from { services.addSpan(from, to, [4]float32{run.Color.Red, run.Color.Green, run.Color.Blue, run.Color.Alpha}) } metrics := baseMetrics @@ -679,7 +700,10 @@ func (services *textServices) drawRuns(context uintptr, label platform.TextLabel services.cairoRestore(context) } } else if printableASCII(piece) { - for index := range len(piece) { + // ASCII ink stays inside its cell; a cell either side holds an italic's overhang. + first := max(int(math.Floor((shownLeft-left)/pitch))-1, 0) + last := min(int(math.Ceil((shownRight-left)/pitch))+1, len(piece)) + for index := first; index < last; index++ { metrics, err = services.configureLayout(piece[index:index+1], family, label.FontSize*scale, run.Weight, run.Italic) if err != nil { services.cairoRestore(context) diff --git a/internal/platform/linux/vulkan_linux.go b/internal/platform/linux/vulkan_linux.go index 4411b6a82..ee7be0dbe 100644 --- a/internal/platform/linux/vulkan_linux.go +++ b/internal/platform/linux/vulkan_linux.go @@ -964,7 +964,7 @@ func (renderer *vulkanRenderer) createScenePipelines(extent vkExtent2D) error { return err } } - if err := renderer.text.upload(renderer, renderer.pixelScale()); err != nil { + if err := renderer.text.upload(renderer, renderer.pixelScale(), renderer.textViewport(extent.Width, extent.Height)); err != nil { return err } return renderer.recordCommands(extent) @@ -1302,7 +1302,7 @@ func (renderer *vulkanRenderer) stageFrame(frame platform.Frame) (bool, error) { } } renderer.compositingBatches = groupCompositingLayers(renderer.rectangleBatches, renderer.text.labels, renderer.text.order, renderer.compositingBatches) - if err := renderer.text.upload(renderer, renderer.pixelScale()); err != nil { + if err := renderer.text.upload(renderer, renderer.pixelScale(), renderer.textViewport(renderer.width, renderer.height)); err != nil { return false, err } return true, nil @@ -1360,7 +1360,7 @@ func (renderer *vulkanRenderer) setScaleOnce(scale float32) error { if err := vkCheck(renderer.api.deviceWaitIdle(renderer.device), "wait before scale change"); err != nil { return err } - if err := renderer.text.upload(renderer, scale); err != nil { + if err := renderer.text.upload(renderer, scale, renderer.textViewport(renderer.width, renderer.height)); err != nil { return err } return renderer.recordCommands(vkExtent2D{Width: renderer.width, Height: renderer.height}) diff --git a/internal/platform/linux/vulkan_refresh_linux.go b/internal/platform/linux/vulkan_refresh_linux.go index 3a7218296..3aae4087d 100644 --- a/internal/platform/linux/vulkan_refresh_linux.go +++ b/internal/platform/linux/vulkan_refresh_linux.go @@ -19,7 +19,7 @@ func (renderer *vulkanRenderer) refreshText() error { label.closeImage(renderer) } } - if err := renderer.text.upload(renderer, renderer.pixelScale()); err != nil { + if err := renderer.text.upload(renderer, renderer.pixelScale(), renderer.textViewport(renderer.width, renderer.height)); err != nil { return fmt.Errorf("linux: refresh text: %w", err) } return renderer.recordCommands(vkExtent2D{Width: renderer.width, Height: renderer.height}) diff --git a/internal/platform/linux/vulkan_text_linux.go b/internal/platform/linux/vulkan_text_linux.go index aadd03635..c1ffa81f7 100644 --- a/internal/platform/linux/vulkan_text_linux.go +++ b/internal/platform/linux/vulkan_text_linux.go @@ -164,6 +164,15 @@ type vulkanLabelTexture struct { scale float32 // width and height are the texture's size in device pixels. width, height int + // skip is the device column of the label the texture starts at: a line wider than a + // texture holds, wide, has a texture of the window of it that can be seen + // (platform.WideTextLabelWindow). It is 0 for every other label. + skip int + wide bool + // dropped is set when the label has no texture at scale because none holds it or, + // wide, none of it can be seen: it draws nothing, and is not rasterized every frame + // for that. + dropped bool // lcd is set when the texture holds the coverage of each channel of LCD text, to be // blended with the label's color by the LCD pipeline. lcd bool @@ -599,14 +608,75 @@ func validateTextLabel(index int, label platform.TextLabel) error { return nil } -func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32) error { +// needsUpload reports whether the label is rasterized again at scale for a scene viewport +// device pixels wide: it has no texture there, its image's texture no longer suits the size +// it is drawn at, or it is a wide line whose texture no longer holds the part of it that can +// be seen. +func (label *vulkanLabelTexture) needsUpload(scale float32, viewport int) bool { + l := label.label + if l.Value == "" && len(l.Bitmap) == 0 || l.Width <= 0 || l.Height <= 0 { + return false + } + if label.scale != scale || label.view == 0 && !label.dropped { + return true + } + if len(l.Bitmap) > 0 { + if label.view == 0 { + return platform.LabelTextureFits(platform.BitmapTextureExtent(l, scale)) + } + return bitmapTextureStale(label, scale) + } + if !label.wide { + return false + } + skip, width, _, _, ok := label.window(scale, viewport) + return ok != (label.view != 0) || ok && (skip != label.skip || width != label.width) +} + +// window is the part of a text label's texture that is rasterized at scale for a scene +// viewport device pixels wide: the device columns from skip to skip+width of the label, +// height high. A label one texture holds is rasterized whole, at the width +// labelRasterWidth reserves; a wider one from the window of it that can be seen, which +// keeps the texture it has while that still holds them; wide is set for such a line. ok +// is false when it is not drawn: none of a wide line can be seen, or no texture holds +// the label. +func (label *vulkanLabelTexture) window(scale float32, viewport int) (skip, width, height int, wide, ok bool) { + height = int(math.Ceil(float64(label.label.Height * scale))) + full := labelRasterWidth(label.label, scale, height) + haveSkip, haveWidth := 0, 0 + if label.view != 0 && label.scale == scale { + haveSkip, haveWidth = label.skip, label.width + } + skip, width, wide, ok = platform.WideTextLabelWindow(label.label, scale, full, height, viewport, haveSkip, haveWidth) + return skip, width, height, wide, ok && platform.LabelTextureFits(width, height) +} + +// drop leaves the label without a texture at scale, for one it cannot have: a label no +// texture holds is not drawn, and does not stop the window drawing the others. +func (label *vulkanLabelTexture) drop(renderer *vulkanRenderer, scale float32, wide bool) { + label.closeImage(renderer) + label.scale, label.wide, label.dropped = scale, wide, true +} + +// textViewport is the device width of the scene in a target width by height: the width a +// line wider than a texture holds is windowed to. +func (renderer *vulkanRenderer) textViewport(width, height uint32) int { + if renderer.frame.active() { + _, _, content := renderer.frame.content(width, height) + return int(content.Width) + } + return int(width) +} + +// upload rasterizes and uploads every label that needsUpload at scale, for a scene +// viewport device pixels wide. +func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, viewport int) error { if textState.services == nil || renderer.uploadCommand == 0 { return nil } dirty := false for index := range textState.labels { - label := &textState.labels[index] - if (label.label.Value != "" || len(label.label.Bitmap) > 0) && label.label.Width > 0 && label.label.Height > 0 && (label.view == 0 || label.scale != scale || bitmapTextureStale(label, scale)) { + if textState.labels[index].needsUpload(scale, viewport) { dirty = true break } @@ -627,17 +697,21 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32) err defer closeStaging() for index := range textState.labels { label := &textState.labels[index] - if label.label.Value == "" && len(label.label.Bitmap) == 0 || label.label.Width <= 0 || label.label.Height <= 0 || label.view != 0 && label.scale == scale && !bitmapTextureStale(label, scale) { + if !label.needsUpload(scale, viewport) { continue } - height := int(math.Ceil(float64(label.label.Height * scale))) - width := labelRasterWidth(label.label, scale, height) var pixels []byte - lcd := false + lcd, wide := false, false var spans []colorSpan + skip, width, height := 0, 0, 0 if len(label.label.Bitmap) > 0 { width, height = label.label.BitmapWidth, label.label.BitmapHeight - if shown, high := platform.BitmapTextureExtent(label.label, scale); shown < width || high < height { + shown, high := platform.BitmapTextureExtent(label.label, scale) + if !platform.LabelTextureFits(shown, high) { + label.drop(renderer, scale, false) + continue + } + if shown < width || high < height { // A bitmap drawn smaller than it is stored is averaged down to the device // pixels it covers; sampling a few of its texels would alias. pixels = platform.ResampleBGRA(label.label.Bitmap, label.label.BitmapStride, width, height, shown, high) @@ -647,10 +721,16 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32) err pixels = tightBitmap(label.label.Bitmap, width, height, label.label.BitmapStride) } } else { + var ok bool + skip, width, height, wide, ok = label.window(scale, viewport) + if !ok { + label.drop(renderer, scale, wide) + continue + } var err error // ClearType-style blending needs an opaque target: a window or an offscreen // image cleared opaque. - pixels, lcd, err = textState.services.rasterize(label.label, scale, width, height, renderer.dualSource && textState.lcdPipeline != 0 && renderer.color.Alpha >= 1) + pixels, lcd, err = textState.services.rasterizeWindow(label.label, scale, skip, width, height, renderer.dualSource && textState.lcdPipeline != 0 && renderer.color.Alpha >= 1) if err != nil { return fmt.Errorf("linux: rasterize label %d: %w", index, err) } @@ -662,7 +742,7 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32) err } staging = append(staging, stage) label.scale, label.lcd = scale, lcd - label.width, label.height = width, height + label.width, label.height, label.skip, label.wide = width, height, skip, wide label.spans = append(label.spans[:0], spans...) // after createImage, which clears the label } if err := vkCheck(renderer.api.endCommandBuffer(renderer.uploadCommand), "end text upload"); err != nil { @@ -693,7 +773,7 @@ func labelRasterWidth(label platform.TextLabel, scale float32, height int) int { if len(label.Runs) > 0 && label.CellWidth > 0 && height > 0 && width > 0 && ok { step := float64(label.CellWidth) * 16 reserved := min(math.Ceil(float64(label.Width)/step)*step, float64(needed)) - limit := min(16384, 16*1024*1024/height) + limit := platform.LabelTextureWidth(height) if width <= limit { width = max(width, int(min(math.Ceil(reserved*float64(scale)), float64(limit)))) } @@ -864,6 +944,7 @@ func (textState *vulkanText) record(renderer *vulkanRenderer, command uintptr, e // A grid line has a color per run: its coverage is drawn once for each, cut to the // columns of the run. origin, _ := label.pixelOrigin(scale) + origin += label.skip // the spans are the texture's columns for spanIndex := range label.spans { span := &label.spans[spanIndex] scratch.cut = scratch.scissor @@ -881,11 +962,12 @@ func (textState *vulkanText) record(renderer *vulkanRenderer, command uintptr, e // quad is where the label's texture is drawn, in logical pixels: its top left and its size are // whole device pixels, so every texel lands on one pixel and the sampler blends none with its -// neighbour. Text takes the texture's own size; an image takes the device pixels -// its logical bounds cover. +// neighbour. Text takes the texture's own size, at the columns of the label it holds; an +// image takes the device pixels its logical bounds cover. func (label *vulkanLabelTexture) quad(scale float32) [4]float32 { l := label.label x, y := label.pixelOrigin(scale) + x += label.skip width, height := label.width, label.height if len(l.Bitmap) > 0 { width, height = platform.DeviceExtent(l.X, l.Width, scale), platform.DeviceExtent(l.Y, l.Height, scale) @@ -934,6 +1016,7 @@ func labelScissor(label platform.TextLabel, scale float32, extent vkExtent2D) (s } func (label *vulkanLabelTexture) closeImage(renderer *vulkanRenderer) { + label.skip, label.wide, label.dropped = 0, false, false if renderer == nil || renderer.api == nil || renderer.device == 0 { label.image, label.memory, label.view, label.scale, label.lcd = 0, 0, 0, 0, false label.width, label.height, label.spans = 0, 0, label.spans[:0] diff --git a/internal/platform/linux/wide_label_linux_test.go b/internal/platform/linux/wide_label_linux_test.go new file mode 100644 index 000000000..42307d456 --- /dev/null +++ b/internal/platform/linux/wide_label_linux_test.go @@ -0,0 +1,254 @@ +package linux + +import ( + "bytes" + "errors" + "image" + "strings" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// wideValue is a log line of 4096 characters: at 8 logical pixels a cell and 150% it is +// 49152 device pixels wide, three times what a texture holds. +var wideValue = strings.Repeat("0123456789abcdef", 256) + +func wideMonoLine(value string, x float32, runs []gfx.TextRun) platform.TextLabel { + return platform.TextLabel{ + Value: value, X: x, Y: 4, Width: float32(len(value))*8 + 8, Height: 18, FontSize: 13, CellWidth: 8, + Mono: true, Runs: runs, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + Clipped: true, Clip: gfx.Rect{Width: 400, Height: 40}, + } +} + +func wholeRun(value string) []gfx.TextRun { + return []gfx.TextRun{{Bytes: int32(len(value)), Cells: int32(len(value)), Weight: 400, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}}} +} + +// wideBackends open a 400 by 40 scene at 150%, cleared to clear, with the Vulkan renderer and +// with the CPU one, and return what draws labels on it. A backend the machine cannot run skips. +var wideBackends = []struct { + name string + open func(t *testing.T, clear platform.Color) func(labels ...platform.TextLabel) *image.RGBA +}{ + {"Vulkan", func(t *testing.T, clear platform.Color) func(labels ...platform.TextLabel) *image.RGBA { + t.Helper() + offscreen, err := NewOffscreen(400, 40, 1.5, clear) + if errors.Is(err, platform.ErrNoGraphics) { + t.Skipf("no Vulkan device: %v", err) + } + if err != nil { + t.Fatal(err) + } + t.Cleanup(offscreen.Close) + return func(labels ...platform.TextLabel) *image.RGBA { return renderScene(t, offscreen, nil, labels) } + }}, + {"CPU", func(t *testing.T, clear platform.Color) func(labels ...platform.TextLabel) *image.RGBA { + t.Helper() + offscreen, err := NewCPUOffscreen(400, 40, 1.5, clear) + if err != nil { + t.Skipf("no text services: %v", err) // Pango and Cairo are system libraries + } + t.Cleanup(offscreen.Close) + return func(labels ...platform.TextLabel) *image.RGBA { + t.Helper() + if err := offscreen.Set(nil, labels); err != nil { + t.Fatal(err) + } + pixels, err := offscreen.Image() + if err != nil { + t.Fatal(err) + } + return pixels + } + }}, +} + +// A line wider than a texture holds gets a texture of the window of it that the viewport and +// its clip show, with or without runs. A scroll inside that window keeps the texture and one +// past it rasterizes the line again; a line scrolled out of view, or too tall for any texture, +// is dropped and not rasterized again every frame for that. +func TestVulkanWideLabelWindowFollowsTheViewport(t *testing.T) { + const scale, viewport = 1.5, 600 + for _, runs := range [][]gfx.TextRun{nil, wholeRun(wideValue)} { + label := vulkanLabelTexture{label: wideMonoLine(wideValue, 0, runs)} + if skip, width, height, wide, ok := label.window(scale, viewport); !ok || !wide || skip != 0 || width != 1800 || height != 27 { + t.Errorf("runs %d, start of the line: window = %d, %d, %d, %v, %v; want 0, 1800, 27, wide", len(runs), skip, width, height, wide, ok) + } + label.label.X = -20000 // 30000 device pixels scrolled off the left + if skip, width, _, _, ok := label.window(scale, viewport); !ok || skip != 30000-600 || width != 1800 { + t.Errorf("runs %d, scrolled: window = %d, %d, %v; want 29400, 1800", len(runs), skip, width, ok) + } + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a wide line without a texture is not rasterized", len(runs)) + } + label.view, label.scale, label.skip, label.width, label.height, label.wide = 1, scale, 29400, 1800, 27, true + label.label.X = -20100 + if label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a scroll inside the texture's window rasterizes the line again", len(runs)) + } + label.label.X = -21000 + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a scroll past the texture's window keeps the texture", len(runs)) + } + label.label.X = -40000 + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a line scrolled out of view keeps its texture", len(runs)) + } + if _, _, _, wide, ok := label.window(scale, viewport); ok || !wide { + t.Errorf("runs %d: a line scrolled out of view has a window", len(runs)) + } + label.drop(nil, scale, true) + if label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a dropped line out of view is rasterized again", len(runs)) + } + label.label.X = -20000 + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a dropped line scrolled back into view is not rasterized", len(runs)) + } + label.label.Height = 12000 // 18000 device pixels + if _, _, _, _, ok := label.window(scale, viewport); ok { + t.Errorf("runs %d: a line too tall for any texture has a window", len(runs)) + } + label.drop(nil, scale, false) + if label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a dropped line too tall for any texture is rasterized again", len(runs)) + } + } +} + +// A monospaced line wider than any texture, such as a long log line shown unwrapped, is drawn +// from a window of it at its start and scrolled, on an opaque target and a transparent one, +// without and with runs, by the Vulkan renderer and by the CPU one. Its pixels are the pixels +// of the start of the same line, which one texture holds, drawn where it is: the window moves +// no glyph. Drawing it whole asked for a texture larger than the bound, and the error stopped +// the window drawing anything again. The Vulkan scene draws each scroll in turn, so the +// texture of the line is windowed again as it scrolls. +func TestWideMonoLineIsDrawnFromAWindowOfIt(t *testing.T) { + scrolls := []int{0, 1000} // characters scrolled off the left + for _, backend := range wideBackends { + t.Run(backend.name, func(t *testing.T) { + for _, clear := range []platform.Color{{Alpha: 1}, {}} { + draw := backend.open(t, clear) + for _, withRuns := range []bool{false, true} { + name := map[bool]string{false: "transparent", true: "opaque"}[clear.Alpha >= 1] + + map[bool]string{false: "", true: " with runs"}[withRuns] + wide := make([]*image.RGBA, len(scrolls)) + for index, scrolled := range scrolls { + var runs []gfx.TextRun + if withRuns { + runs = wholeRun(wideValue) + } + wide[index] = draw(wideMonoLine(wideValue, -8*float32(scrolled), runs)) + } + for index, scrolled := range scrolls { + start := wideValue[:scrolled+300] + var runs []gfx.TextRun + if withRuns { + runs = wholeRun(start) + } + want := draw(wideMonoLine(start, -8*float32(scrolled), runs)) + got, painted := wide[index], 0 + for y := 0; y < 60; y++ { + for x := 0; x < 600; x++ { + if got.RGBAAt(x, y) != want.RGBAAt(x, y) { + t.Fatalf("%s, %d characters scrolled: pixel %d,%d is %v, the start of the line's is %v", + name, scrolled, x, y, got.RGBAAt(x, y), want.RGBAAt(x, y)) + } + if isPainted(got, x, y) { + painted++ + } + } + } + if painted < 1000 { + t.Errorf("%s, %d characters scrolled: %d pixels of text painted", name, scrolled, painted) + } + } + } + } + }) + } +} + +// The CPU window's scene draws a line wider than a texture holds from the window of it the +// canvas shows. A scroll inside that window keeps its picture, one past it draws a new window, +// and a line scrolled off the canvas has no picture until it is scrolled back; after each the +// canvas is what a scene built with the line where it is paints. +func TestSoftSceneDrawsAWideLineFromWhatTheCanvasShows(t *testing.T) { + services, err := newTextServices() + if err != nil { + t.Skipf("no text services: %v", err) + } + const scale = 1.5 + clear := platform.Color{Alpha: 1} + label := wideMonoLine(wideValue, 0, wholeRun(wideValue)) + live, err := newSoftScene(services, 600, 60, scale, clear, nil, []platform.TextLabel{label}) + if err != nil { + t.Fatal(err) + } + live.paint() + for _, step := range []struct { + name string + x float32 + skip int // the first column of the line's picture, or -1 for none + }{ + {"scrolled inside its picture", -100, 0}, + {"scrolled past its picture", -8000, 11400}, + {"scrolled a little", -8100, 11400}, + {"scrolled off the canvas", -40000, -1}, + {"scrolled back", -8000, 11400}, + } { + next := label + next.X = step.x + if _, err := live.apply(platform.Frame{TextLabels: []platform.TextLabel{next}}); err != nil { + t.Fatalf("%s: %v", step.name, err) + } + live.paint() + slot := &live.labels[0] + switch { + case step.skip < 0 && (slot.hasImage || slot.visible): + t.Errorf("%s: the line has a picture", step.name) + case step.skip >= 0 && (!slot.hasImage || !slot.visible || slot.image.skip != step.skip || slot.image.width != 1800): + t.Errorf("%s: picture from column %d, %d wide (drawn %v); want %d, 1800", step.name, slot.image.skip, slot.image.width, slot.hasImage, step.skip) + } + whole, err := newSoftScene(services, live.canvas.Width, live.canvas.Height, scale, clear, nil, []platform.TextLabel{next}) + if err != nil { + t.Fatal(err) + } + whole.paint() + if !bytes.Equal(live.canvas.Pix, whole.canvas.Pix) { + t.Fatalf("%s: canvas differs from a full paint", step.name) + } + } +} + +// A label no texture holds, an image larger than one or a line taller than one, is not drawn, +// and the labels beside it still are: one label a renderer cannot hold does not fail the frame. +// The CPU renderer has no texture and may draw the image. +func TestLabelNoTextureHoldsDoesNotFailTheFrame(t *testing.T) { + const imageWidth = platform.LabelTextureLimit + 16 + tall := platform.TextLabel{Value: "tall", X: 200, Y: 0, Width: 40, Height: platform.LabelTextureLimit + 1, FontSize: 13, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + wide := platform.TextLabel{X: 0, Y: 30, Width: imageWidth, Height: 2, + Bitmap: make([]byte, imageWidth*2*4), BitmapWidth: imageWidth, BitmapHeight: 2, BitmapStride: imageWidth * 4, BitmapID: 1, BitmapVersion: 1} + beside := platform.TextLabel{Value: "beside", X: 10, Y: 4, Width: 80, Height: 18, FontSize: 13, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + for _, backend := range wideBackends { + t.Run(backend.name, func(t *testing.T) { + pixels := backend.open(t, platform.Color{Alpha: 1})(tall, wide, beside) + painted := 0 + for y := 0; y < 40; y++ { // the label beside, at 150% + for x := 0; x < 150; x++ { + if isPainted(pixels, x, y) { + painted++ + } + } + } + if painted == 0 { + t.Fatal("the label beside one no texture holds was not drawn") + } + }) + } +} diff --git a/internal/platform/windows/direct_grid_windows.go b/internal/platform/windows/direct_grid_windows.go index 8bad25bf8..a2f311b2a 100644 --- a/internal/platform/windows/direct_grid_windows.go +++ b/internal/platform/windows/direct_grid_windows.go @@ -18,12 +18,14 @@ type gridPiece struct { } // gridPieces splits a fixed-pitch label into its runs. A label without runs is one piece -// of the label's own color and weight. -func (rasterizer *directRasterizer) gridPieces(label platform.TextLabel, pitch float32) []gridPiece { +// of the label's own color and weight. skip is the whole device columns of the line left of +// the texture the pieces are drawn into: each piece stands that much further left, so the +// glyphs keep the columns they have when the whole line is drawn. +func (rasterizer *directRasterizer) gridPieces(label platform.TextLabel, pitch float32, skip int) []gridPiece { rasterizer.pieces = rasterizer.pieces[:0] if len(label.Runs) == 0 { rasterizer.pieces = append(rasterizer.pieces, gridPiece{ - text: label.Value, weight: label.Weight, index: -1, + text: label.Value, weight: label.Weight, index: -1, left: -float32(skip), color: d2dColor{R: float32(label.Color.Red), G: float32(label.Color.Green), B: float32(label.Color.Blue), A: float32(label.Color.Alpha)}, }) return rasterizer.pieces @@ -42,7 +44,7 @@ func (rasterizer *directRasterizer) gridPieces(label platform.TextLabel, pitch f rasterizer.pieces = append(rasterizer.pieces, gridPiece{ text: text, run: run, weight: run.Weight, color: d2dColor{R: run.Color.Red, G: run.Color.Green, B: run.Color.Blue, A: run.Color.Alpha}, - left: float32(run.Column) * pitch, span: float32(run.Cells) * pitch, index: index, + left: float32(run.Column)*pitch - float32(skip), span: float32(run.Cells) * pitch, index: index, }) } return rasterizer.pieces @@ -66,15 +68,17 @@ type colorSpan struct { // and drawing a saturated color twice for the brightness of each channel would double the // cost of the terminal for a difference nobody sees. Runs stand on cells of the grid, so the // columns of one run never hold the glyphs of another except for the last pixel the -// ClearType filter spills over. -func (rasterizer *directRasterizer) gridLCD(pixels []byte, label platform.TextLabel, scale float32, width, height int) error { +// ClearType filter spills over. skip is as for grid: the columns a run owns are planned along +// the whole line, as its neighbours' ink reaches, and then moved onto the texture. +func (rasterizer *directRasterizer) gridLCD(pixels []byte, label platform.TextLabel, scale float32, width, height, skip int) error { family := monoFamily(label.MonoFace) fallback := rasterizer.fontFallback(label.MonoFace) size := label.FontSize * scale pitch := label.CellWidth * scale baseline := float32(platform.TextBaseline(label, height, scale)) - pieces := rasterizer.gridPieces(label, pitch) - columns := rasterizer.ownedColumns(label, pieces, family, fallback, size, pitch, width) + pieces := rasterizer.gridPieces(label, pitch, skip) + columns := rasterizer.ownedColumns(label, pieces, family, fallback, size, pitch, skip+width) + platform.ShiftGridSpans(columns, skip, width) if err := rasterizer.useGDI(pieces, family, size, width, height); err != nil { return err } diff --git a/internal/platform/windows/direct_windows.go b/internal/platform/windows/direct_windows.go index 787d5e94b..26df93e5d 100644 --- a/internal/platform/windows/direct_windows.go +++ b/internal/platform/windows/direct_windows.go @@ -295,9 +295,9 @@ func (rasterizer *directRasterizer) rasterize(label platform.TextLabel, scale fl rasterizer.spans = rasterizer.spans[:0] if label.Mono || len(label.Runs) > 0 { if allowLCD && !platform.ColorGlyphs(label.Value) { - return pixels, true, rasterizer.gridLCD(pixels, label, scale, width, height) + return pixels, true, rasterizer.gridLCD(pixels, label, scale, width, height, skip) } - return pixels, false, rasterizer.grid(pixels, label, scale, width, height) + return pixels, false, rasterizer.grid(pixels, label, scale, width, height, skip) } lcd = allowLCD && !platform.ColorGlyphs(label.Value) baseline := float32(platform.TextBaseline(label, height, scale)) @@ -485,7 +485,8 @@ func coverageOfChannels(pixels []byte, bitmap *textBitmap, width, height int, dr // weight and decorations of their own, each character on its cell of the grid (Viva's, not the // font's), or the whole value of a monospaced label. Colors are applied as the text is drawn // (premultiplied BGRA, grayscale antialiasing), so a line is one texture however many colors it holds. -func (rasterizer *directRasterizer) grid(pixels []byte, label platform.TextLabel, scale float32, width, height int) error { +// skip is the device columns of the line left of the texture, for a line wider than a texture holds. +func (rasterizer *directRasterizer) grid(pixels []byte, label platform.TextLabel, scale float32, width, height, skip int) error { family := monoFamily(label.MonoFace) fallback := rasterizer.fontFallback(label.MonoFace) size := label.FontSize * scale @@ -499,7 +500,7 @@ func (rasterizer *directRasterizer) grid(pixels []byte, label platform.TextLabel fill(scratch, width, height, d2dColor{}) target.begin(d2dColor{A: 1}, d2dAntialiasGrayscale) var drawErr error - for _, piece := range rasterizer.gridPieces(label, pitch) { + for _, piece := range rasterizer.gridPieces(label, pitch, skip) { target.setColor(piece.color) if err := rasterizer.drawRun(target, family, fallback, size, piece.weight, piece.run, piece.text, piece.left, piece.span, pitch, baseline, pieceClip{}); err != nil && drawErr == nil { drawErr = err diff --git a/internal/platform/windows/label_picture_windows.go b/internal/platform/windows/label_picture_windows.go index 3e00b4108..c7435beac 100644 --- a/internal/platform/windows/label_picture_windows.go +++ b/internal/platform/windows/label_picture_windows.go @@ -153,8 +153,8 @@ func (label *labelTexture) usePicture(picture *labelPicture) { label.spans = label.spans[:0] } -func (renderer *renderer) reuseLabelPicture(label *labelTexture, scale float32) bool { - skip, width, shown := label.window(scale) +func (renderer *renderer) reuseLabelPicture(label *labelTexture, scale float32, viewport int) bool { + skip, width, shown := label.window(scale, viewport) if !shown { return false } diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index 64e71ef74..8c499d7ac 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -585,7 +585,7 @@ func (renderer *renderer) presentWithSync(width, height int, scale float32, sync func (renderer *renderer) draw(width, height int, scale float32) error { // A page that appeared has many labels to draw; draw their pixels in one // Direct2D session before any of them is composited. - if err := renderer.prepareLabels(scale); err != nil { + if err := renderer.prepareLabels(scale, width); err != nil { return err } clear := [4]float32{float32(renderer.color.Red), float32(renderer.color.Green), float32(renderer.color.Blue), float32(renderer.color.Alpha)} @@ -649,14 +649,13 @@ func (renderer *renderer) draw(width, height int, scale float32) error { label.dropTexture() continue } - skip, windowWidth, shown := label.window(scale) + skip, windowWidth, shown := label.window(scale, width) if !shown { label.close() continue } - if label.view == 0 || label.stale || label.scale != scale || label.skip != skip || skip > 0 && label.width != windowWidth || renderer.pictureChanged(label, scale, skip, windowWidth) || - len(label.label.Bitmap) > 0 && platform.BitmapTextureStale(label.label, scale, label.width, label.height) { - if err := renderer.rasterize(label, scale); err != nil { + if renderer.needsRaster(label, scale, skip, windowWidth) { + if err := renderer.rasterize(label, scale, width); err != nil { return fmt.Errorf("rasterize label %d: %w", index, err) } } @@ -681,8 +680,9 @@ func (renderer *renderer) draw(width, height int, scale float32) error { continue } // A grid line has a color per run: its coverage is drawn once for each, cut to the - // columns of the run. + // columns of the run, which count from the texture's left edge. origin, _ := label.pixelOrigin(scale) + origin += label.skip for _, span := range label.spans { cut = scissor cut.Left, cut.Right = max(cut.Left, int32(origin+span.left)), min(cut.Right, int32(origin+span.right)) diff --git a/internal/platform/windows/renderer_windows_test.go b/internal/platform/windows/renderer_windows_test.go index 0c8995d9a..75bec8bed 100644 --- a/internal/platform/windows/renderer_windows_test.go +++ b/internal/platform/windows/renderer_windows_test.go @@ -417,12 +417,12 @@ func TestGridInkWidthStopsNearTheLastRun(t *testing.T) { t.Fatal("one more typed character changed the texture width, so every key would make a new texture") } label := labelTexture{label: platform.TextLabel{Value: "x", Mono: true, Runs: runs, CellWidth: cell, Width: 100 * cell, Height: 20, FontSize: 12}} - skip, width, ok := label.window(scale) + skip, width, ok := label.window(scale, 0) if !ok || skip != 0 || width != ink { t.Fatalf("window = %d, %d, %v, want 0, %d, true", skip, width, ok, ink) } label.label.Width = 4 - if _, width, _ = label.window(scale); width > 4*scale { + if _, width, _ = label.window(scale, 0); width > 4*scale { t.Fatalf("a narrow label got a texture %d wide, wider than itself", width) } } diff --git a/internal/platform/windows/text_batch_windows.go b/internal/platform/windows/text_batch_windows.go index 91f0c45f5..b9e986891 100644 --- a/internal/platform/windows/text_batch_windows.go +++ b/internal/platform/windows/text_batch_windows.go @@ -83,14 +83,14 @@ type labelBatch struct { // add queues a label. It reports false when the label's pixels would differ // from the per-label path, and full when the batch bitmap could not hold it; // the caller then flushes and tries the label again. -func (batch *labelBatch) add(label *labelTexture, scale float32, allowLCD bool) (added, full bool, err error) { - skip, width, ok := label.window(scale) +func (batch *labelBatch) add(label *labelTexture, scale float32, viewport int, allowLCD bool) (added, full bool, err error) { + skip, width, ok := label.window(scale, viewport) if !ok { return false, false, nil } height := int(math.Ceil(float64(label.label.Height * scale))) - if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 { - return false, false, nil // the per-label path reports the bounded-size error + if !platform.LabelTextureFits(width, height) { + return false, false, nil // the per-label path leaves it without a texture } size := label.label.FontSize * scale if size <= 0 || math.IsNaN(float64(size)) || math.IsInf(float64(size), 0) { @@ -228,7 +228,7 @@ func (batch *labelBatch) draw(renderer *renderer, items []labelBatchItem, pack b // prepareLabels rasterizes the proportional labels that changed this frame in // batches. Labels it leaves untouched are drawn by the per-label path in draw. -func (renderer *renderer) prepareLabels(scale float32) error { +func (renderer *renderer) prepareLabels(scale float32, viewport int) error { if renderer.noLabelBatch { return nil } @@ -248,17 +248,14 @@ func (renderer *renderer) prepareLabels(scale float32) error { len(label.label.Bitmap) > 0 || label.label.Mono || len(label.label.Runs) > 0 { continue } - skip, windowWidth, shown := label.window(scale) - if !shown { + skip, windowWidth, shown := label.window(scale, viewport) + if !shown || !renderer.needsRaster(label, scale, skip, windowWidth) { continue } - if !(label.view == 0 || label.stale || label.scale != scale || label.skip != skip || skip > 0 && label.width != windowWidth || renderer.pictureChanged(label, scale, skip, windowWidth)) { + if renderer.reuseLabelPicture(label, scale, viewport) { continue } - if renderer.reuseLabelPicture(label, scale) { - continue - } - _, full, err := batch.add(label, scale, allowLCD) + _, full, err := batch.add(label, scale, viewport, allowLCD) if err != nil { return err } @@ -267,7 +264,7 @@ func (renderer *renderer) prepareLabels(scale float32) error { if err := flush(); err != nil { return err } - if _, _, err := batch.add(label, scale, allowLCD); err != nil { + if _, _, err := batch.add(label, scale, viewport, allowLCD); err != nil { return err } } diff --git a/internal/platform/windows/text_editing_windows_test.go b/internal/platform/windows/text_editing_windows_test.go index febc20be2..373369090 100644 --- a/internal/platform/windows/text_editing_windows_test.go +++ b/internal/platform/windows/text_editing_windows_test.go @@ -191,11 +191,11 @@ func TestNativeTextOverlayRasterizesOnlyTheVisibleColumns(t *testing.T) { Value: "value", X: -1490, Y: 0, Width: 1700, Height: 24, FontSize: 16, Clipped: true, Clip: gfx.Rect{X: 10, Y: 0, Width: 200, Height: 24}, }} - if skip, width, ok := label.window(2); !ok || skip != 3000 || width != 400 { + if skip, width, ok := label.window(2, 0); !ok || skip != 3000 || width != 400 { t.Fatalf("window = %d, %d, %v; want 3000, 400, true", skip, width, ok) } label.label.X, label.label.Width = 10, 200 - if skip, width, ok := label.window(2); !ok || skip != 0 || width != 400 { + if skip, width, ok := label.window(2, 0); !ok || skip != 0 || width != 400 { t.Fatalf("unscrolled window = %d, %d, %v; want 0, 400, true", skip, width, ok) } } diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go index bb4e2f804..35153e68e 100644 --- a/internal/platform/windows/text_windows.go +++ b/internal/platform/windows/text_windows.go @@ -249,18 +249,37 @@ func (label *labelTexture) pixelOrigin(scale float32) (x, y int) { return platform.DevicePosition(l.X, l.OriginX, scale), platform.DevicePosition(l.Y, l.OriginY, scale) } -// window is the part of the label's full texture that its clip can show, in device -// pixels. A clipped line rasterizes only inside its clip, so a long scrolled -// single-line field costs the visible width, not the whole line. The text does not -// move: the skip is a whole number of device columns, so every glyph texel keeps the -// phase it has when the whole texture is drawn. Labels that are not clipped, and -// images and grid lines, keep their whole texture. -func (label *labelTexture) window(scale float32) (skip, width int, ok bool) { +// window is the part of the label's full texture that is rasterized, in device pixels: +// the columns from skip to skip+width. viewport is the width of the target in device +// pixels, or 0 when the caller has none. A clipped line rasterizes only inside its +// clip, so a long scrolled single-line field costs the visible width, not the whole +// line. A line of any kind wider than a texture holds, such as a log line of thousands +// of characters, rasterizes around the part of it the viewport and its clip show, and +// keeps its texture while a scroll stays inside it (platform.WideTextLabelWindow). The +// text does not move: the skip is a whole number of device columns, so every glyph +// texel keeps the phase it has when the whole texture is drawn. Other labels that are +// not clipped, and grid lines, keep their whole texture, and images always do. ok is +// false when nothing is drawn: none of the label can be seen, or it is too tall for +// any texture. +func (label *labelTexture) window(scale float32, viewport int) (skip, width int, ok bool) { full := int(math.Ceil(float64(label.label.Width * scale))) if label.label.Mono && len(label.label.Runs) > 0 { full = min(full, gridInkWidth(label.label.Runs, label.label.CellWidth, scale)) } - if !label.label.Clipped || label.label.Mono || len(label.label.Runs) > 0 || len(label.label.Bitmap) > 0 { + if len(label.label.Bitmap) > 0 { + return 0, full, full > 0 + } + // Every frame asks this of every label, so one a texture holds pays only this test. + if height := int(math.Ceil(float64(label.label.Height * scale))); !platform.LabelTextureFits(full, height) { + haveSkip, haveWidth := 0, 0 + if label.view != 0 && label.scale == scale { + haveSkip, haveWidth = label.skip, label.width + } + if skip, width, wide, ok := platform.WideTextLabelWindow(label.label, scale, full, height, viewport, haveSkip, haveWidth); wide { + return skip, width, ok + } + } + if !label.label.Clipped || label.label.Mono || len(label.label.Runs) > 0 { return 0, full, full > 0 } x, _ := label.pixelOrigin(scale) @@ -328,22 +347,38 @@ func sameRuns(left, right []gfx.TextRun) bool { } return true } -func (renderer *renderer) rasterize(label *labelTexture, scale float32) error { - if renderer.reuseLabelPicture(label, scale) { - return nil + +// needsRaster reports whether the label's texture must be drawn again before it is +// composited from the window skip to skip+width: it has none, what it shows or its +// scale changed, its window moved, the picture it shares no longer matches, or an +// image's texture no longer suits the size it is drawn at. +func (renderer *renderer) needsRaster(label *labelTexture, scale float32, skip, width int) bool { + if label.view == 0 || label.stale || label.scale != scale { + return true } - skip, width, ok := label.window(scale) - if !ok { - label.dropTexture() - label.scale, label.width, label.height, label.skip = scale, 0, 0, 0 + if len(label.label.Bitmap) > 0 { + return platform.BitmapTextureStale(label.label, scale, label.width, label.height) + } + return label.skip != skip || label.width != width || renderer.pictureChanged(label, scale, skip, width) +} + +// rasterize draws the label's texture for a target viewport device pixels wide (0 when +// unknown; see window). A label no texture can hold, an image larger than the device +// allows or a line too tall, is left without one and not drawn: one label the device +// cannot hold must not stop the window drawing the others. +func (renderer *renderer) rasterize(label *labelTexture, scale float32, viewport int) error { + if renderer.reuseLabelPicture(label, scale, viewport) { return nil } + skip, width, ok := label.window(scale, viewport) height := int(math.Ceil(float64(label.label.Height * scale))) - if len(label.label.Bitmap) > 0 { + if ok && len(label.label.Bitmap) > 0 { width, height = platform.BitmapTextureExtent(label.label, scale) } - if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 { - return fmt.Errorf("windows: label texture exceeds bounded size") + if !ok || !platform.LabelTextureFits(width, height) { + label.dropTexture() + label.scale = scale + return nil } var pixels []byte var err error diff --git a/internal/platform/windows/wide_label_windows_test.go b/internal/platform/windows/wide_label_windows_test.go new file mode 100644 index 000000000..8dd175038 --- /dev/null +++ b/internal/platform/windows/wide_label_windows_test.go @@ -0,0 +1,214 @@ +package windows + +import ( + "bytes" + "image" + "image/color" + "math" + "runtime" + "strings" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// wideValue is a log line of 4096 characters: at 8 logical pixels a cell and 150% it is +// 49152 device pixels wide, three times what a Direct3D 11 texture holds. +var wideValue = strings.Repeat("0123456789abcdef", 256) + +func wideMonoLine(value string, x float32, runs []gfx.TextRun) platform.TextLabel { + return platform.TextLabel{ + Value: value, X: x, Y: 4, Width: float32(len(value))*8 + 8, Height: 18, FontSize: 13, CellWidth: 8, + Mono: true, Runs: runs, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + Clipped: true, Clip: gfx.Rect{Width: 400, Height: 40}, + } +} + +func wholeRun(value string) []gfx.TextRun { + return []gfx.TextRun{{Bytes: int32(len(value)), Cells: int32(len(value)), Weight: 400, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}}} +} + +// A line wider than a texture holds gets a window of it around what the viewport and its +// clip show, of any kind, within the limit; one that cannot be seen, or that is too tall +// for any texture, gets none and is not drawn. +func TestWideLabelWindowFollowsTheViewport(t *testing.T) { + const scale, viewport = 1.5, 600 + for _, runs := range [][]gfx.TextRun{nil, wholeRun(wideValue)} { + label := labelTexture{label: wideMonoLine(wideValue, 0, runs)} + skip, width, ok := label.window(scale, viewport) + if !ok || skip != 0 || width != 1800 { + t.Errorf("runs %d, start of the line: window = %d, %d, %v; want 0, 1800, true", len(runs), skip, width, ok) + } + label.label.X = -20000 // 30000 device pixels scrolled off the left + skip, width, ok = label.window(scale, viewport) + if !ok || skip != 30000-600 || width != 1800 { + t.Errorf("runs %d, scrolled: window = %d, %d, %v; want 29400, 1800, true", len(runs), skip, width, ok) + } + label.label.X = -40000 + if _, _, ok = label.window(scale, viewport); ok { + t.Errorf("runs %d: a line scrolled out of the viewport has a window", len(runs)) + } + label.label.X, label.label.Clipped = 0, false + if skip, width, ok = label.window(scale, 0); !ok || width > platform.LabelTextureLimit || skip != 0 { + t.Errorf("runs %d, no viewport or clip: window = %d, %d, %v; want one texture from the start", len(runs), skip, width, ok) + } + label.label.Height = 12000 // 18000 device pixels + if _, _, ok = label.window(scale, viewport); ok { + t.Errorf("runs %d: a line too tall for any texture has a window", len(runs)) + } + } +} + +// A monospaced line wider than any texture the device makes, such as a long log line +// shown unwrapped, is rasterized from a window of it at its start and scrolled, as ClearType +// and in grayscale, without and with runs. The window's texture holds the pixels the texture +// of the start of the same line, which one texture holds, has for the columns both show: the +// window moves no glyph. +func TestWideMonoLineWindowHoldsThePixelsOfTheLine(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + rasterizer, err := newDirectRasterizer() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + defer rasterizer.close() + const scale, viewport = 1.5, 600 + raster := func(label platform.TextLabel, lcd bool) (pixels []byte, skip, width, height int) { + t.Helper() + texture := labelTexture{label: label} + skip, width, ok := texture.window(scale, viewport) + if !ok { + t.Fatalf("a line of %d characters at %v has no window", len(label.Value), label.X) + } + height = int(math.Ceil(float64(label.Height * scale))) + pixels, _, err := rasterizer.rasterize(label, scale, width, height, lcd, skip) + if err != nil { + t.Fatal(err) + } + return append([]byte(nil), pixels...), skip, width, height + } + for _, lcd := range []bool{true, false} { + for _, withRuns := range []bool{false, true} { + for _, scrolled := range []int{0, 1000} { // characters scrolled off the left + start := wideValue[:scrolled+300] + wideRuns, startRuns := []gfx.TextRun(nil), []gfx.TextRun(nil) + if withRuns { + wideRuns, startRuns = wholeRun(wideValue), wholeRun(start) + } + x := -8 * float32(scrolled) + name := map[bool]string{false: "grayscale", true: "ClearType"}[lcd] + map[bool]string{false: "", true: " with runs"}[withRuns] + wide, wideSkip, wideWidth, height := raster(wideMonoLine(wideValue, x, wideRuns), lcd) + want, wantSkip, wantWidth, _ := raster(wideMonoLine(start, x, startRuns), lcd) + if wideWidth <= 0 || wideWidth > platform.LabelTextureLimit { + t.Fatalf("%s, %d characters scrolled: the line's texture is %d wide", name, scrolled, wideWidth) + } + origin := platform.DevicePosition(x, 0, scale) + painted := 0 + for column := 0; column < viewport; column++ { // device columns of the target + got, at := column-origin-wideSkip, column-origin-wantSkip + if got < 0 || got >= wideWidth || at < 0 || at >= wantWidth { + t.Fatalf("%s, %d characters scrolled: column %d is outside a texture (%d of %d, %d of %d)", + name, scrolled, column, got, wideWidth, at, wantWidth) + } + for row := 0; row < height; row++ { + a, b := wide[(row*wideWidth+got)*4:][:4], want[(row*wantWidth+at)*4:][:4] + if !bytes.Equal(a, b) { + t.Fatalf("%s, %d characters scrolled: pixel %d,%d is %v, the start of the line's is %v", + name, scrolled, column, row, a, b) + } + if a[3] != 0 { + painted++ + } + } + } + if painted < 1000 { + t.Errorf("%s, %d characters scrolled: %d pixels of text", name, scrolled, painted) + } + } + } + } +} + +// Drawn on a target, as ClearType (an opaque one) and in grayscale (a transparent one), the +// wide line is where the start of the same line is, at its start and scrolled. Drawing it +// whole asked Direct3D 11 for a texture wider than it makes, and the error stopped the window +// drawing anything again. A channel may differ by one level: the window's texture starts off +// the target where the start's does not, so the sampler reaches the same texel centres along +// a different quad, and Direct3D's linear filter weighs texels to 8 bits, which can give a +// texel 1/256 of its neighbour. A glyph moved by a device pixel differs by far more. +func TestWideMonoLineIsDrawnFromAWindowOfIt(t *testing.T) { + for _, clearColor := range []platform.Color{black, {}} { + for _, withRuns := range []bool{false, true} { + for _, scrolled := range []int{0, 1000} { // characters scrolled off the left + start := wideValue[:scrolled+300] + wideRuns, startRuns := []gfx.TextRun(nil), []gfx.TextRun(nil) + if withRuns { + wideRuns, startRuns = wholeRun(wideValue), wholeRun(start) + } + x := -8 * float32(scrolled) + wide := renderOffscreen(t, clearColor, wideMonoLine(wideValue, x, wideRuns)) + want := renderOffscreen(t, clearColor, wideMonoLine(start, x, startRuns)) + name := map[bool]string{false: "grayscale", true: "ClearType"}[clearColor.Alpha >= 1] + + map[bool]string{false: "", true: " with runs"}[withRuns] + painted := 0 + for y := 0; y < 60; y++ { + for x := 0; x < 600; x++ { + if a, b := wide.RGBAAt(x, y), want.RGBAAt(x, y); !withinALevel(a, b) { + t.Fatalf("%s, %d characters scrolled: pixel %d,%d is %v, the start of the line's is %v", + name, scrolled, x, y, a, b) + } + if isPainted(wide, x, y) { + painted++ + } + } + } + if painted < 1000 { + t.Errorf("%s, %d characters scrolled: %d pixels of text painted", name, scrolled, painted) + } + } + } + } +} + +// withinALevel reports whether no channel of a and b differs by more than one level. +func withinALevel(a, b color.RGBA) bool { + near := func(p, q uint8) bool { return int(p)-int(q) <= 1 && int(q)-int(p) <= 1 } + return near(a.R, b.R) && near(a.G, b.G) && near(a.B, b.B) && near(a.A, b.A) +} + +// A label no texture holds, an image larger than the device allows or a line taller than +// a texture, is not drawn, and the labels beside it still are: one label the device cannot +// hold does not fail the frame. +func TestLabelNoTextureHoldsDoesNotFailTheFrame(t *testing.T) { + const imageWidth = platform.LabelTextureLimit + 16 + tall := platform.TextLabel{Value: "tall", X: 200, Y: 0, Width: 40, Height: platform.LabelTextureLimit + 1, FontSize: 13, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + wide := platform.TextLabel{X: 0, Y: 30, Width: imageWidth, Height: 2, + Bitmap: make([]byte, imageWidth*2*4), BitmapWidth: imageWidth, BitmapHeight: 2, BitmapStride: imageWidth * 4, BitmapID: 1, BitmapVersion: 1} + beside := platform.TextLabel{Value: "beside", X: 10, Y: 4, Width: 80, Height: 18, FontSize: 13, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + pixels := renderOffscreen(t, black, tall, wide, beside) + painted := 0 + for y := 0; y < 40; y++ { // the label beside, at 150% + for x := 0; x < 150; x++ { + if isPainted(pixels, x, y) { + painted++ + } + } + } + if painted == 0 { + t.Fatal("the label beside one no texture holds was not drawn") + } +} + +// renderOffscreen draws the labels on a 400 by 40 scene at 150%, cleared to clearColor. +func renderOffscreen(t *testing.T, clearColor platform.Color, labels ...platform.TextLabel) *image.RGBA { + t.Helper() + offscreen, err := NewOffscreen(400, 40, 1.5, clearColor) + if err != nil { + t.Skipf("no Direct3D 11 device: %v", err) + } + defer offscreen.Close() + return renderScene(t, offscreen, nil, labels) +}