pipes: cache board geometry and colour-label paint (#ux-audit)
- Commit
524306c2ecdf191c1bf8da2ccd5e1aedc9c26322- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 01:13 UTC (23 days ago)
- Parents
2e8a6cb
Symptom: dragging a pipe on a large board did a full board-geometry pass on every drag step, and colour-blind mode allocated a new android.graphics.Paint for every endpoint label on every frame. Root cause: GameBoard recomposes whenever the active path changes, i.e. on every cell the finger enters. Its body recomputed the content bounds (several filterKeys/map passes over renderPositions), the centring offsets and a Rect per cell inline, and drawColorLabel built a fresh Paint per call. Fix: - New ui/BoardGeometry.kt. BoardLayout holds the level's layout in cell units (maxDim, centring offsets, render-position shift) and is remembered per level. BoardGeometry scales it to pixels (cell rects, board bounds) and owns hitTest/hitTestDrag; it is remembered per (layout, cellSizePx). The maths is moved verbatim from GameBoard. - ColorLabelPaint wraps one reusable Paint; GameBoard remembers one and passes it to drawColorLabel, which now only updates colour and text size. The parameter defaults to a fresh instance so existing callers keep working. User-visible effect: none intended beyond smoother drags on big boards (14x14, 17 colours) and less GC churn in colour-blind mode. Verification: new BoardGeometryTest covers square rect/hit-test maths, rescaling one layout at two cell sizes, centring of irregular shapes, holes not being drag targets, and hex nearest-centre hits; existing PipesScreensTest board renders still pass.
Diff
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardGeometry.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardGeometry.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardGeometry.ktnew file mode 100644index 0000000000..73e4eb0f6a--- /dev/null+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardGeometry.kt@@ -0,0 +1,138 @@+package com.vayunmathur.games.pipes.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.LevelData++/**+ * The board's layout in cell units, independent of the pixel size it is drawn at.+ *+ * Computed once per level: scanning every cell for the bounding box is cheap once, but+ * the board recomposes on every drag step, so it must not run per frame.+ */+class BoardLayout(val levelData: LevelData) {+ /** Board side length in cells: the canvas is square and fits this many cells across. */+ val maxDim: Float++ private val shiftX: Float+ private val shiftY: Float+ private val offsetCol: Float+ private val offsetRow: Float++ init {+ val positions = levelData.renderPositions?.filterKeys { it in levelData.cells }?.values+ val hasPositions = levelData.renderPositions != null && levelData.cells.isNotEmpty()+ val (contentW, contentH) = if (hasPositions && !positions.isNullOrEmpty()) {+ (positions.maxOf { it.x } - positions.minOf { it.x } + 1f) to+ (positions.maxOf { it.y } - positions.minOf { it.y } + 1f)+ } else if (hasPositions) {+ 1f to 1f+ } else {+ levelData.cols.toFloat() to levelData.rows.toFloat()+ }+ // Hex rows overlap vertically (0.866 spacing) so shrink slightly to avoid clipping.+ val hexShrink = if (levelData.grid == "hex") 0.92f else 1f+ val effectiveMaxDim = maxOf(contentW, contentH, 1f) / hexShrink+ maxDim = maxOf(maxOf(levelData.rows, levelData.cols).toFloat(), effectiveMaxDim)++ // Center the board within the square canvas using the actual cells' bounding+ // box, so non-square / non-rectangular shapes aren't stuck in the top-left.+ // Render-position layouts are shifted so their minimum sits at 0 instead.+ if (levelData.renderPositions != null || levelData.cells.isEmpty()) {+ offsetCol = 0f+ offsetRow = 0f+ } else {+ val minRow = levelData.cells.minOf { it.row }+ val minCol = levelData.cells.minOf { it.col }+ val usedCols = levelData.cells.maxOf { it.col } - minCol + 1+ val usedRows = levelData.cells.maxOf { it.row } - minRow + 1+ offsetCol = (maxDim - usedCols) / 2f - minCol+ offsetRow = (maxDim - usedRows) / 2f - minRow+ }+ if (hasPositions && !positions.isNullOrEmpty()) {+ shiftX = (maxDim - contentW) / 2f - positions.minOf { it.x }+ shiftY = (maxDim - contentH) / 2f - positions.minOf { it.y }+ } else {+ shiftX = 0f+ shiftY = 0f+ }+ }++ /** Top-left corner of [cell] in cell units. */+ fun origin(cell: CellPos): Offset {+ val pos = levelData.renderPositions?.get(cell)+ return if (pos != null) {+ Offset(pos.x + shiftX, pos.y + shiftY)+ } else {+ Offset(cell.col + offsetCol, cell.row + offsetRow)+ }+ }+}++/**+ * [BoardLayout] scaled to pixels, plus hit-testing.+ *+ * Every touch handler must use the geometry of the size the board is drawn at *now*:+ * rebuild this whenever [cellSizePx] changes (rotation, fold, window resize).+ */+class BoardGeometry(val layout: BoardLayout, val cellSizePx: Float) {+ val levelData: LevelData get() = layout.levelData+ val isHex: Boolean = layout.levelData.grid == "hex"++ val cellRects: Map<CellPos, Rect> = layout.levelData.cells.associateWith { cell ->+ val o = layout.origin(cell)+ Rect(Offset(o.x * cellSizePx, o.y * cellSizePx), Size(cellSizePx, cellSizePx))+ }++ val boardBounds: Rect = if (cellRects.isEmpty()) Rect.Zero else Rect(+ left = cellRects.values.minOf { it.left },+ top = cellRects.values.minOf { it.top },+ right = cellRects.values.maxOf { it.right },+ bottom = cellRects.values.maxOf { it.bottom },+ )++ fun hitTest(offset: Offset): CellPos? {+ if (!isHex) {+ return cellRects.entries.firstOrNull { (_, rect) -> rect.contains(offset) }?.key+ }+ // Hex: nearest center within the hex radius wins (rects overlap vertically).+ val radius = cellSizePx * HEX_HIT_RADIUS+ var best: CellPos? = null+ var bestDist = Float.MAX_VALUE+ for ((cell, rect) in cellRects) {+ val d = (rect.center - offset).getDistanceSquared()+ if (d < bestDist && d <= radius * radius) {+ bestDist = d+ best = cell+ }+ }+ return best ?: cellRects.entries.firstOrNull { (_, rect) -> rect.contains(offset) }?.key+ }++ /**+ * While dragging, a finger that leaves the board keeps driving the border cell nearest+ * to it, so the user doesn't have to come back inside to continue the pipe.+ */+ fun hitTestDrag(offset: Offset): CellPos? {+ hitTest(offset)?.let { return it }+ if (cellRects.isEmpty() || boardBounds.contains(offset)) return null+ return cellRects.entries.minWithOrNull(+ compareBy(+ { squaredDistanceToRect(it.value, offset) },+ { (it.value.center - offset).getDistanceSquared() },+ )+ )?.key+ }++ private companion object {+ const val HEX_HIT_RADIUS = 0.62f+ }+}++private fun squaredDistanceToRect(rect: Rect, point: Offset): Float {+ val dx = maxOf(rect.left - point.x, 0f, point.x - rect.right)+ val dy = maxOf(rect.top - point.y, 0f, point.y - rect.bottom)+ return dx * dx + dy * dy+}
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.ktindex 88292ae257..c694ddf10f 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt@@ -4,12 +4,12 @@ import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect-import androidx.compose.ui.geometry.Size import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalDensity import com.vayunmathur.games.pipes.data.CellPos import com.vayunmathur.games.pipes.data.LevelData import com.vayunmathur.games.pipes.platform.PipesGameState@@ -29,102 +29,15 @@ fun GameBoard( ) { BoxWithConstraints(modifier = modifier, contentAlignment = Alignment.Center) { val boardSize = minOf(maxWidth, maxHeight)- // For staggered hex layouts contentW/H come from renderPositions bounds, not rows/cols.- val renderPositions = levelData.renderPositions- val hasRenderPositions = renderPositions != null- val (contentW, contentH) = if (hasRenderPositions && levelData.cells.isNotEmpty()) {- val xs = renderPositions.filterKeys { it in levelData.cells }.values.map { it.x }- val ys = renderPositions.filterKeys { it in levelData.cells }.values.map { it.y }- if (xs.isEmpty()) 1f to 1f else (xs.maxOrNull()!! - xs.minOrNull()!! + 1f) to (ys.maxOrNull()!! - ys.minOrNull()!! + 1f)- } else {- levelData.cols.toFloat() to levelData.rows.toFloat()- }- // Hex rows overlap vertically (0.866 spacing) so shrink slightly to avoid clipping.- val hexShrink = if (levelData.grid == "hex") 0.92f else 1f- val effectiveMaxDim = maxOf(contentW, contentH, 1f) / hexShrink- val maxDim = maxOf(maxOf(levelData.rows, levelData.cols).toFloat(), effectiveMaxDim)- val cellSizeDp = boardSize / maxDim-- val cellSizePx = with(androidx.compose.ui.platform.LocalDensity.current) { cellSizeDp.toPx() }-- // Center the board within the square canvas using the actual cells' bounding- // box, so non-square / non-rectangular shapes aren't stuck in the top-left.- // Skip when explicit render positions are provided.- val (offsetCol, offsetRow) = if (hasRenderPositions || levelData.cells.isEmpty()) {- 0f to 0f- } else {- val minRow = levelData.cells.minOf { it.row }- val maxRow = levelData.cells.maxOf { it.row }- val minCol = levelData.cells.minOf { it.col }- val maxCol = levelData.cells.maxOf { it.col }- val usedCols = maxCol - minCol + 1- val usedRows = maxRow - minRow + 1- val ox = (maxDim - usedCols) / 2f - minCol- val oy = (maxDim - usedRows) / 2f - minRow- ox to oy- }-- // Shift render-position layouts so min sits at 0 and center in the square canvas.- val (shiftX, shiftY) = if (hasRenderPositions && levelData.cells.isNotEmpty()) {- val xs = renderPositions.filterKeys { it in levelData.cells }.values.map { it.x }- val ys = renderPositions.filterKeys { it in levelData.cells }.values.map { it.y }- val minX = xs.minOrNull() ?: 0f- val minY = ys.minOrNull() ?: 0f- val offX = (maxDim - contentW) / 2f - minX- val offY = (maxDim - contentH) / 2f - minY- offX to offY- } else {- 0f to 0f- }-- val cellRects = levelData.cells.associateWith { cell ->- val (x, y) = levelData.renderPositions?.get(cell)?.let { (it.x + shiftX) to (it.y + shiftY) }- ?: ((cell.col + offsetCol) to (cell.row + offsetRow))- Rect(Offset(x * cellSizePx, y * cellSizePx), Size(cellSizePx, cellSizePx))- }-- val isHex = levelData.grid == "hex"-- fun hitTest(offset: Offset): CellPos? {- if (!isHex) {- return cellRects.entries.firstOrNull { (_, rect) ->- rect.contains(offset)- }?.key- }- // Hex: nearest center within the hex radius wins (rects overlap vertically).- var best: CellPos? = null- var bestDist = Float.MAX_VALUE- for ((cell, rect) in cellRects) {- val d = (rect.center - offset).getDistanceSquared()- if (d < bestDist && d <= (cellSizePx * 0.62f) * (cellSizePx * 0.62f)) {- bestDist = d- best = cell- }- }- if (best != null) return best- return cellRects.entries.firstOrNull { (_, rect) -> rect.contains(offset) }?.key- }-- val boardBounds = if (cellRects.isEmpty()) Rect.Zero else Rect(- left = cellRects.values.minOf { it.left },- top = cellRects.values.minOf { it.top },- right = cellRects.values.maxOf { it.right },- bottom = cellRects.values.maxOf { it.bottom }- )-- // While dragging, a finger that leaves the board keeps driving the border- // cell nearest to it, so the user doesn't have to come back inside to- // continue the pipe.- fun hitTestDrag(offset: Offset): CellPos? {- hitTest(offset)?.let { return it }- if (cellRects.isEmpty() || boardBounds.contains(offset)) return null- return cellRects.entries.minWithOrNull(- compareBy(- { squaredDistanceToRect(it.value, offset) },- { (it.value.center - offset).getDistanceSquared() }- )- )?.key- }+ // Layout and pixel geometry are cached: the board recomposes on every drag step, and+ // rescanning every cell for bounds and rects each time is wasted work.+ val layout = remember(levelData) { BoardLayout(levelData) }+ val cellSizeDp = boardSize / layout.maxDim+ val cellSizePx = with(LocalDensity.current) { cellSizeDp.toPx() }+ val geometry = remember(layout, cellSizePx) { BoardGeometry(layout, cellSizePx) }+ val cellRects = geometry.cellRects+ val isHex = geometry.isHex+ val labelPaint = remember { ColorLabelPaint() } Canvas( modifier = Modifier@@ -138,11 +51,11 @@ fun GameBoard( when { event.changes.any { it.pressed && !it.previousPressed } -> {- val cell = hitTest(pos)+ val cell = geometry.hitTest(pos) if (cell != null) onStartDraw(cell) } event.changes.any { it.pressed } -> {- val cell = hitTestDrag(pos)+ val cell = geometry.hitTestDrag(pos) if (cell != null) onExtendPath(cell) } event.changes.any { !it.pressed && it.previousPressed } -> {@@ -221,19 +134,13 @@ fun GameBoard( for (cell in ep.cells) { val rect = cellRects[cell] ?: continue drawEndpointBall(rect, color)- if (colorblind) drawColorLabel(rect, ep.colorIndex)+ if (colorblind) drawColorLabel(rect, ep.colorIndex, labelPaint) } } } } } -private fun squaredDistanceToRect(rect: Rect, point: Offset): Float {- val dx = maxOf(rect.left - point.x, 0f, point.x - rect.right)- val dy = maxOf(rect.top - point.y, 0f, point.y - rect.bottom)- return dx * dx + dy * dy-}- private fun directionBetween(from: CellPos, to: CellPos): Direction? { return when { to.row < from.row -> Direction.UP
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.ktindex 23d0253029..0646f2b120 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.kt@@ -144,20 +144,32 @@ fun DrawScope.drawWrapMarker(cellRect: Rect, dir: Direction, color: Color) { drawCircle(color = color, radius = s * 0.9f, center = Offset(ex, ey)) } +/**+ * The text paint behind [drawColorLabel], kept by the caller across frames. Allocating a+ * Paint per label per frame churned the GC on every drag step in colour-blind mode.+ */+class ColorLabelPaint {+ val paint: android.graphics.Paint = android.graphics.Paint().apply {+ isAntiAlias = true+ textAlign = android.graphics.Paint.Align.CENTER+ typeface = android.graphics.Typeface.DEFAULT_BOLD+ }+}+ /** Colorblind aid: draw the flow's identifying letter centered in the cell. */-fun DrawScope.drawColorLabel(cellRect: Rect, colorIndex: Int) {+fun DrawScope.drawColorLabel(+ cellRect: Rect,+ colorIndex: Int,+ labelPaint: ColorLabelPaint = ColorLabelPaint(),+) { val letter = ('A' + (colorIndex % 26)).toString() val onColor = PIPE_COLORS[colorIndex % PIPE_COLORS.size] // Pick black/white text for contrast against the flow color. val luminance = 0.299f * onColor.red + 0.587f * onColor.green + 0.114f * onColor.blue val textColor = if (luminance > 0.6f) android.graphics.Color.BLACK else android.graphics.Color.WHITE- val paint = android.graphics.Paint().apply {- isAntiAlias = true- this.color = textColor- textAlign = android.graphics.Paint.Align.CENTER- textSize = cellRect.width * 0.5f- typeface = android.graphics.Typeface.DEFAULT_BOLD- }+ val paint = labelPaint.paint+ paint.color = textColor+ paint.textSize = cellRect.width * 0.5f val cx = cellRect.center.x val cy = cellRect.center.y - (paint.descent() + paint.ascent()) / 2f drawContext.canvas.nativeCanvas.drawText(letter, cx, cy, paint)
games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/BoardGeometryTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/BoardGeometryTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/BoardGeometryTest.ktnew file mode 100644index 0000000000..e1edc2dfd1--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/BoardGeometryTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.games.pipes.ui++import androidx.compose.ui.geometry.Offset+import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.EndpointPair+import com.vayunmathur.games.pipes.data.LevelData+import com.vayunmathur.games.pipes.data.computeAdjacency+import com.vayunmathur.games.pipes.data.computeHexAdjacency+import com.vayunmathur.games.pipes.data.hexRenderPositions+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertSame++class BoardGeometryTest {+ private fun rect(rows: Int, cols: Int) =+ buildSet { for (r in 0 until rows) for (c in 0 until cols) add(CellPos(r, c)) }++ private fun level(cells: Set<CellPos>, rows: Int, cols: Int) = LevelData(+ "g", rows, cols, cells, computeAdjacency(cells), null,+ listOf(EndpointPair(0, listOf(cells.first(), cells.last()))), emptySet(), 1,+ )++ @Test fun squareCellsMapToPixelRectsAndBack() {+ val geo = BoardGeometry(BoardLayout(level(rect(5, 5), 5, 5)), 60f)+ assertEquals(5f, geo.layout.maxDim)+ val r = geo.cellRects.getValue(CellPos(2, 3))+ assertEquals(180f, r.left); assertEquals(120f, r.top); assertEquals(60f, r.width)+ assertEquals(CellPos(2, 3), geo.hitTest(Offset(190f, 130f)))+ assertNull(geo.hitTest(Offset(-5f, 10f)))+ // Off the board while dragging: the nearest border cell keeps driving the stroke+ assertEquals(CellPos(0, 4), geo.hitTestDrag(Offset(400f, -40f)))+ }++ @Test fun sameLayoutRescalesWithCellSize() {+ val layout = BoardLayout(level(rect(5, 5), 5, 5))+ val big = BoardGeometry(layout, 60f)+ val small = BoardGeometry(layout, 30f)+ assertSame(big.layout, small.layout)+ val p = Offset(135f, 15f)+ assertEquals(CellPos(0, 2), big.hitTest(p))+ assertEquals(CellPos(0, 4), small.hitTest(p))+ }++ @Test fun irregularShapesAreCentredAndHolesAreNotDragTargets() {+ // A 3-wide column inside a 5x5 frame is centred horizontally.+ val cells = buildSet { for (r in 0 until 5) for (c in 1..3) add(CellPos(r, c)) }+ val geo = BoardGeometry(BoardLayout(level(cells, 5, 5)), 10f)+ assertEquals(10f, geo.cellRects.getValue(CellPos(0, 1)).left)+ val holed = rect(3, 3) - CellPos(1, 1)+ val g2 = BoardGeometry(BoardLayout(level(holed, 3, 3)), 10f)+ assertNull(g2.hitTestDrag(Offset(15f, 15f)))+ }++ @Test fun hexUsesNearestCentre() {+ val cells = rect(3, 3)+ val hex = LevelData(+ "h", 3, 3, cells, computeHexAdjacency(cells), hexRenderPositions(cells),+ listOf(EndpointPair(0, listOf(CellPos(0, 0), CellPos(2, 2)))), emptySet(), 1, emptyMap(), "hex",+ )+ val geo = BoardGeometry(BoardLayout(hex), 40f)+ for ((cell, r) in geo.cellRects) assertEquals(cell, geo.hitTest(r.center))+ }+}