From 1810e8e9e52e463bb249019f62a3ea2ececd619b Mon Sep 17 00:00:00 2001 From: jmmon Date: Sat, 21 Nov 2026 00:29:36 -0500 Subject: [PATCH 1/2] feat(factory): Zone Hint dismissal leaves no residue (integer Overlay Box rects) (#4) --- specs/issue-4.md | 275 ++++++++++++++++++++++++++++++ src/services/draw/overlay.spec.ts | 124 ++++++++++++++ src/services/draw/overlay.ts | 75 ++++++-- src/services/draw/utils.spec.ts | 63 +++++++ src/services/draw/utils.ts | 44 +++-- 5 files changed, 552 insertions(+), 29 deletions(-) create mode 100644 specs/issue-4.md create mode 100644 src/services/draw/overlay.spec.ts create mode 100644 src/services/draw/utils.spec.ts diff --git a/specs/issue-4.md b/specs/issue-4.md new file mode 100644 index 0000000..547be33 --- /dev/null +++ b/specs/issue-4.md @@ -0,0 +1,275 @@ +# Issue #4 — Zone Hint dismissal leaves no residue (integer Overlay Box rects) + +## Goal + +A dismissed Zone Hint leaves zero residual pixels on the Overlay Canvas on +every show→hide cycle, and the fps / dev-stats Overlay Boxes likewise leave no +residue when their values change length or they close. This is achieved by +rounding every Overlay Box rect at the source — floor the left/top, ceil the +right/bottom — via one shared helper, so `fillRect` and `clearRect` always +cover pixel-identical, pixel-aligned regions. Today the Zone Hint's fractional +bottom edge (`tileSize × 1.6` = 51.2 px at tileSize 32) leaves a faint ~9 % +black 1 px line after every dismissal, and the right-anchored fps box leaves a +vertical strip variant when its string length changes. + +## Non-goals + +- No changes to the help, help-hint, AFK, statusbar, or chunk-overlay rect + computations. Their fractional edges are explicitly out of scope. +- No refactor of the overlay draw architecture (no new draw scheduler, no + full-canvas-per-frame clear). +- No change to text metrics (`fontSize`, `lineHeight`, `leftPadding` stay + fractional); only the box rect used for fill/clear is rounded. +- No viewport-resize residue handling beyond what exists today (resize is not + part of this issue). +- No change to the zone-teaching state machine or hint dismissal triggers. + +## Contracts + +### Why the residue happens (invariant to preserve) + +`fillRect`/`clearRect` with fractional coordinates anti-alias edge pixels. +The Zone Hint is filled once (alpha 0.55 × 0.2 coverage on the bottom row +≈ 0.11) and cleared once on dismissal (removes only 20 % of that row's alpha) +→ ~0.09 black line persists. The fps/dev-stats boxes are redrawn every frame; +their fractional left column converges to full box alpha, and when the box +width changes (fps string length) the old wider box's left columns are never +cleared → persistent vertical strip. Integer rects make fill and clear exact +complements. + +### New shared helper — `src/services/draw/utils.ts` + +```ts +export interface PixelRect { + left: number; + top: number; + right: number; + bottom: number; +} + +/** Round a rect outward to device pixels: floor left/top, ceil right/bottom. + * fillRect/clearRect over the result cover identical, pixel-aligned regions. */ +export function pixelRect( + left: number, + top: number, + right: number, + bottom: number, +): PixelRect; +``` + +- `left`/`top` use `Math.floor`, `right`/`bottom` use `Math.ceil`. +- Integer inputs pass through unchanged. +- Negative coordinates behave normally (floor toward −∞). + +### Changed rect computations — `src/services/draw/overlay.ts` + +All three helpers must be **exported** (they are module-private today) so unit +tests can call them, and each must route its box rect through `pixelRect`: + +1. `getZoneHintRect(viewport: Viewport, config: MapConfig): RectDimensions` + — keeps its `{ left, top, w, h }` shape, but `left`, `top`, `left + w`, + `top + h` are all integers. Source values: `w = tileSize * 9`, + `h = tileSize * 1.6`, `left = (viewport.width - w) / 2`, + `top = tileSize * 0.5`. +2. `getFpsStyles(viewport: Viewport, config: MapConfig, canvas: HTMLCanvasElement, fps: string, ema?: string): StylesWithContext` + — returned `x`, `y`, `x + width`, `y + height` are all integers. The box is + right-anchored (`x = viewport.width - width`), so after rounding + `right === viewport.width` (viewport widths are integer canvas widths). +3. `getDevStatsStyles(viewport: Viewport, config: MapConfig, canvas: HTMLCanvasElement): StylesWithContext` + — same integer-edge invariant. Its width is value-independent (derived from + `STAT_NAME_LONGEST`), so rounding alone removes its residue. + +Invariants the implementation must preserve: + +- Every draw/close pair (`drawZoneHint`/`closeZoneHint`, `drawFps`/`closeFps`, + `drawDevStats`/`closeDevStats`) computes its rect through the same helper, + so fill and clear are pixel-identical for the same inputs. +- The scale-change paths (`hasScaleChanged` + `generateOldDimensions`) keep + working: the old-dimension rects also flow through the helpers, so old rects + are integer too. +- Text layout (font size, line height, padding, text positions) is unchanged; + only the rect edges move, by < 1 px. + +### fps clear must cover the previous box + +Rounding alone does NOT remove the length-change strip: when the fps string +shrinks (e.g. `"60.00"` → `"4.00"`), the new narrower clear rect never covers +the old wider box's left columns. The contract therefore also requires: + +- `drawFps`'s clear region must cover **both the previously drawn fps box and + the new one** (suggested: track the last drawn `PixelRect` in a module-level + variable in `overlay.ts` and clear the union of old and new). +- `closeFpsOnly` must clear the previously drawn box. Its current max-length + placeholder `("00.0", "00.0")` is **shorter than real fps strings** + (`initFpsTest` emits `toFixed(2)` values like `"60.00"`, `"120.00"`), so it + under-covers today; replace it with the tracked last rect (or a placeholder + at least as wide as any real value). +- `closeDevStats` needs no such union (constant width); the rounded rect is + exactly what was drawn. + +### Untouched + +`generateHelpDimensions`, `drawHelpHint`'s inline rects, `getAfkRect`, +`getStatusStyles`, `CHUNK_OVERLAY` — no `pixelRect` call, no edge changes. + +### Edge cases + +- Integer-input rects: unchanged (no ±1 px growth). +- Odd viewport widths → fractional zone-hint `left` (e.g. `(1023 − 288) / 2 = +367.5`): floor/ceil still yields integers that contain the fractional rect. +- Fractional scale (e.g. 1.25): all three helpers produce fractional rects + internally; `pixelRect` guarantees integer edges regardless. +- Viewport narrower than the box (negative `left`): allowed, rounded outward. + +## Acceptance criteria + +1. **GIVEN** fractional coordinates WHEN `pixelRect(l, t, r, b)` is called + THEN the result has `left = Math.floor(l)`, `top = Math.floor(t)`, + `right = Math.ceil(r)`, `bottom = Math.ceil(b)`, and integer inputs return + unchanged. +2. **GIVEN** `getZoneHintRect` called with viewport widths 800, 1023, 1024, + 1280 at `tileSize = 32`, `scale = 1`, and again at `scale = 1.25` WHEN the + rect is returned THEN `left`, `top`, `left + w`, `top + h` are all + integers and the rounded rect contains the unrounded rect + (`left ≤ origLeft`, `top ≤ origTop`, `right ≥ origRight`, + `bottom ≥ origBottom`). +3. **GIVEN** `getFpsStyles` called with `fps ∈ {"5.00", "60.00", "120.00"}` + (with and without `ema`) at viewport widths 800, 1023, 1280, `tileSize 32`, + `scale 1` and `scale 1.25` WHEN the styles are returned THEN `x`, `y`, + `x + width`, `y + height` are all integers and `x + width === +viewport.width`. +4. **GIVEN** `getDevStatsStyles` called at viewport widths 800, 1023, 1280, + `tileSize 32`, `scale 1` and `scale 1.25` WHEN the styles are returned + THEN `x`, `y`, `x + width`, `y + height` are all integers. +5. **GIVEN** the fps box drawn with a 5-char fps string WHEN the value changes + to a 4-char string THEN no pixel remains painted in the top-right region + left of the new box's left edge (vertical strip gone). Verified by QA + Scenario 2 (CPU throttle + strip probe). +6. **GIVEN** the Zone Hint is visible WHEN it is dismissed THEN every pixel of + the overlay canvas inside the rounded rect + (`left = floor((W − 288) / 2)`, `top = 16`, + `right = ceil((W − 288) / 2 + 288)`, `bottom = ceil(16 + 51.2) = 68`, + `W` = overlay canvas width) has alpha exactly 0. Verified by QA + Scenario 1. +7. **GIVEN** fps + dev-stats are displayed WHEN `show.devStats` is toggled off + THEN every pixel of the overlay canvas in region + `x ∈ [W − 260, W)`, `y ∈ [0, 140)` has alpha exactly 0. Verified by QA + Scenario 2 step 8. +8. **GIVEN** the final diff WHEN the help, help-hint, AFK, and statusbar rect + computations are inspected THEN none of them call `pixelRect` and their + rect math is byte-identical to before (reviewer diff check; automated + proxy: `grep -n "pixelRect" src/services/draw/overlay.ts` shows call sites + only in the zone-hint, fps, and dev-stats sections). +9. **GIVEN** the completed change WHEN `pnpm test.unit && pnpm lint && +pnpm build.types && pnpm build` runs THEN all four commands exit 0. + +## Test plan + +- **Create `src/services/draw/utils.spec.ts`** (colocated with `utils.ts`): + covers AC1 — `pixelRect` floor/ceil directions, integer passthrough, + negative coordinates, containment of the input rect. +- **Create `src/services/draw/overlay.spec.ts`** (colocated with `overlay.ts`): + - AC2 — `getZoneHintRect` integer edges + containment across the width / + tileSize / scale matrix above. + - AC3 — `getFpsStyles` integer edges, right edge flush with + `viewport.width`, across the fps-string / width / scale matrix. + - AC4 — `getDevStatsStyles` integer edges across the same matrix. +- **Harness details**: + - The style helpers take an `HTMLCanvasElement` only to attach + `canvas.getContext("2d")!` to the returned object; they never call + methods on it during style computation. Pass a stub: + `{ getContext: () => ({}) as CanvasRenderingContext2D }` cast as + `HTMLCanvasElement`. No jsdom / node-canvas needed (vitest runs in node + env per `vite.config.ts`). + - Build `MapConfig` fixtures as object literals cast `as MapConfig` + (interface in `src/server/map.ts`); only `tileSize`, `scale`, + `lastScale` matter. `Viewport` literals: `{ width, height, origin: { x: 0, y: 0 } }`. + - Pure-function entry points: `pixelRect`, `getZoneHintRect`, + `getFpsStyles`, `getDevStatsStyles` (all exported by this change). No + fake timers needed; nothing reads the clock. + - AC5/AC6/AC7 are canvas-pixel behaviors owned by the QA station's + Playwright run (below); do not attempt them in vitest. + +## QA plan + +Boot: `pnpm dev --port 5199 --strictPort`, base URL +`http://localhost:5199`. Throwaway harness at `qa-artifacts/qa-run.ts` +(Playwright config with `testMatch` on it, `reuseExistingServer: false`, +chromium, viewport 1280×720). **One browser context / one page is enough** — +this is a single-player rendering check; no multiplayer pairing needed. +Login flow (same as `e2e/intro.spec.ts`): goto `/canvas1`, fill +`#username`, click Submit, poll +`__vimworld.client.isReady && __vimworld.client.lastAckCheckpoint` (20 s). +Press keys one at a time with ~100 ms gaps. Fresh server = fresh world (chest +not yet emptied). All probes read +`document.querySelector('canvas[data-name="overlay"]')` and use +`getContext("2d").getImageData(...)`; `W` = that canvas's `width` attribute +(scrollbars may make it ≠ 1280, so never hardcode). + +### Scenario 1 — Zone Hint show → dismiss → zero residue (AC6) + +1. Login as `qa-residue-4`. Walk to the room-3 chest: press + `1 7 l w 2 l w 2 l w 2 l 9 l k`; poll `__vimworld.client.player.pos` + equals `{ x: 40, y: 8 }`. +2. Poll `__vimworld.client.zoneHintText` matches `/take the key/i` (10 s). +3. Screenshot `qa-artifacts/zone-hint-visible.png`. +4. Probe A (hint painted): compute + `left = Math.floor((W - 288) / 2)`, `top = 16`, + `right = Math.ceil((W - 288) / 2 + 288)`, `bottom = 68`; + `getImageData(left, top, right - left, bottom - top)`; assert the pixel at + `(left + 5, top + 4)` has alpha > 100 (hint background present). +5. Dismiss for real: press `y`, `i`, `"` (yank the key → auto-dismiss); poll + `__vimworld.client.zoneHintText === ""` (10 s); wait 300 ms for the close + frame. +6. Probe B: same `getImageData`; assert **every** pixel has `alpha === 0`. +7. Screenshot `qa-artifacts/zone-hint-dismissed.png`. + +### Scenario 2 — fps / dev-stats vertical residue (AC5, AC7) + +1. Same page (dev overlay is on by default: `show.devStats = true`). Wait 2 s + so the fps box has settled (≈ `"60.00"`, 5 chars). +2. Force a value-length change via CDP: + `const cdp = await page.context().newCDPSession(page);` + `await cdp.send("Emulation.setCPUThrottlingRate", { rate: 20 })`; wait 4 s + (fps drops below 10 → string shrinks to 4 chars → box narrows → a buggy + build leaves the old wider box's left columns painted). +3. fps strip probe (AC5): region `x ∈ [W − 260, W)`, `y ∈ [0, 50)`. On row 25, + scan left from column `W − 1` while alpha > 0; let `L` be the first column + left of that run. Assert `L > W − 260` (box found) and every pixel in + columns `[W − 260, L − 1]` has `alpha === 0`. +4. dev-stats strip probe: same algorithm on row 100, region `y ∈ [54, 140)`. +5. Screenshot `qa-artifacts/fps-devstats-throttled.png` clipped to + `{ x: W - 260, y: 0, width: 260, height: 140 }`. +6. Un-throttle: `cdp.send("Emulation.setCPUThrottlingRate", { rate: 1 })`. +7. Close the boxes: `page.evaluate(() => { (window as any).__vimworld.show.devStats = false })`; + wait 300 ms. +8. Close probe (AC7): `getImageData(W - 260, 0, 260, 140)`; assert every + pixel has `alpha === 0`. +9. Screenshot `qa-artifacts/devstats-closed.png` (same clip). + +Evidence: 4 screenshots (≤ 6 allowed). Every numbered probe above is a +Playwright assertion, not a human eyeball. + +## Risks + +- **The issue text attributes the fps length-change strip to rounding alone; + rounding cannot fix it** (a narrower new clear rect never covers the old + wider box). The contract therefore adds the last-rect/max-rect clear for + `drawFps`/`closeFpsOnly`. If the reviewer reads the issue as "rounding only, + nothing else", AC5 will fail — this interpretation is the spec author's call. +- `closeFpsOnly`'s current placeholder `("00.0", "00.0")` is shorter than real + fps strings (`toFixed(2)` → `"60.00"`, `"120.00"`), so it under-covers + today; the fix must widen or replace it or AC7 fails. +- dev-stats width is value-independent (`STAT_NAME_LONGEST`), so its + "value length changes" case is a no-op; the vertical-strip risk is fps-only. + The dev-stats probe still guards against regressions. +- Scenario 2's length change assumes headless fps starts ≥ 10 (5-char string). + On an extremely slow runner the baseline may already be 4 chars; the probe + still passes but exercises less. The strip assertions hold either way. +- The zone-hint dismissal path (yank the key) needs a fresh world; QA boots + its own dev server with `reuseExistingServer: false`, so this is satisfied. +- `tileSize` is read live from `__vimworld.world.config.tileSize` (32 today); + the probe formulas use `t = tileSize`, `w = 9t`, `h = 1.6t` rather than + hardcoded 288/51.2 if the config ever changes. + +STATUS: READY diff --git a/src/services/draw/overlay.spec.ts b/src/services/draw/overlay.spec.ts new file mode 100644 index 0000000..8dd51ac --- /dev/null +++ b/src/services/draw/overlay.spec.ts @@ -0,0 +1,124 @@ +import { describe, expect, test } from "vitest"; +import { + getDevStatsStyles, + getFpsStyles, + getZoneHintRect, +} from "~/services/draw/overlay"; +import type { MapConfig } from "~/server/map"; +import type { Viewport } from "~/simulation/client/types"; + +// Overlay Box rects must have integer edges so fillRect/clearRect are exact +// complements and dismissed boxes leave zero residue (issue #4). + +// The style helpers only attach canvas.getContext("2d") to the returned +// object; they never call methods on it during style computation. +const canvasStub = () => + ({ + getContext: () => ({}) as CanvasRenderingContext2D, + }) as unknown as HTMLCanvasElement; + +const viewport = (width: number): Viewport => ({ + width, + height: 720, + origin: { x: 0, y: 0 }, +}); + +const config = (scale: number): MapConfig => + ({ tileSize: 32, scale, lastScale: scale }) as MapConfig; + +const WIDTHS = [800, 1023, 1024, 1280]; +const FPS_WIDTHS = [800, 1023, 1280]; +const SCALES = [1, 1.25]; + +const isInt = (n: number) => Number.isInteger(n); + +describe("getZoneHintRect", () => { + test("integer edges and outward rounding at scale 1 (spec source values)", () => { + for (const width of WIDTHS) { + const r = getZoneHintRect(viewport(width), config(1)); + // spec source values at tileSize 32: w = 288, h = 51.2, top = 16 + const w = 32 * 9; + const h = 32 * 1.6; + const left = (width - w) / 2; + const top = 32 * 0.5; + expect(isInt(r.left)).toBe(true); + expect(isInt(r.top)).toBe(true); + expect(isInt(r.left + r.w)).toBe(true); + expect(isInt(r.top + r.h)).toBe(true); + // rounded rect contains the unrounded source rect ... + expect(r.left).toBeLessThanOrEqual(left); + expect(r.top).toBeLessThanOrEqual(top); + expect(r.left + r.w).toBeGreaterThanOrEqual(left + w); + expect(r.top + r.h).toBeGreaterThanOrEqual(top + h); + // ... with each edge moved by < 1 px (no arbitrary padding) + expect(r.left).toBeGreaterThan(left - 1); + expect(r.top).toBeGreaterThan(top - 1); + expect(r.left + r.w).toBeLessThan(left + w + 1); + expect(r.top + r.h).toBeLessThan(top + h + 1); + } + }); + + test("integer edges hold at fractional scale 1.25", () => { + for (const width of WIDTHS) { + const r = getZoneHintRect(viewport(width), config(1.25)); + expect(isInt(r.left)).toBe(true); + expect(isInt(r.top)).toBe(true); + expect(isInt(r.left + r.w)).toBe(true); + expect(isInt(r.top + r.h)).toBe(true); + } + }); +}); + +describe("getFpsStyles", () => { + test("integer edges with right edge flush at viewport.width across the matrix", () => { + for (const width of FPS_WIDTHS) { + for (const scale of SCALES) { + for (const fps of ["5.00", "60.00", "120.00"]) { + for (const ema of [undefined, "16.7"]) { + const s = getFpsStyles( + viewport(width), + config(scale), + canvasStub(), + fps, + ema, + ); + expect(isInt(s.x)).toBe(true); + expect(isInt(s.y)).toBe(true); + expect(isInt(s.x + s.width)).toBe(true); + expect(isInt(s.y + s.height)).toBe(true); + // right-anchored box: rounded right edge stays flush + expect(s.x + s.width).toBe(width); + } + } + } + } + }); + + test("box width grows with fps string length (drives the residue bug)", () => { + const vp = viewport(1280); + const cfg = config(1); + const narrow = getFpsStyles(vp, cfg, canvasStub(), "5.00"); + const wide = getFpsStyles(vp, cfg, canvasStub(), "120.00"); + // a longer value must produce a strictly wider box; if width ignored + // the string, the length-change strip could never be reproduced + expect(wide.width).toBeGreaterThan(narrow.width); + }); +}); + +describe("getDevStatsStyles", () => { + test("integer edges across the width / scale matrix", () => { + for (const width of FPS_WIDTHS) { + for (const scale of SCALES) { + const s = getDevStatsStyles( + viewport(width), + config(scale), + canvasStub(), + ); + expect(isInt(s.x)).toBe(true); + expect(isInt(s.y)).toBe(true); + expect(isInt(s.x + s.width)).toBe(true); + expect(isInt(s.y + s.height)).toBe(true); + } + } + }); +}); diff --git a/src/services/draw/overlay.ts b/src/services/draw/overlay.ts index 9cc1904..abbd8d3 100644 --- a/src/services/draw/overlay.ts +++ b/src/services/draw/overlay.ts @@ -1,5 +1,10 @@ import { roundToDecimals } from "~/utils/utils"; -import { generateOldDimensions, hasScaleChanged } from "./utils"; +import { + generateOldDimensions, + hasScaleChanged, + pixelRect, + PixelRect, +} from "./utils"; import { GameState } from "~/hooks/useState"; import { MapConfig } from "~/server/map"; import { Viewport } from "~/simulation/client/types"; @@ -51,7 +56,7 @@ interface StylesWithContext extends BoxStyles { // **************************************************************** // has about 10 total chars wide + padding -function getFpsStyles( +export function getFpsStyles( viewport: Viewport, { scale }: MapConfig, canvas: HTMLCanvasElement, @@ -69,11 +74,20 @@ function getFpsStyles( 12, scale, ); + // right-anchored box: round the rect outward so fill/clear are exact + const rect = pixelRect( + viewport.width - styles.width, + 0, + viewport.width, + styles.height, + ); return { ctx: canvas.getContext("2d")!, - x: viewport.width - styles.width, - y: 0, ...styles, + x: rect.left, + y: rect.top, + width: rect.right - rect.left, + height: rect.bottom - rect.top, }; } @@ -90,10 +104,18 @@ function closeFps( return d; } +// last box drawn by drawFps, so a shorter fps string still clears the old +// wider box's columns (issue #4 vertical strip) +let lastFpsRect: PixelRect | null = null; + export function closeFpsOnly(state: GameState) { - // erase with a max-length placeholder so the box is fully covered - // regardless of the last drawn fps/ema string lengths - closeFps(state, state.ctx.client.viewport, state.ctx.world.config, "00.0", "00.0"); + // clear exactly the box that was drawn last (the old "00.0" placeholder + // was shorter than real fps values and under-covered) + if (!lastFpsRect) return; + const ctx = state.refs.overlay.value!.getContext("2d")!; + const r = lastFpsRect; + ctx.clearRect(r.left, r.top, r.right - r.left, r.bottom - r.top); + lastFpsRect = null; } export function drawFps(state: GameState, fps: string, ema?: string) { @@ -109,6 +131,17 @@ export function drawFps(state: GameState, fps: string, ema?: string) { fps, ema, ); + // and the previously drawn box, so a shrinking fps string leaves no strip + if (lastFpsRect) { + const r = lastFpsRect; + d.ctx.clearRect(r.left, r.top, r.right - r.left, r.bottom - r.top); + } + lastFpsRect = { + left: d.x, + top: d.y, + right: d.x + d.width, + bottom: d.y + d.height, + }; // background d.ctx.fillStyle = "rgba(0, 0, 0, 0.3)"; @@ -207,7 +240,7 @@ type D = { y: number; lines: number; }; -function getDevStatsStyles( +export function getDevStatsStyles( viewport: Viewport, { scale }: MapConfig, canvas: HTMLCanvasElement, @@ -225,12 +258,21 @@ function getDevStatsStyles( scale, ); const fpsYEnd = 2 * styles.fontSize + 12 * scale; + const y = fpsYEnd + 10 * scale; // slight gap from the fps window + const rect = pixelRect( + viewport.width - styles.width, + y, + viewport.width, + y + styles.height, + ); return { ctx: canvas.getContext("2d")!, - x: viewport.width - styles.width, - y: fpsYEnd + 10 * scale, // slight gap from the fps window ...styles, + x: rect.left, + y: rect.top, + width: rect.right - rect.left, + height: rect.bottom - rect.top, }; } @@ -422,17 +464,20 @@ export function drawHelpHint(state: GameState) { // **************************************************************** /** single-line contextual hint, top-center — one verb at a time */ -function getZoneHintRect( +export function getZoneHintRect( viewport: Viewport, { tileSize }: MapConfig, ): RectDimensions { const w = tileSize * 9; const h = tileSize * 1.6; + const left = (viewport.width - w) / 2; + const top = tileSize * 0.5; + const rect = pixelRect(left, top, left + w, top + h); return { - left: (viewport.width - w) / 2, - top: tileSize * 0.5, - w, - h, + left: rect.left, + top: rect.top, + w: rect.right - rect.left, + h: rect.bottom - rect.top, }; } diff --git a/src/services/draw/utils.spec.ts b/src/services/draw/utils.spec.ts new file mode 100644 index 0000000..a65dec2 --- /dev/null +++ b/src/services/draw/utils.spec.ts @@ -0,0 +1,63 @@ +import { describe, expect, test } from "vitest"; +import { pixelRect } from "~/services/draw/utils"; + +// pixelRect rounds a rect outward to device pixels so fillRect/clearRect +// always cover pixel-identical, pixel-aligned regions (issue #4). + +describe("pixelRect", () => { + test("floors left/top and ceils right/bottom on fractional input", () => { + const r = pixelRect(10.2, 20.7, 30.9, 40.1); + expect(r.left).toBe(10); + expect(r.top).toBe(20); + expect(r.right).toBe(31); + expect(r.bottom).toBe(41); + }); + + test("integer inputs pass through unchanged (no ±1 px growth)", () => { + const r = pixelRect(4, 8, 12, 16); + expect(r.left).toBe(4); + expect(r.top).toBe(8); + expect(r.right).toBe(12); + expect(r.bottom).toBe(16); + + const neg = pixelRect(-4, -8, 12, 16); + expect(neg.left).toBe(-4); + expect(neg.top).toBe(-8); + expect(neg.right).toBe(12); + expect(neg.bottom).toBe(16); + }); + + test("negative coordinates floor toward −∞ and ceil toward +∞", () => { + const r = pixelRect(-10.8, -3.2, -1.4, 6.6); + expect(r.left).toBe(-11); + expect(r.top).toBe(-4); + expect(r.right).toBe(-1); + expect(r.bottom).toBe(7); + }); + + test("result contains the input rect on every edge, grown by < 1 px", () => { + const cases: Array<[number, number, number, number]> = [ + [1.2, 3.7, 8.9, 12.4], + [-5.5, 0.5, 2.25, 9.75], + [0, 0, 0.5, 0.5], + [367.5, 16, 655.5, 67.2], + ]; + for (const [left, top, right, bottom] of cases) { + const r = pixelRect(left, top, right, bottom); + expect(Number.isInteger(r.left)).toBe(true); + expect(Number.isInteger(r.top)).toBe(true); + expect(Number.isInteger(r.right)).toBe(true); + expect(Number.isInteger(r.bottom)).toBe(true); + // outward rounding: the rounded rect contains the input rect ... + expect(r.left).toBeLessThanOrEqual(left); + expect(r.top).toBeLessThanOrEqual(top); + expect(r.right).toBeGreaterThanOrEqual(right); + expect(r.bottom).toBeGreaterThanOrEqual(bottom); + // ... and never grows by a full pixel + expect(r.left).toBeGreaterThan(left - 1); + expect(r.top).toBeGreaterThan(top - 1); + expect(r.right).toBeLessThan(right + 1); + expect(r.bottom).toBeLessThan(bottom + 1); + } + }); +}); diff --git a/src/services/draw/utils.ts b/src/services/draw/utils.ts index 0b66f4b..a60e49c 100644 --- a/src/services/draw/utils.ts +++ b/src/services/draw/utils.ts @@ -1,8 +1,31 @@ import { WorldEntity } from "~/types/worldTypes"; -import { LocalWorldWrapper, Viewport } from "~/simulation/client/types";; +import { LocalWorldWrapper, Viewport } from "~/simulation/client/types"; import { GameState } from "~/hooks/useState"; import { MapConfig } from "~/server/map"; +export interface PixelRect { + left: number; + top: number; + right: number; + bottom: number; +} + +/** Round a rect outward to device pixels: floor left/top, ceil right/bottom. + * fillRect/clearRect over the result cover identical, pixel-aligned regions. */ +export function pixelRect( + left: number, + top: number, + right: number, + bottom: number, +): PixelRect { + return { + left: Math.floor(left), + top: Math.floor(top), + right: Math.ceil(right), + bottom: Math.ceil(bottom), + }; +} + export const getScaledTileSize = (config: MapConfig, scaleDecimal: number) => { const tileSize = Math.round(config.chunkWidth * scaleDecimal); const actualScale = tileSize / config.chunkWidth; @@ -22,10 +45,9 @@ export function hasScaleChanged(state: LocalWorldWrapper) { ); } -export function generateOldDimensions(state: LocalWorldWrapper): [ - Viewport, - MapConfig, -] { +export function generateOldDimensions( + state: LocalWorldWrapper, +): [Viewport, MapConfig] { const tileSize = state.world.config.tileSize * state.world.config.lastScale; const config: MapConfig = { ...state.world.config, @@ -38,10 +60,7 @@ export function generateOldDimensions(state: LocalWorldWrapper): [ height: state.client.viewport.height, origin: state.client.viewport.origin, }; - return [ - viewport, - config, - ]; + return [viewport, config]; } export function clearOldCanvas( @@ -50,9 +69,7 @@ export function clearOldCanvas( ) { // clear old rect if (hasScaleChanged(state)) { - const [ viewport ] = generateOldDimensions( - state, - ); + const [viewport] = generateOldDimensions(state); ctx.clearRect(0, 0, viewport.width, viewport.height); } } @@ -82,7 +99,7 @@ export function shadeColor(color: string, percent: number /** 0-100 */) { } export function clearAll(state: GameState) { - const [ viewport ] = generateOldDimensions(state.ctx); + const [viewport] = generateOldDimensions(state.ctx); [ [viewport.width, viewport.height], // old [ @@ -96,4 +113,3 @@ export function clearAll(state: GameState) { state.refs.overlay.value!.getContext("2d")!.clearRect(0, 0, x, y); }); } - From a255070203e00f3d8014e09c75d03b59f3866175 Mon Sep 17 00:00:00 2001 From: jmmon Date: Sat, 21 Nov 2026 00:47:11 -0500 Subject: [PATCH 2/2] docs(factory): retro for issue #4 --- factory/retro/LEDGER.md | 5 +++++ factory/retro/issue-4.md | 31 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 factory/retro/LEDGER.md create mode 100644 factory/retro/issue-4.md diff --git a/factory/retro/LEDGER.md b/factory/retro/LEDGER.md new file mode 100644 index 0000000..fc13595 --- /dev/null +++ b/factory/retro/LEDGER.md @@ -0,0 +1,5 @@ +# Ledger + +One line per issue, upserted on rerun. Columns: date | issue | outcome | attempts (spec/tests/implement/qa/review) | minutes (wall) | tags | merged | edits + +2026-11-21 | #4 | pr | 2/1/1/1/1 | 39 | spec-miss | - | - diff --git a/factory/retro/issue-4.md b/factory/retro/issue-4.md new file mode 100644 index 0000000..1aec714 --- /dev/null +++ b/factory/retro/issue-4.md @@ -0,0 +1,31 @@ +## Factory retro for #4 + +**Zone Hint dismissal leaves no residue (integer Overlay Box rects)** + +- Outcome: pr +- Attempts: spec 3 (2 failed in run 1, 1 ok in run 2) / tests 1 / implement 1 / qa 1 / review 1 +- Wall minutes: 40 + +### Failures + +- spec (run 1): `opencode run` rejected the runner's `--dir` flag (`Unrecognized flag: --dir`), so the spec agent never executed; `specs/issue-4.md` was not written on either attempt and the run escalated (`factory/logs/issue-4/spec-2.log`, `factory/logs/issue-4/run.log`) — tags: spec-miss, env-fail +- qa (internal to attempt 1): the spec-mandated boot on port 5199 500s `/canvas1` because `src/server/constants.ts` hardcodes the dev `API_PORT` to 5173 and `src/services/origin.ts` builds the SSR origin from it; the harness reran the same `qa-run.ts` on a fresh strictPort server at 5173 and passed, with the deviation documented in the harness (`factory/logs/issue-4/qa-1.log`) — tags: env-fail + +### Root cause + +The first run escalated because the factory runner invoked the spec station with a `--dir` flag the installed `opencode` CLI does not recognize, so the CLI exited before the agent ran and no spec was written; the reset rerun then passed every station on its first attempt. + +### What went well + +The rerun was one-pass end to end: the tester's red phase failed exactly on the 9 new tests (`factory/logs/issue-4/red.log`), implement went green on attempt 1 (119/119 in `factory/logs/issue-4/gate-1.log`), and review approved in round 1. QA caught that the spec's 20× CPU throttle plus a bare 4 s sleep would have passed vacuously (fps stayed 4 chars on this box) and strengthened the probe to a left-edge poll at 100× throttle before reporting pass. The spec also caught a real gap the issue text glossed over — the `"00.0"` placeholder under-covers the fps box — and flagged the interpretation for the reviewer. + +### Proposal + +none + +### Merge outcome + +Filled later by `factory/retro.sh --merged`. + +- merged: +- human edits: none | spec | tests | code | other