Kevin Coughlin. Blog

The bytes were never the cost

In Salt Line I tried to speed up the layered overlay by sending palette indices instead of RGBA. The Galaxy A16 profile said the bytes were never the cost.

The change that shipped is saltline#201 (fe771e97). The listings are from the pull request head, d284578. NOTES §11 has the entry.

Trying palette indices in #200

The layered overlay is everything drawn over the sky and the ground. In play it uploaded as RGBA. saltline#200 sent one byte a pixel, an index into a 256-colour palette, coloured by a canvas_item shader.

On Salt Line the strip-pass timer fell, and the thread did not. The A16 timer was 1.338 ms to 1.252 ms, five runs of main and seven of the branch, about 0.1 ms a frame. NOTES §11 says to judge a strip change by whole-thread counters. Four alternating profile runs put the GL thread at 32.4% of a core (32.0–32.9) on main and 32.0% (31.5–32.4) on the branch. The ranges overlap. The whole app was 59.2% (58.7–59.9) against 59.7% (59.5–59.8). That is no measurable saving. It also needed the sprite art cut to 256 colours, a 256 KB lookup table and an extra edge layer. I closed #200 without merging. iOS and the Pixel were not checked.

The span covered the empty middle

A simpleperf profile of the A16's GL thread, profiling build, first updated phase, put 11% of it in memcmp and 6% in memset. memcmp is the strip comparison against the shadow copy. memset is the overlay's clear. Both only look inside each row's written columns.

Those columns were one span, from the leftmost write to the rightmost. The HUD draws at both edges of a row, so the span takes the empty middle with it. On a 20 s autopilot run the span covered 304k pixels a frame where 63k were painted.

Before #201, mark stored that span:

for cols in &mut self.cols[py0 as usize..py1 as usize] {
    *cols = if cols.1 <= cols.0 {
        (px0, px1)
    } else {
        (cols.0.min(px0), cols.1.max(px1))
    };
}

A mask of column tiles

Canvas::written is now raster::Written, a u64 mask per row: pub struct Written(u64). Bit t is a column tile. A tile is at least 8 columns wide, and at most 64 tiles fit on a row. On the A16's 1560-wide detailed frame the tile is 25 columns. Canvas::clear and Shadow::take_if_changed visit only the marked tiles, and adjacent tiles join into one run. The same autopilot run then walked 93k pixels a frame. Art, the upload path and the GPU side are untouched.

/// Width in display columns of a tile of a row `pw` wide: at most 64
/// tiles a row, and none narrower than 8 columns.
#[inline]
pub fn tile_w(pw: i32) -> i32 {
    ((pw + 63) / 64).max(8)
}

/// The tiles covering display columns `x0..x1` of a row `pw` wide.
#[inline]
pub fn span(pw: i32, x0: i32, x1: i32) -> Written {
    let (x0, x1) = (x0.max(0), x1.min(pw));
    if x1 <= x0 {
        return Written::NONE;
    }
    let tw = Self::tile_w(pw);
    let (t0, t1) = (x0 / tw, (x1 - 1) / tw);
    Written((u64::MAX >> (63 - t1)) & (u64::MAX << t0))
}

runs turns the mask back into column ranges, joining neighbours:

pub fn runs(self, pw: i32) -> impl Iterator<Item = (i32, i32)> {
    let tw = Self::tile_w(pw);
    let mut bits = self.0;
    std::iter::from_fn(move || {
        if bits == 0 {
            return None;
        }
        let t0 = bits.trailing_zeros();
        let t1 = t0 + (bits >> t0).trailing_ones();
        bits &= u64::MAX.checked_shl(t1).unwrap_or(0);
        Some((t0 as i32 * tw, (t1 as i32 * tw).min(pw)))
    })
}

mark unions the span's tiles into each row it covers:

let span = Written::span(self.pixel_w(), px0, px1);
for cols in &mut self.cols[py0 as usize..py1 as usize] {
    *cols = cols.union(span);
}

The clear walks dirty row bands, and inside a band only the runs:

pub fn clear(&mut self) {
    let pw = self.pixel_w();
    let stride = pw as usize * 4;
    let mut bits = self.dirty;
    while bits != 0 {
        let b = bits.trailing_zeros() as i32;
        bits &= bits - 1;
        for y in self.band_start(b) as usize..self.band_start(b + 1) as usize {
            for (x0, x1) in std::mem::take(&mut self.cols[y]).runs(pw) {
                self.px[y * stride + x0 as usize * 4..y * stride + x1 as usize * 4].fill(0);
            }
        }
    }
    self.dirty = 0;
}

The strip comparison does the same with the union of what the frame says it wrote and what the shadow still holds. Outside that union both sides are transparent black, so they are not read:

let spans = |y: i32, cols: Written| {
    cols.runs(w).map(move |(x0, x1)| {
        y as usize * stride + x0 as usize * 4..y as usize * stride + x1 as usize * 4
    })
};
let changed = (y0..y1).any(|y| {
    spans(y, written(y).union(self.cols[y as usize]))
        .any(|r| frame[r.clone()] != self.bytes[r])
});
for y in y0..y1 {
    let now = written(y);
    if changed {
        // Outside the union both rows are transparent black, so
        // copying it makes the rows equal.
        for r in spans(y, now.union(self.cols[y as usize])) {
            self.bytes[r.clone()].copy_from_slice(&frame[r]);
        }
    }
    // Equal or now copied, the row held is the frame's, which
    // `written` bounds.
    self.cols[y as usize] = now;
}

What the A16 measured

Profiling builds, four alternating runs per build. Both APKs used the same pinned engine template (godot-templates-4.7.2-96290a6ebc101c9c) and rustc 1.99.0. The baseline's main differs from this pull request's base only in CI and tools files.

main#201
GL thread instructions / frame3.45M (3.38–3.47)3.13M (3.10–3.15)
GL thread cycles / frame3.15M2.87M
Strip pass1.304 ms (1.28–1.35)1.126 ms (1.12–1.13)
process, updated frames2.322 ms (2.29–2.40)2.163 ms (2.15–2.17)
process, frozen control1.144 ms (1.13–1.16)1.132 ms (1.09–1.19)

Instructions and cycles are simpleperf on the GL thread, updated phase. NOTES §11 says the instruction count is the measure for a strip change. It falls 9%, and the ranges do not overlap. The frozen control is flat.

In the profile, memcmp drops from 11% of the thread to 7%, about half of the instructions saved. The rest is not attributed, likely the shadow's smaller copies. The clear's memset barely moves, which looks bound by memory traffic rather than by bytes or by how many times it is called.

The profiling GPU check passed all three scenes on the A16. The layered-vs-flat tests passed, 788 lib tests. New tests cover Written: joined runs, row ends, clipping, and widths up to 9999 fitting in 64 tiles. clear_and_touched_agree_with_the_pixels and comparing_written_columns_is_comparing_everything now exercise multi-tile masks. A review of the branch found no bugs: every write path marks its range, and the bit math and the shadow logic check out. The doc notes from that review are 40ad4f5.

These numbers are the Galaxy A16. #201 does not report another phone.

What I would repeat

Strips that stay put

saltline#202 (0aecc490) is the follow-up that keeps a strip whose pixels did not change. A 20 s autopilot run at a phone's size (1600×720 detailed buffer, 90 fps) had 93% of the overlay pixels it cleared, drew and compared in strips that came out unchanged, and 38% of frames changed no strip at all.

On the A16, against main at #201, that pull request's runs put process on updated frames at 2.213 ms (2.18–2.24) to 1.684 ms (1.66–1.73), and the GL thread at 31.6% of a core (30.7–32.5) to 28.6% (27.8–29.2). Those numbers were taken before two small refinements on the branch: rows folded per strip, and a lost probe writes nothing. iOS and the Pixel were not checked.

saltline#203 merged on December 2. A landing shake and an outline flash were still redrawing strips whose pixels did not change. It is not measured on a device.