Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(glyphgrid): color-keyed atlas with reset-on-full and mip gutters

enesf8c855b3128d
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index 25a048327..17ac790f8 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -688,11 +688,13 @@ function glyphDebugOn(): boolean {
function glyphDebugTap(): ((info: GlyphSlotAllocation) => void) | undefined {
if (!glyphDebugOn()) return undefined
- return ({ slot, code, bold, italic, x, y }): void => {
+ return ({ slot, code, bold, italic, x, y, fg, bg }): void => {
console.warn(
`[glyphgrid] slot ${slot} code 0x${code.toString(16)} ${JSON.stringify(
String.fromCodePoint(code)
- )}${bold ? ' bold' : ''}${italic ? ' italic' : ''} at ${x},${y}`
+ )}${bold ? ' bold' : ''}${italic ? ' italic' : ''} at ${x},${y} fg=${fg.toString(
+ 16
+ )} bg=${bg.toString(16)}`
)
}
}
diff --git a/src/renderer/glyphgrid/atlas.test.ts b/src/renderer/glyphgrid/atlas.test.ts
index 810c6b056..c2ab85d08 100644
--- a/src/renderer/glyphgrid/atlas.test.ts
+++ b/src/renderer/glyphgrid/atlas.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from 'vitest'
-import { GlyphAtlas, type GlyphRasterizer, type GlyphSlotAllocation } from './atlas'
+import { GUTTER_PX, GlyphAtlas, type GlyphRasterizer, type GlyphSlotAllocation } from './atlas'
+
+/** Colors reach the atlas as opaque packed lanes — it never decodes them, so small distinct
+ * numbers keep the recorded call strings readable. */
+const FG = 11
+const BG = 22
function fakeRasterizer(cellW = 10, cellH = 20): GlyphRasterizer & { calls: string[] } {
const calls: string[] = []
@@ -8,68 +13,118 @@ function fakeRasterizer(cellW = 10, cellH = 20): GlyphRasterizer & { calls: stri
cellH,
calls,
source: null,
- draw(code, bold, italic, x, y) {
- calls.push(`${code}|${bold ? 'b' : ''}${italic ? 'i' : ''}@${x},${y}`)
+ draw(code, bold, italic, x, y, fg, bg) {
+ calls.push(`${code}|${bold ? 'b' : ''}${italic ? 'i' : ''}|${fg}|${bg}@${x},${y}`)
+ },
+ // Logged into the SAME array as the draws, so "the page was blanked BEFORE the triggering
+ // glyph was drawn into it" is one ordering assertion rather than two independent counters.
+ clearPage() {
+ calls.push('CLEAR')
}
}
}
+/** The layout the tests below are written against, restated independently of the atlas so a change
+ * to `strideX`/`cellXY` has to be re-argued here rather than silently re-derived from itself. */
+const pitch = (cell: number): number => Math.max(1, Math.ceil(cell)) + 2 * GUTTER_PX
+
describe('GlyphAtlas', () => {
it('slot 0 is blank and never rasterized; first real glyph gets slot 1', () => {
const r = fakeRasterizer()
const atlas = new GlyphAtlas(r, 100)
- expect(atlas.glyphFor(0x20, false, false)).toBe(0) // space = blank slot, no draw
+ expect(atlas.glyphFor(0x20, false, false, FG, BG)).toBe(0) // space = blank slot, no draw
expect(r.calls).toEqual([])
- expect(atlas.glyphFor(0x41, false, false)).toBe(1) // 'A'
+ expect(atlas.glyphFor(0x41, false, false, FG, BG)).toBe(1) // 'A'
expect(r.calls).toHaveLength(1)
})
it('same key is cached (one rasterization, stable slot); styles are distinct keys', () => {
const r = fakeRasterizer()
const atlas = new GlyphAtlas(r, 100)
- const a = atlas.glyphFor(0x41, false, false)
- expect(atlas.glyphFor(0x41, false, false)).toBe(a)
- expect(atlas.glyphFor(0x41, true, false)).not.toBe(a)
+ const a = atlas.glyphFor(0x41, false, false, FG, BG)
+ expect(atlas.glyphFor(0x41, false, false, FG, BG)).toBe(a)
+ expect(atlas.glyphFor(0x41, true, false, FG, BG)).not.toBe(a)
expect(r.calls).toHaveLength(2)
})
+ // The whole point of Phase 1c: the atlas holds CoreText's COLORED output, so the colors are part
+ // of the key. A monochrome atlas keyed `code|style` would hand the second cell below the first
+ // cell's pixels — red text painted in the theme's grey.
+ describe('color keys (the atlas stores real pixels, not coverage)', () => {
+ it('the same glyph in a different foreground is a different slot', () => {
+ const r = fakeRasterizer()
+ const atlas = new GlyphAtlas(r, 100)
+ const a = atlas.glyphFor(0x41, false, false, FG, BG)
+ const b = atlas.glyphFor(0x41, false, false, FG + 1, BG)
+ expect(b).not.toBe(a)
+ expect(r.calls).toEqual([`65||${FG}|${BG}@16,2`, `65||${FG + 1}|${BG}@30,2`])
+ })
+
+ it('the same glyph on a different background is a different slot', () => {
+ const atlas = new GlyphAtlas(fakeRasterizer(), 100)
+ const a = atlas.glyphFor(0x41, false, false, FG, BG)
+ expect(atlas.glyphFor(0x41, false, false, FG, BG + 1)).not.toBe(a)
+ })
+
+ it('every lane of the key participates — no two of the five collide', () => {
+ const atlas = new GlyphAtlas(fakeRasterizer(), 100)
+ const slots = [
+ atlas.glyphFor(0x41, false, false, FG, BG),
+ atlas.glyphFor(0x42, false, false, FG, BG), // code
+ atlas.glyphFor(0x41, true, false, FG, BG), // bold
+ atlas.glyphFor(0x41, false, true, FG, BG), // italic
+ atlas.glyphFor(0x41, false, false, FG + 1, BG), // fg
+ atlas.glyphFor(0x41, false, false, FG, BG + 1) // bg
+ ]
+ expect(new Set(slots).size).toBe(slots.length)
+ })
+
+ it('the colors ride into the rasterizer untouched (it, not the shader, paints them)', () => {
+ const r = fakeRasterizer()
+ const atlas = new GlyphAtlas(r, 100)
+ atlas.glyphFor(0x41, false, false, 0xff112233, 0xff445566)
+ expect(r.calls).toEqual([`65||${0xff112233}|${0xff445566}@16,2`])
+ })
+ })
+
it('lays slots out row-major within the page and reports correct uv rects', () => {
- const r = fakeRasterizer(10, 20) // 100px page → 10 cols × 5 rows
+ const r = fakeRasterizer(10, 20) // pitch 14 × 24 → 7 cols × 4 rows in a 100px page
const atlas = new GlyphAtlas(r, 100)
- for (let i = 0; i < 11; i++) atlas.glyphFor(0x30 + i, false, false) // '0'..':' fills into row 2
- // The i-th glyph lands in slot i+1 (slot 0 is blank), so calls[9] is '9' (0x39) in slot 10.
- // slot 10 = row 1, col 0 → x=0, y=20; slot 11 = row 1, col 1 → x=10, y=20.
- expect(r.calls[8]).toBe(`${0x38}|@90,0`) // slot 9 = last cell of row 0
- expect(r.calls[9]).toBe(`${0x39}|@0,20`)
- expect(r.calls[10]).toBe(`${0x3a}|@10,20`)
- const rect = atlas.slotRect(1)
- expect(rect).toEqual({ u0: 0.1, v0: 0, u1: 0.2, v1: 0.2 })
+ for (let i = 0; i < 9; i++) atlas.glyphFor(0x30 + i, false, false, FG, BG) // '0'..'8'
+ // The i-th glyph lands in slot i+1 (slot 0 is blank), so calls[5] is slot 6 — the last cell of
+ // row 0 — and calls[6] is slot 7, the first of row 1. Every origin is the INK origin: the pitch
+ // cell's corner plus the gutter on both axes.
+ expect(r.calls[5]).toBe(`${0x35}||${FG}|${BG}@86,2`) // slot 6: (6*14)+2, 0+2
+ expect(r.calls[6]).toBe(`${0x36}||${FG}|${BG}@2,26`) // slot 7: row 1 → 0+2, 24+2
+ expect(r.calls[7]).toBe(`${0x37}||${FG}|${BG}@16,26`)
+ expect(atlas.slotRect(1)).toEqual({ u0: 16 / 100, v0: 2 / 100, u1: 26 / 100, v1: 22 / 100 })
})
it('slotRect is correct past row 0', () => {
- const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 100) // 10 cols × 5 rows
- expect(atlas.slotRect(10)).toEqual({ u0: 0, v0: 0.2, u1: 0.1, v1: 0.4 })
+ const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 100) // 7 cols × 4 rows
+ expect(atlas.slotRect(7)).toEqual({ u0: 2 / 100, v0: 26 / 100, u1: 12 / 100, v1: 46 / 100 })
})
- // What this pins, exactly: `slotRect` against a HAND-TRANSCRIBED copy of gl-webgl2's vertex
- // shader formula — cols = floor(sizePx/strideX), cellUv = [cellW/sizePx, cellH/sizePx],
- // strideUv = [strideX/sizePx, strideY/sizePx], slotOrigin = (slot % cols, floor(slot / cols)) *
- // strideUv (see `uAtlasCols` / `uAtlasCell` / `uAtlasStride` in VERT). So it catches a change to
- // the CPU side (atlas padding, page metrics, slot ordering) — and nothing else.
+ // What this pins, exactly: `slotRect` against a HAND-TRANSCRIBED copy of the uv derivation
+ // gl-webgl2's vertex shader must perform — cols = floor(sizePx/strideX), cellUv =
+ // [cellW/sizePx, cellH/sizePx], strideUv = [strideX/sizePx, strideY/sizePx], gutterUv =
+ // GUTTER_PX/sizePx, slotOrigin = (slot % cols, floor(slot / cols)) * strideUv + gutterUv. So it
+ // catches a change to the CPU side (atlas gutter, page metrics, slot ordering) — and nothing else.
//
// Every number on the shader side is computed HERE, from the cell the rasterizer was built with
// — never read back off the atlas. Deriving `cols` from `atlas.strideX` would make the test
// agree with whatever the atlas decided, including conflating the pitch with the extent.
//
// It is NOT a tie to the live GLSL: the shader side below is this test's own copy, so editing
- // the real shader leaves this green, and `slotRect` currently has no production caller at all
- // (the shader derives its uvs itself from the uniforms). The actual tie — a visual pass, or
- // pinning the GLSL against a generated line — is owed to Phase 1b.
+ // the real shader leaves this green. AND, DURING PHASE 1c, THE LIVE SHADER DOES NOT YET MATCH IT:
+ // the gutter term is Task 3's (`uploadAtlas` has to carry GUTTER_PX and VERT has to add it to
+ // `slotOrigin`). This file is the CPU-side truth T3 aligns to; until it lands, the shader samples
+ // a gutter-sized offset off every glyph.
//
- // Run over an integer cell AND a fractional one: an integer cell has stride === extent, so it
- // alone cannot tell a pitch/extent conflation from a correct derivation.
+ // Run over an integer cell AND a fractional one: an integer cell has stride === extent + 2*gutter
+ // on both axes, so it alone cannot tell a pitch/extent conflation from a correct derivation.
it.each([
- { label: 'integer cell (stride === extent)', cellW: 10, cellH: 20, sizePx: 100 },
+ { label: 'integer cell (extent is a whole texel)', cellW: 10, cellH: 20, sizePx: 100 },
{ label: 'fractional device cell (13px font at dpr 2)', cellW: 15.66, cellH: 31.2, sizePx: 512 }
])('slotRect agrees with the shader uv derivation for every interesting slot — $label', ({
cellW,
@@ -77,16 +132,27 @@ describe('GlyphAtlas', () => {
sizePx
}) => {
const atlas = new GlyphAtlas(fakeRasterizer(cellW, cellH), sizePx)
- const strideX = Math.ceil(cellW)
- const strideY = Math.ceil(cellH)
+ const strideX = Math.ceil(cellW) + 2 * GUTTER_PX
+ const strideY = Math.ceil(cellH) + 2 * GUTTER_PX
const cols = Math.floor(sizePx / strideX)
const rows = Math.floor(sizePx / strideY)
const cellUv = [cellW / sizePx, cellH / sizePx]
const strideUv = [strideX / sizePx, strideY / sizePx]
+ const gutterUv = GUTTER_PX / sizePx
for (const slot of [0, 1, cols - 1, cols, cols + 1, cols * rows - 1]) {
- const u0 = (slot % cols) * strideUv[0]
- const v0 = Math.floor(slot / cols) * strideUv[1]
- expect(atlas.slotRect(slot)).toEqual({ u0, v0, u1: u0 + cellUv[0], v1: v0 + cellUv[1] })
+ const u0 = (slot % cols) * strideUv[0] + gutterUv
+ const v0 = Math.floor(slot / cols) * strideUv[1] + gutterUv
+ const got = atlas.slotRect(slot)
+ // Compared to 12 decimals rather than exactly: the two sides are algebraically identical but
+ // ASSOCIATE differently — the atlas divides `(inkX + cellW)` by the page once, the shader
+ // adds `cellW/sizePx` to an already-divided origin — so they can disagree in the last double
+ // ulp (~1e-17 here). 1e-12 of a unit uv is ~1e-9 of a texel; nothing samples differently for
+ // it, and the GPU truncates all of it to fp32 anyway. A conflated pitch/extent, the defect
+ // this test exists for, is off by a whole texel or more.
+ expect(got.u0).toBeCloseTo(u0, 12)
+ expect(got.v0).toBeCloseTo(v0, 12)
+ expect(got.u1).toBeCloseTo(u0 + cellUv[0], 12)
+ expect(got.v1).toBeCloseTo(v0 + cellUv[1], 12)
}
})
@@ -94,74 +160,284 @@ describe('GlyphAtlas', () => {
// metrics, rounded up to whole texels, while the grid draws each cell at xterm's exact device
// cell — so every glyph was stretched over a quad a couple of percent smaller than its bitmap
// and resampled ("rougher than the DOM renderer"). Now the sampled EXTENT is the exact
- // (fractional) cell and only the slot PITCH rounds.
+ // (fractional) cell and only the slot PITCH rounds — and the pitch additionally carries the
+ // gutter the mip chain needs.
describe('fractional device cells (xterm reports charWidth * dpr, which is not an integer)', () => {
it('keeps the sampled extent exact and rounds only the slot pitch', () => {
const atlas = new GlyphAtlas(fakeRasterizer(15.66, 31), 2048)
expect(atlas.cellW).toBe(15.66) // extent: unrounded, so texel:pixel is 1:1 at zoom 1
- expect(atlas.strideX).toBe(16) // pitch: whole texels
+ expect(atlas.strideX).toBe(16 + 2 * GUTTER_PX) // pitch: whole texels + both gutters
expect(atlas.cellH).toBe(31)
- expect(atlas.strideY).toBe(31)
+ expect(atlas.strideY).toBe(31 + 2 * GUTTER_PX)
const rect = atlas.slotRect(1)
expect(rect.u1 - rect.u0).toBeCloseTo(15.66 / 2048, 12)
- expect(rect.u0).toBeCloseTo(16 / 2048, 12) // …starting on a texel boundary
+ expect(rect.u0).toBeCloseTo((20 + GUTTER_PX) / 2048, 12) // …starting on a texel boundary
})
it('lays slots out on the pitch, so no two glyphs share a boundary texel', () => {
const r = fakeRasterizer(15.66, 31)
const atlas = new GlyphAtlas(r, 2048)
- atlas.glyphFor(0x41, false, false) // slot 1
- atlas.glyphFor(0x42, false, false) // slot 2
- expect(r.calls[0]).toBe(`${0x41}|@16,0`)
- expect(r.calls[1]).toBe(`${0x42}|@32,0`)
+ atlas.glyphFor(0x41, false, false, FG, BG) // slot 1
+ atlas.glyphFor(0x42, false, false, FG, BG) // slot 2
+ expect(r.calls[0]).toBe(`${0x41}||${FG}|${BG}@22,2`) // 1*20 + gutter
+ expect(r.calls[1]).toBe(`${0x42}||${FG}|${BG}@42,2`) // 2*20 + gutter
})
- it('counts capacity in whole pitches — the gutter is not usable area', () => {
- // floor(100/16) = 6 cols, floor(100/31) = 3 rows.
- expect(new GlyphAtlas(fakeRasterizer(15.66, 31), 100).capacity).toBe(18)
+ it('counts capacity in whole pitches — the gutters are not usable area', () => {
+ // pitch 20 × 35 → floor(100/20) = 5 cols, floor(100/35) = 2 rows.
+ expect(new GlyphAtlas(fakeRasterizer(15.66, 31), 100).capacity).toBe(10)
})
it('a sub-texel cell still yields a finite pitch rather than an infinite capacity', () => {
const atlas = new GlyphAtlas(fakeRasterizer(0.4, 0.4), 100)
- expect(atlas.strideX).toBe(1)
- expect(atlas.capacity).toBe(10000)
+ expect(atlas.strideX).toBe(1 + 2 * GUTTER_PX)
+ expect(atlas.capacity).toBe(400) // floor(100/5)^2
+ })
+ })
+
+ // The gutter is what makes the mip chain usable: a level-n texel averages a 2^n-wide block of
+ // level-0 texels, so ink that sits flush against a slot boundary is averaged into the NEIGHBOUR's
+ // minified texels. These tests pin the arithmetic that keeps every slot's ink 2*GUTTER_PX away
+ // from every other slot's ink.
+ describe('mip gutters', () => {
+ it('exports the gutter the rasterizer and the shader both have to agree with', () => {
+ expect(GUTTER_PX).toBe(2)
+ })
+
+ it('the pitch is the rounded-up cell plus a gutter on BOTH sides of each axis', () => {
+ for (const [cellW, cellH] of [
+ [10, 20],
+ [15.66, 31.2],
+ [0.4, 0.4]
+ ]) {
+ const atlas = new GlyphAtlas(fakeRasterizer(cellW, cellH), 2048)
+ expect(atlas.strideX).toBe(pitch(cellW))
+ expect(atlas.strideY).toBe(pitch(cellH))
+ }
+ })
+
+ it('the ink origin sits one gutter inside its pitch cell, on both axes', () => {
+ const r = fakeRasterizer(10, 20)
+ const atlas = new GlyphAtlas(r, 100) // 7 cols
+ for (let i = 0; i < 8; i++) atlas.glyphFor(0x41 + i, false, false, FG, BG)
+ for (let slot = 1; slot <= 8; slot++) {
+ const col = slot % 7
+ const row = Math.floor(slot / 7)
+ expect(r.calls[slot - 1]).toContain(
+ `@${col * pitch(10) + GUTTER_PX},${row * pitch(20) + GUTTER_PX}`
+ )
+ }
+ })
+
+ it('the uv rect follows the ink, not the pitch cell', () => {
+ const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 100)
+ const rect = atlas.slotRect(1)
+ expect(rect.u0 * 100).toBeCloseTo(pitch(10) + GUTTER_PX, 9)
+ expect(rect.v0 * 100).toBeCloseTo(GUTTER_PX, 9)
+ // The extent is still exactly the cell — the gutter moved the origin, it did not grow the
+ // sampled area (which would sample the neighbour's backdrop into every glyph at zoom 1).
+ expect((rect.u1 - rect.u0) * 100).toBeCloseTo(10, 9)
+ expect((rect.v1 - rect.v0) * 100).toBeCloseTo(20, 9)
+ })
+
+ // Slot 0 is isolated by the SAME rule as every other slot — it is not a special case in the
+ // layout, it is simply the slot nobody ever draws into. If its mip neighbourhood could reach
+ // slot 1's ink, every space on a zoomed-out canvas would grow a ghost.
+ it('separates every slot pair — slot 0 included — by two full gutters of ink-free page', () => {
+ for (const [cellW, cellH, sizePx] of [
+ [10, 20, 100],
+ [15.66, 31.2, 512]
+ ]) {
+ const atlas = new GlyphAtlas(fakeRasterizer(cellW, cellH), sizePx)
+ const inkRect = (slot: number): { x0: number; y0: number; x1: number; y1: number } => {
+ const r = atlas.slotRect(slot)
+ return {
+ x0: r.u0 * sizePx,
+ y0: r.v0 * sizePx,
+ x1: r.u1 * sizePx,
+ y1: r.v1 * sizePx
+ }
+ }
+ const cols = Math.floor(sizePx / atlas.strideX)
+ for (const slot of [0, 1, 2, cols, cols + 1]) {
+ for (const other of [0, 1, 2, cols, cols + 1]) {
+ if (slot === other) continue
+ const a = inkRect(slot)
+ const b = inkRect(other)
+ // Separated on at least one axis by 2*GUTTER_PX — two slots in the same row share rows
+ // of texels, so the guarantee is per-axis, not a euclidean distance.
+ const gapX = Math.max(b.x0 - a.x1, a.x0 - b.x1)
+ const gapY = Math.max(b.y0 - a.y1, a.y0 - b.y1)
+ expect(Math.max(gapX, gapY)).toBeGreaterThanOrEqual(2 * GUTTER_PX - 1e-9)
+ }
+ }
+ }
+ })
+
+ it('keeps the gutter of the LAST slot inside the page', () => {
+ const sizePx = 512
+ const atlas = new GlyphAtlas(fakeRasterizer(15.66, 31.2), sizePx)
+ const last = atlas.capacity - 1
+ const rect = atlas.slotRect(last)
+ expect(rect.u1 * sizePx + GUTTER_PX).toBeLessThanOrEqual(sizePx)
+ expect(rect.v1 * sizePx + GUTTER_PX).toBeLessThanOrEqual(sizePx)
})
})
it('a degenerate page (sizePx < cellW) yields blank slots and a zero rect, never NaN', () => {
const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 5)
expect(atlas.capacity).toBe(0)
- expect(atlas.glyphFor(0x41, false, false)).toBe(0)
+ expect(atlas.glyphFor(0x41, false, false, FG, BG)).toBe(0)
expect(atlas.slotRect(0)).toEqual({ u0: 0, v0: 0, u1: 0, v1: 0 })
})
it('sets dirty on new glyphs and clears on demand', () => {
const atlas = new GlyphAtlas(fakeRasterizer(), 100)
expect(atlas.dirty).toBe(false)
- atlas.glyphFor(0x41, false, false)
+ atlas.glyphFor(0x41, false, false, FG, BG)
expect(atlas.dirty).toBe(true)
atlas.clearDirty()
expect(atlas.dirty).toBe(false)
})
- it('a full page falls back to the blank slot instead of overflowing', () => {
- const r = fakeRasterizer(10, 20)
- const atlas = new GlyphAtlas(r, 20) // 2 cols × 1 row = capacity 2 (slot 0 blank + 1 real)
- expect(atlas.capacity).toBe(2)
- expect(atlas.glyphFor(0x41, false, false)).toBe(1)
- expect(atlas.glyphFor(0x42, false, false)).toBe(0) // full → blank, never throws
+ // Reset-on-full is xterm's `clearTextureAtlas` model: colored keys grow with the palette, so a
+ // page WILL fill; clearing it wholesale (and having consumers repack every row) is what avoids
+ // eviction's dangling-slot problem — no live lane can ever point at a slot someone else reused,
+ // because after a reset no lane points anywhere until it is rewritten.
+ describe('reset on a full page', () => {
+ /** A page with room for exactly slot 0 + one real slot: pitch 14 × 24 → 2 cols × 1 row. */
+ const fullAfterOne = (): { r: ReturnType<typeof fakeRasterizer>; atlas: GlyphAtlas } => {
+ const r = fakeRasterizer(10, 20)
+ return { r, atlas: new GlyphAtlas(r, 28) }
+ }
+
+ it('does not fire before the page is actually full', () => {
+ const { atlas } = fullAfterOne()
+ expect(atlas.capacity).toBe(2)
+ expect(atlas.glyphFor(0x41, false, false, FG, BG)).toBe(1)
+ expect(atlas.resetCount).toBe(0)
+ })
+
+ it('a cache hit on a full page never resets', () => {
+ const { atlas } = fullAfterOne()
+ atlas.glyphFor(0x41, false, false, FG, BG)
+ expect(atlas.glyphFor(0x41, false, false, FG, BG)).toBe(1)
+ expect(atlas.resetCount).toBe(0)
+ })
+
+ it('fires at capacity, blanks the page, and lands the triggering key in the fresh page', () => {
+ const { r, atlas } = fullAfterOne()
+ atlas.glyphFor(0x41, false, false, FG, BG)
+ r.calls.length = 0
+ expect(atlas.glyphFor(0x42, false, false, FG, BG)).toBe(1) // fresh page → slot 1 again
+ expect(atlas.resetCount).toBe(1)
+ // Ordering is the contract: the pixels are blanked BEFORE the triggering glyph is drawn, or
+ // the clear would erase the glyph that caused it.
+ expect(r.calls).toEqual(['CLEAR', `${0x42}||${FG}|${BG}@16,2`])
+ expect(atlas.dirty).toBe(true)
+ })
+
+ it('forgets every key it held, so the old ones re-rasterize into the fresh page', () => {
+ const { r, atlas } = fullAfterOne()
+ atlas.glyphFor(0x41, false, false, FG, BG)
+ atlas.glyphFor(0x42, false, false, FG, BG) // reset; 'B' now owns slot 1
+ r.calls.length = 0
+ expect(atlas.glyphFor(0x41, false, false, FG, BG)).toBe(1) // another reset for 'A'
+ expect(atlas.resetCount).toBe(2)
+ expect(r.calls).toEqual(['CLEAR', `${0x41}||${FG}|${BG}@16,2`])
+ })
+
+ it('notifies subscribers AFTER the clear and BEFORE the triggering allocation', () => {
+ const { r, atlas } = fullAfterOne()
+ atlas.onReset(() => r.calls.push('ONRESET'))
+ atlas.glyphFor(0x41, false, false, FG, BG)
+ r.calls.length = 0
+ atlas.glyphFor(0x42, false, false, FG, BG)
+ expect(r.calls).toEqual(['CLEAR', 'ONRESET', `${0x42}||${FG}|${BG}@16,2`])
+ })
+
+ it('subscribers see EMPTY bookkeeping — a repack started there packs the fresh page', () => {
+ const { atlas } = fullAfterOne()
+ let seen = -1
+ atlas.onReset(() => {
+ // The key that filled the old page is gone: asking for it again allocates slot 1 of the
+ // fresh page rather than returning the stale slot it used to hold.
+ seen = atlas.glyphFor(0x41, false, false, FG, BG)
+ })
+ atlas.glyphFor(0x41, false, false, FG, BG) // slot 1
+ const triggering = atlas.glyphFor(0x42, false, false, FG, BG)
+ expect(seen).toBe(1) // subscriber repacked 'A' into the fresh page…
+ expect(triggering).toBe(0) // …which filled it again, so 'B' degrades to blank this frame
+ expect(atlas.resetCount).toBe(1) // and does NOT recurse into a second reset
+ })
+
+ it('every subscriber is called, and each one can be disposed independently', () => {
+ const { atlas } = fullAfterOne()
+ const hits: string[] = []
+ const a = atlas.onReset(() => hits.push('a'))
+ atlas.onReset(() => hits.push('b'))
+ atlas.glyphFor(0x41, false, false, FG, BG)
+ atlas.glyphFor(0x42, false, false, FG, BG)
+ expect(hits).toEqual(['a', 'b'])
+ a.dispose()
+ atlas.glyphFor(0x43, false, false, FG, BG)
+ expect(hits).toEqual(['a', 'b', 'b'])
+ })
+
+ it('a disposed subscription is idempotent and never resurrects', () => {
+ const { atlas } = fullAfterOne()
+ let hits = 0
+ const sub = atlas.onReset(() => hits++)
+ sub.dispose()
+ sub.dispose()
+ atlas.glyphFor(0x41, false, false, FG, BG)
+ atlas.glyphFor(0x42, false, false, FG, BG)
+ expect(hits).toBe(0)
+ })
+
+ it('a throwing subscriber costs its own notification, not the frame', () => {
+ const { r, atlas } = fullAfterOne()
+ const hits: string[] = []
+ atlas.onReset(() => {
+ throw new Error('repack blew up')
+ })
+ atlas.onReset(() => hits.push('b'))
+ atlas.glyphFor(0x41, false, false, FG, BG)
+ r.calls.length = 0
+ expect(() => atlas.glyphFor(0x42, false, false, FG, BG)).not.toThrow()
+ expect(hits).toEqual(['b']) // the surviving subscriber still ran
+ expect(r.calls).toEqual(['CLEAR', `${0x42}||${FG}|${BG}@16,2`])
+ })
+
+ // A page that cannot hold a single real glyph must DEGRADE, not thrash: resetting an empty
+ // page on every request would clear + notify forever and never render anything.
+ it('never resets a page too small to hold one glyph', () => {
+ const r = fakeRasterizer(10, 20)
+ const atlas = new GlyphAtlas(r, 24) // 1 col × 1 row = capacity 1 (slot 0 only)
+ let hits = 0
+ atlas.onReset(() => hits++)
+ expect(atlas.capacity).toBe(1)
+ expect(atlas.glyphFor(0x41, false, false, FG, BG)).toBe(0)
+ expect(atlas.glyphFor(0x42, false, false, FG, BG)).toBe(0)
+ expect(atlas.resetCount).toBe(0)
+ expect(hits).toBe(0)
+ expect(r.calls).toEqual([])
+ })
})
+
describe('debug allocation tap (device instrumentation for the blank-glyph bug)', () => {
it('reports each NEW slot with the origin the ink was drawn at, and never on a cache hit', () => {
const seen: GlyphSlotAllocation[] = []
const atlas = new GlyphAtlas(fakeRasterizer(10, 20), 100, (i) => seen.push(i))
- atlas.glyphFor(0x78, false, false)
- atlas.glyphFor(0x78, false, false) // cache hit — must NOT re-report
- atlas.glyphFor(0x78, true, false) // a different style IS a different slot
- atlas.glyphFor(0x20, false, false) // the blank slot is never an allocation
+ atlas.glyphFor(0x78, false, false, FG, BG)
+ atlas.glyphFor(0x78, false, false, FG, BG) // cache hit — must NOT re-report
+ atlas.glyphFor(0x78, true, false, FG, BG) // a different style IS a different slot
+ atlas.glyphFor(0x78, false, false, FG + 1, BG) // …and so is a different colour
+ atlas.glyphFor(0x20, false, false, FG, BG) // the blank slot is never an allocation
expect(seen).toEqual([
- { slot: 1, code: 0x78, bold: false, italic: false, x: 10, y: 0 },
- { slot: 2, code: 0x78, bold: true, italic: false, x: 20, y: 0 }
+ { slot: 1, code: 0x78, bold: false, italic: false, x: 16, y: 2, fg: FG, bg: BG },
+ { slot: 2, code: 0x78, bold: true, italic: false, x: 30, y: 2, fg: FG, bg: BG },
+ { slot: 3, code: 0x78, bold: false, italic: false, x: 44, y: 2, fg: FG + 1, bg: BG }
])
})
@@ -170,9 +446,9 @@ describe('GlyphAtlas', () => {
const atlas = new GlyphAtlas(r, 100, () => {
throw new Error('debug tap blew up')
})
- expect(() => atlas.glyphFor(0x78, false, false)).not.toThrow()
- expect(atlas.glyphFor(0x78, false, false)).toBe(1) // still cached and usable
- expect(r.calls).toEqual(['120|@10,0']) // ...and rasterized exactly once
+ expect(() => atlas.glyphFor(0x78, false, false, FG, BG)).not.toThrow()
+ expect(atlas.glyphFor(0x78, false, false, FG, BG)).toBe(1) // still cached and usable
+ expect(r.calls).toEqual([`120||${FG}|${BG}@16,2`]) // ...and rasterized exactly once
expect(atlas.dirty).toBe(true)
})
})
diff --git a/src/renderer/glyphgrid/atlas.ts b/src/renderer/glyphgrid/atlas.ts
index 6e19b392b..55beee6c2 100644
--- a/src/renderer/glyphgrid/atlas.ts
+++ b/src/renderer/glyphgrid/atlas.ts
@@ -1,21 +1,68 @@
-/** Monochrome glyph atlas BOOKKEEPING. Rasterization is injected (GlyphRasterizer) so this
- * module is pure and unit-testable; the real rasterizer (raster.ts) draws white glyphs onto an
- * OffscreenCanvas that gl-webgl2.ts uploads as the atlas texture. Colors are per-cell instance
- * data tinted in the shader — that is what keeps the key space to code|bold|italic. */
+/** COLOR glyph atlas BOOKKEEPING. Rasterization is injected (GlyphRasterizer) so this module is
+ * pure and unit-testable; the real rasterizer (raster.ts) paints each slot's real background and
+ * then the glyph in its real foreground onto an OffscreenCanvas that gl-webgl2.ts uploads as the
+ * atlas texture.
+ *
+ * WHY COLORED, not monochrome-plus-a-tint. The old atlas stored white-on-black COVERAGE keyed
+ * `code|bold italic` and the fragment shader mixed fg/bg by it — one slot per glyph shape, at the
+ * cost of performing the anti-aliasing blend ourselves. That blend is exactly what could never be
+ * made to match: CoreText's rasterization of light-on-dark text carries its own gamma and
+ * smoothing compensation, so re-mixing its coverage in the shader was a tuning knob with no
+ * correct setting (six device rounds of BLEND_GAMMA say so). xterm's own TextureAtlas asks the
+ * platform to draw the glyph in its REAL colours over its REAL background and blits the result
+ * 1:1; keying on the colours is the price of that, and it is the price this file now pays.
+ *
+ * The key space therefore grows with the palette, which is what `reset()` below is for. */
export interface GlyphRasterizer {
cellW: number
cellH: number
- draw(code: number, bold: boolean, italic: boolean, x: number, y: number): void
+ /** Paint one slot. `x, y` is the INK origin in page pixels (already one gutter inside the pitch
+ * cell — see GUTTER_PX); `fg`/`bg` are packColor lanes, the FINAL per-cell colours with
+ * selection/cursor already applied by the caller. */
+ draw(
+ code: number,
+ bold: boolean,
+ italic: boolean,
+ x: number,
+ y: number,
+ fg: number,
+ bg: number
+ ): void
+ /** Blank the whole page. Called by `GlyphAtlas.reset()` and by nothing else: the bookkeeping and
+ * the pixels have to be emptied in the same breath or a stale slot keeps its old ink. */
+ clearPage(): void
readonly source: TexImageSource | null
}
+/**
+ * The ink-free margin, in page texels, on EVERY side of a slot's cell rect. Exported because three
+ * modules have to agree on it: this file lays the page out with it, raster.ts fills it with the
+ * slot's own background colour, and gl-webgl2.ts offsets its uv derivation by it.
+ *
+ * WHY 2 — the derivation, since this number is what bounds the usable mip chain. A mip level-n
+ * texel is the average of an aligned 2^n × 2^n block of level-0 texels. Two slots' inks are
+ * separated by 2*GUTTER_PX = 4 texels of gutter (this slot's plus the neighbour's), so a level-n
+ * block can only contain ink from BOTH slots once it is wider than that separation, i.e. once
+ * 2^n > 4 → n >= 3. Levels 0, 1 and 2 therefore never mix a foreign glyph into this slot, which is
+ * why gl-webgl2 clamps TEXTURE_MAX_LOD to MAX_SAFE_LOD = 2.
+ *
+ * What the gutter does NOT promise, stated so nobody reads more into it: bilinear filtering WITHIN
+ * a level still reaches the adjacent texel, which at level 2 can be a pure-gutter texel holding a
+ * blend of this slot's background and the neighbour's. That is a soft edge between two BACKGROUND
+ * colours at heavy zoom-out — never a ghost glyph — and it is the residual the LOD clamp accepts.
+ * The promise is about INK, and it holds only while raster.ts keeps ink inside the cell rect: ink
+ * allowed to overhang into the gutter shortens the ink-to-ink separation and invalidates the
+ * derivation above.
+ */
+export const GUTTER_PX = 2
+
/** One slot allocation, reported to an optional debug tap. See `GlyphAtlas`'s constructor.
*
* This exists for ONE open device bug: a single letter (`ç` in round 5, lowercase `x` in round 7)
* renders BLANK while its neighbours are fine. Every headless-auditable path was audited and is
* clean — box-glyphs claims nothing below U+0300 and never returns an empty op list, the raster
- * re-blacks under the clip before it inks on BOTH branches, `cellXY` is the single copy of the
- * layout math and the shader recomputes it identically, `strideX = ceil(cellW) >= cellW` always
+ * re-paints under the clip before it inks on BOTH branches, `cellXY` is the single copy of the
+ * layout math and the shader recomputes it identically, `strideX >= cellW + 2*GUTTER_PX` always
* (the rasterizer's cell is captured at construction and never re-adopted), and the atlas's dirty
* flag is polled by the rAF driver every frame, so no wake-up can be missed. What is left needs a
* real font on a real device, which no test here can produce — so the next round collects
@@ -25,21 +72,33 @@ export interface GlyphSlotAllocation {
code: number
bold: boolean
italic: boolean
- /** Page-pixel origin the ink was drawn at — `cellXY(slot)`. */
+ /** Page-pixel INK origin the glyph was drawn at — `cellXY(slot)`. */
x: number
y: number
+ /** The packed colour lanes the slot was rasterized in — part of its key. */
+ fg: number
+ bg: number
+}
+
+/** What `onReset` hands back. A plain disposable rather than an unsubscribe function so the call
+ * sites read the same as every other subscription in the renderer. */
+export interface GlyphAtlasSubscription {
+ dispose(): void
}
export class GlyphAtlas {
private slots = new Map<string, number>()
/** Slot 0 is permanently blank and is never handed to the rasterizer: every space, every
* unknown code point and every cell of a not-yet-uploaded GPU buffer samples it. Its
- * BLANKNESS is a contract on raster.ts — the page is opaque BLACK (= coverage 0; ink is white
- * and the shader reads the luminance) and nothing may ever draw at (0,0), so slot 0 simply
- * stays black — not something this file can enforce, so the two must change together. If ink
- * ever lands there, every space on the canvas grows a glyph. */
+ * BLANKNESS is a contract on raster.ts — the page starts blank and nothing may ever draw into
+ * slot 0 — not something this file can enforce, so the two must change together. If ink ever
+ * lands there, every space on the canvas grows a glyph. Slot 0 is NOT a special case in the
+ * layout: it sits inside the same gutter every other slot does, so its mip neighbourhood is
+ * free of slot 1's ink for the same reason theirs are free of each other's. */
private nextSlot = 1
private dirtyFlag = false
+ private resets = 0
+ private resetSubs = new Set<() => void>()
constructor(
private rasterizer: GlyphRasterizer,
@@ -69,8 +128,8 @@ export class GlyphAtlas {
}
/**
- * The slot PITCH, in whole texels — the cell rounded UP, so consecutive slots never share a
- * texel.
+ * The slot PITCH, in whole texels — the cell rounded UP plus a gutter on each side, so
+ * consecutive slots share neither a texel nor a mip neighbourhood.
*
* Pitch and extent are separate for one reason. Rounding the CELL to whole texels (what this
* atlas used to do) means a glyph rasterized into N texels is drawn onto a quad of N±0.5
@@ -80,14 +139,17 @@ export class GlyphAtlas {
* a fractional origin would put two neighbouring glyphs' anti-aliasing in the SAME boundary
* texel, and a full-block glyph would then bleed a dim column into an unrelated slot.
*
- * The `max(1, …)` is not decoration: a pitch of 0 makes `capacity` infinite and `cellXY`'s
- * modulo NaN.
+ * The gutter rides on the PITCH, not on the extent: growing the sampled extent would pull the
+ * neighbouring backdrop into every glyph at zoom 1, which is the opposite of the point.
+ *
+ * The `max(1, …)` is not decoration: without it a sub-texel cell would round to a 0-texel ink
+ * box, and `capacity`/`cellXY` would count slots that cannot hold a pixel.
*/
get strideX(): number {
- return Math.max(1, Math.ceil(this.rasterizer.cellW))
+ return Math.max(1, Math.ceil(this.rasterizer.cellW)) + 2 * GUTTER_PX
}
get strideY(): number {
- return Math.max(1, Math.ceil(this.rasterizer.cellH))
+ return Math.max(1, Math.ceil(this.rasterizer.cellH)) + 2 * GUTTER_PX
}
get capacity(): number {
@@ -96,13 +158,23 @@ export class GlyphAtlas {
return cols * rows
}
- /** Row-major top-left of a slot, in page PIXELS — the single copy of the layout math.
+ /** How many times the page has been cleared and re-filled. Read by the device-debug log line —
+ * resets are expected to be rare, and "how rare" is the number that decides whether the v1
+ * reset-on-full model needs the Phase-2 escalation to real LRU eviction. */
+ get resetCount(): number {
+ return this.resets
+ }
+
+ /** Row-major INK origin of a slot, in page PIXELS — the single copy of the layout math.
*
* Both consumers must agree exactly: `glyphFor` uses it to place the ink and `slotRect` to
* derive the uv rect the shader samples. Two hand-written copies would drift the moment
- * either the page metrics or the padding changed, and the symptom is every glyph rendering
+ * either the page metrics or the gutter changed, and the symptom is every glyph rendering
* a fraction of a cell off — not a crash, just permanently wrong text.
*
+ * The pitch cell's corner is `(slot % cols) * strideX`; the INK starts one gutter inside it on
+ * each axis, which is what leaves the ink-free margin the mip chain needs (see GUTTER_PX).
+ *
* On a DEGENERATE page (`sizePx < strideX`, so `cols === 0`) `slot % 0` is NaN, which would
* propagate silently into the uv rect. Capacity is 0 there, so no slot is ever allocated and
* the origin is simply (0,0) — the blank slot. */
@@ -110,29 +182,84 @@ export class GlyphAtlas {
const cols = Math.floor(this.sizePx / this.strideX)
if (cols <= 0) return { x: 0, y: 0 }
return {
- x: (slot % cols) * this.strideX,
- y: Math.floor(slot / cols) * this.strideY
+ x: (slot % cols) * this.strideX + GUTTER_PX,
+ y: Math.floor(slot / cols) * this.strideY + GUTTER_PX
}
}
- glyphFor(code: number, bold: boolean, italic: boolean): number {
+ /**
+ * Subscribe to page resets. Fired AFTER the page has been blanked and the bookkeeping emptied,
+ * and BEFORE the allocation that triggered the reset lands — so a subscriber that repacks
+ * immediately packs into the fresh page and can never write a lane pointing at a slot that no
+ * longer holds what it held.
+ *
+ * A subscriber MAY call back into `glyphFor` (that is what a repack is), and doing so is safe:
+ * the reset path never recurses, and an allocation that no longer fits the freshly-filled page
+ * degrades to the blank slot instead of resetting again. It is still the wrong shape for the
+ * addon — a full repack inside someone else's pack loop — which is why T4 defers it.
+ */
+ onReset(cb: () => void): GlyphAtlasSubscription {
+ this.resetSubs.add(cb)
+ return {
+ dispose: () => {
+ this.resetSubs.delete(cb)
+ }
+ }
+ }
+
+ /**
+ * Clear the page and start over — xterm's `clearTextureAtlas` model.
+ *
+ * Colour keys grow with the palette, so a single page WILL fill on a busy canvas. The
+ * alternative, evicting one slot at a time, has a dangling-slot problem this design does not:
+ * a lane already uploaded to the GPU keeps pointing at the evicted slot and silently renders
+ * whatever glyph reused it. After a reset NO lane is valid, subscribers are told exactly that,
+ * and every row is repacked — one expensive frame instead of a permanent class of wrong pixels.
+ */
+ private reset(): void {
+ this.slots.clear()
+ this.nextSlot = 1
+ this.resets++
+ this.rasterizer.clearPage()
+ this.dirtyFlag = true
+ // Iterate a COPY: a subscriber is allowed to dispose itself (or another) from inside its own
+ // callback, and mutating the live set mid-iteration would skip the next subscriber.
+ for (const cb of [...this.resetSubs]) {
+ try {
+ cb()
+ } catch (err) {
+ // One broken repack must not cost the other subscribers their notification — nor the
+ // frame. The page is already consistent by the time we get here.
+ console.warn('[glyphgrid] atlas onReset subscriber threw:', err)
+ }
+ }
+ }
+
+ glyphFor(code: number, bold: boolean, italic: boolean, fg: number, bg: number): number {
if (code === 0x20 || code === 0) return 0
- const key = `${code}|${bold ? 1 : 0}${italic ? 1 : 0}`
+ const key = `${code}|${bold ? 1 : 0}${italic ? 1 : 0}|${fg}|${bg}`
const hit = this.slots.get(key)
if (hit !== undefined) return hit
- // Covers the degenerate page too (capacity 0 → 1 >= 0), so nothing is ever rasterized onto a
- // page that has no room for a single cell.
- if (this.nextSlot >= this.capacity) return 0 // page full — degrade to blank, never throw
+ if (this.nextSlot >= this.capacity) {
+ // A page with room for nothing but the blank slot (capacity <= 1, degenerate pages
+ // included) can never satisfy this request: resetting would blank an empty page and notify
+ // every subscriber on EVERY glyph, forever. Degrade to blank instead.
+ if (this.capacity <= 1) return 0
+ this.reset()
+ // A subscriber may have repacked enough rows to fill the fresh page again. Never recurse —
+ // one reset per request — and degrade to blank rather than allocate off the end of the page.
+ if (this.nextSlot >= this.capacity) return 0
+ }
const slot = this.nextSlot++
const { x, y } = this.cellXY(slot)
- this.rasterizer.draw(code, bold, italic, x, y)
+ this.rasterizer.draw(code, bold, italic, x, y, fg, bg)
this.slots.set(key, slot)
this.dirtyFlag = true
// LAST, and guarded: the tap is a debug aid, so a throwing callback must cost a log line, not
// the glyph — everything above is already committed by the time it runs.
if (this.onAllocate) {
try {
- this.onAllocate({ slot, code, bold, italic, x, y })
+ this.onAllocate({ slot, code, bold, italic, x, y, fg, bg })
} catch {
/* a debug tap never breaks a frame */
}
@@ -140,9 +267,10 @@ export class GlyphAtlas {
return slot
}
- /** The uv rect of a slot: the ORIGIN follows the whole-texel pitch, the SIZE is the exact
- * cell — the two are not the same number (see `strideX`), and the shader derives its uv the
- * same way (`uAtlasStride` for the origin, `uAtlasCell` for the extent). */
+ /** The uv rect of a slot: the ORIGIN is the ink origin (pitch cell + gutter), the SIZE is the
+ * exact cell — the three numbers are not interchangeable (see `strideX` and `GUTTER_PX`), and
+ * the shader must derive its uv the same way (`uAtlasStride` for the pitch, the gutter for the
+ * origin offset, `uAtlasCell` for the extent). */
slotRect(slot: number): { u0: number; v0: number; u1: number; v1: number } {
// A degenerate page has no sampleable area at all: return the ZERO rect rather than let the
// division produce NaN, which the shader would turn into undefined texture reads.
diff --git a/src/renderer/glyphgrid/engine.test.ts b/src/renderer/glyphgrid/engine.test.ts
index 6613ac3ad..fcdd4a208 100644
--- a/src/renderer/glyphgrid/engine.test.ts
+++ b/src/renderer/glyphgrid/engine.test.ts
@@ -64,14 +64,20 @@ function fakeGL(): GlyphGL & {
}
const atlas = () =>
- new GlyphAtlas({ cellW: 10, cellH: 20, source: null, draw: () => undefined }, 100)
+ new GlyphAtlas(
+ { cellW: 10, cellH: 20, source: null, draw: () => undefined, clearPage: () => undefined },
+ 100
+ )
/** An atlas whose rasterizer already has a texture source, so the engine can upload it. */
function loadedAtlas(sizePx = 512, cellW = 7, cellH = 15) {
const source = {} as unknown as TexImageSource
return {
source,
- atlas: new GlyphAtlas({ cellW, cellH, source, draw: () => undefined }, sizePx)
+ atlas: new GlyphAtlas(
+ { cellW, cellH, source, draw: () => undefined, clearPage: () => undefined },
+ sizePx
+ )
}
}
@@ -340,12 +346,14 @@ describe('GlyphGridEngine', () => {
e.setViewport(800, 600, 1)
e.setCamera({ x: 0, y: 0, zoom: 1 })
e.register(spec('a', 0))
- a.glyphFor(0x41, false, false) // dirties the atlas
+ a.glyphFor(0x41, false, false, 0xffffffff, 0xff000000) // dirties the atlas
expect(e.frame()).toBe(true)
// The extent stays exact (texel:pixel 1:1 against the quad the grid draws) and the pitch is
// the whole-texel slot spacing; the shader needs both, and handing it the extent as the pitch
// would overlap every slot with its neighbour.
- expect(gl.uploadAtlas).toHaveBeenCalledWith(source, 512, 15.66, 31.2, 16, 32)
+ // The pitch now carries a GUTTER_PX margin on each side (16 + 4, 32 + 4) — the ink-free
+ // ring the mip chain needs. The extent is unchanged: it is still the exact device cell.
+ expect(gl.uploadAtlas).toHaveBeenCalledWith(source, 512, 15.66, 31.2, 20, 36)
// Stronger than "before the first drawGrid": beginFrame pushes uAtlasCols/uAtlasCell from
// the values uploadAtlas stored, so an upload landing after it would leave frame 1 sampling
// slot 0 everywhere and the uniforms permanently one upload stale.
@@ -361,7 +369,7 @@ describe('GlyphGridEngine', () => {
it('uploads a never-uploaded atlas even when it is not dirty, and only once', () => {
const gl = fakeGL()
const { atlas: a } = loadedAtlas()
- a.glyphFor(0x41, false, false)
+ a.glyphFor(0x41, false, false, 0xffffffff, 0xff000000)
a.clearDirty() // rasterized elsewhere: has content, reports clean
const e = new GlyphGridEngine(gl, a)
e.setViewport(800, 600, 1)
diff --git a/src/renderer/glyphgrid/engine.ts b/src/renderer/glyphgrid/engine.ts
index 6ad0688dd..e84a4a120 100644
--- a/src/renderer/glyphgrid/engine.ts
+++ b/src/renderer/glyphgrid/engine.ts
@@ -38,7 +38,7 @@ export interface GridHandle {
* deferred, not lost, and rides the frame that brings it back into view. Callers therefore
* cannot read a `frame()` of `false` as "my write was dropped".
*
- * The glyph lane must be a slot obtained from `GlyphAtlas.glyphFor(code, bold, italic)` —
+ * The glyph lane must be a slot obtained from `GlyphAtlas.glyphFor(code, bold, italic, fg, bg)` —
* never a raw code point. The atlas owns the slot space (0 is the permanently blank slot,
* and an unrasterized code degrades to it), so a code point written here would sample an
* arbitrary neighbouring glyph.
diff --git a/src/renderer/glyphgrid/feed.test.ts b/src/renderer/glyphgrid/feed.test.ts
index 55f5fea4c..cc58d70e5 100644
--- a/src/renderer/glyphgrid/feed.test.ts
+++ b/src/renderer/glyphgrid/feed.test.ts
@@ -20,6 +20,9 @@ function fakeAtlas(): Pick<GlyphAtlas, 'glyphFor'> & { calls: Array<[number, boo
const calls: Array<[number, boolean, boolean]> = []
return {
calls,
+ // fg/bg are accepted (the atlas keys on them from Phase 1c on) but not recorded yet: the
+ // colours the feed passes are Task 4's subject, and recording them here would pin the
+ // pre-override values this task deliberately leaves alone.
glyphFor(code: number, bold: boolean, italic: boolean): number {
calls.push([code, bold, italic])
return 900 + calls.length
diff --git a/src/renderer/glyphgrid/feed.ts b/src/renderer/glyphgrid/feed.ts
index 5bb639b36..d0ee7b983 100644
--- a/src/renderer/glyphgrid/feed.ts
+++ b/src/renderer/glyphgrid/feed.ts
@@ -214,7 +214,12 @@ export function packViewportRow(
// The guard runs on the DERIVED code: a string can start with a lone surrogate just as
// easily as getCode() can return one, and the rasterizer must never see either.
const code = glyphCode(cell)
- if (isRenderableCode(code)) glyph = atlas.glyphFor(code, bold, italic)
+ // The atlas is keyed by COLOUR from Phase 1c on, so the request carries the lanes this
+ // cell resolved to. NOTE, and this is Task 4's to finish: SELECTION and CURSOR are applied
+ // BELOW this line, so a selected/cursor cell currently asks for a slot in its pre-override
+ // colours. Threading the values is all this task does; moving the request after the
+ // overrides (and the ordering audit that goes with it) is the feed rewire.
+ if (isRenderableCode(code)) glyph = atlas.glyphFor(code, bold, italic, fg, bg)
if (bold) flags |= FLAG_BOLD
if (italic) flags |= FLAG_ITALIC
if (cell.isUnderline() !== 0) flags |= FLAG_UNDERLINE
diff --git a/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx b/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx
index f73edbfb0..427f10e51 100644
--- a/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx
+++ b/src/renderer/glyphgrid/harness/GlyphGridHarness.tsx
@@ -228,12 +228,15 @@ export function GlyphGridHarness() {
// 0x21..0x7a — printable ASCII, so String.fromCodePoint in the rasterizer always
// gets a valid code point.
const code = 0x21 + Math.floor(Math.random() * 90)
+ // Resolved BEFORE the atlas request: the atlas is keyed by colour, so the slot and the
+ // lane have to be asked for with the same pair.
+ const fg = packColor(180 + Math.floor(Math.random() * 75), 200, 160, 255)
writeCell(
row,
c,
// The glyph lane is an ATLAS SLOT, never a raw code point.
- atlas.glyphFor(code, Math.random() < 0.1, false),
- packColor(180 + Math.floor(Math.random() * 75), 200, 160, 255),
+ atlas.glyphFor(code, Math.random() < 0.1, false, fg, bg),
+ fg,
bg,
Math.random() < 0.05 ? FLAG_BOLD : 0
)
diff --git a/src/renderer/glyphgrid/raster.test.ts b/src/renderer/glyphgrid/raster.test.ts
index 2752c521f..6645c048e 100644
--- a/src/renderer/glyphgrid/raster.test.ts
+++ b/src/renderer/glyphgrid/raster.test.ts
@@ -59,6 +59,11 @@ function stubCanvas(): { ops: Op[]; restore: () => void } {
const FONT = { family: 'monospace', sizePx: 16, cellW: 10, cellH: 20 }
+/** Packed colour lanes. T2 is what makes them observable in the ops below; for now they only have
+ * to be threaded through the signature. */
+const FG = 0xffffffff
+const BG = 0xff000000
+
let active: { restore: () => void } | null = null
afterEach(() => {
active?.restore()
@@ -85,7 +90,7 @@ describe('createCanvasRasterizer', () => {
active = stub
const r = createCanvasRasterizer(FONT, 256)!
stub.ops.length = 0
- r.draw(0x41, false, false, 10, 20) // 'A' into the slot at (10,20)
+ r.draw(0x41, false, false, 10, 20, FG, BG) // 'A' into the slot at (10,20)
expect(stub.ops[0]).toEqual({ kind: 'clip', args: [10, 20, 10, 20] })
// The black fill is the slot's own rect — never the page, and the clip above keeps it off the
@@ -106,7 +111,7 @@ describe('createCanvasRasterizer', () => {
active = stub
const r = createCanvasRasterizer(FONT, 256)!
stub.ops.length = 0
- r.draw(0x2588, false, false, 0, 0) // █ full block
+ r.draw(0x2588, false, false, 0, 0, FG, BG) // █ full block
expect(stub.ops.some((o) => o.kind === 'fillText')).toBe(false)
const fills = stub.ops.filter((o) => o.kind === 'fillRect')
@@ -121,10 +126,10 @@ describe('createCanvasRasterizer', () => {
const r = createCanvasRasterizer(FONT, 256)!
const atlas = new GlyphAtlas(r, 256)
stub.ops.length = 0
- expect(atlas.glyphFor(0x20, false, false)).toBe(0)
+ expect(atlas.glyphFor(0x20, false, false, FG, BG)).toBe(0)
expect(stub.ops).toEqual([])
// The first real glyph starts at slot 1 — i.e. past the origin cell.
- atlas.glyphFor(0x41, false, false)
+ atlas.glyphFor(0x41, false, false, FG, BG)
expect(stub.ops.some((o) => o.args[0] === 0 && o.args[1] === 0)).toBe(false)
})
})
diff --git a/src/renderer/glyphgrid/raster.ts b/src/renderer/glyphgrid/raster.ts
index 99a0d8a81..f7e800b08 100644
--- a/src/renderer/glyphgrid/raster.ts
+++ b/src/renderer/glyphgrid/raster.ts
@@ -116,7 +116,18 @@ export function createCanvasRasterizer(
get source() {
return canvas
},
- draw(code, bold, italic, x, y) {
+ /** T2 fills this in: blank the page back to the state `createCanvasRasterizer` leaves it in.
+ * Kept mechanical here — the atlas's reset path needs the member to exist, and the colour
+ * contract (transparent-black page, per-slot backdrops) is Task 2's to land. */
+ clearPage() {
+ ctx.fillStyle = INK_OFF
+ ctx.fillRect(0, 0, atlasSizePx, atlasSizePx)
+ },
+ // fg/bg are the FINAL packed colour lanes for this slot. T2 fills this in: fill the whole
+ // PITCH rect (gutter included) with `bg` and paint the glyph/box ops in `fg`, so the atlas
+ // holds CoreText's own coloured pixels. Until then the draw stays monochrome — the signature
+ // is threaded now because the atlas keys on the colours from this task on.
+ draw(code, bold, italic, x, y, _fg, _bg) {
ctx.save()
ctx.beginPath()
ctx.rect(x, y, font.cellW, font.cellH)