From 902a8ad07537af87ff5578d514f0f718d907a4d1 Mon Sep 17 00:00:00 2001 From: Miley Chandonnet Date: Sat, 17 Oct 2026 19:01:51 +0900 Subject: [PATCH] =?UTF-8?q?PHO-83/#153=20T12=20=C2=B7=20D:=20Modifier.lumo?= =?UTF-8?q?sPointer=20and=20the=20LumosOrb=20plumbing=20=E2=80=94=20hover,?= =?UTF-8?q?=20touch,=20scroll=20pass-through,=20the=20pointer=20on=20Lumos?= =?UTF-8?q?CanvasFrame;=20LumosInputPreview=20and=20the=20desktop=20record?= =?UTF-8?q?ing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `Modifier.lumosPointer(tiltDegrees, onInput)` in :phosphor-lumos-compose: a Modifier.Node over SuspendingPointerInputModifierNode that reads the Final pass and never consumes. Mouse and stylus report on Enter/Move, NONE on Exit, pressed follows the button; touch reports Press/Move pressed and NONE on Release. A consumed change reports NONE and waits for every pointer to lift. The handler's finally reports NONE. A new lambda never restarts it. - The mapping inverts PixelLattice: x = 2px/w − 1, y = 1 − 2py/h, then un-tilted onto the front of the unit sphere. - `LumosCanvasFrame.pointer` (@Transient, canvas px). `PixelLattice.project` takes an optional pointer, defaulting to the frame's input, and `canvasPointer` is the forward mapping, re-tilted and placed in the viewport. - `OrbStepper.setInput` hands the pointer to the source and lays the latest one over every frame projected after it, live, still or recorded; NONE clears a stale live pointer. `LumosDriver.setInput` / `onInput` wrap it. - `LumosOrb` carries the modifier on its Box and tells the source NONE when the driver is disposed (orb gone or source replaced). - `LumosInputPreview`: three interactive THINKING orbs — alone, centre, upper right. `LumosInputPreviewTest` writes the strip and a 3 s, 30 fps GIF of a scripted pointer sweep driven through LumosOrb with real pointer events. - `SteppedScene` gains `sendPointerEvent` and `sendTouch`. - README: the pointer section with a compiled `PointedCanvas` snippet. Co-Authored-By: Claude Fable 5.1 --- README.md | 44 ++++ .../phosphor/lumos/compose/LumosDriver.kt | 13 +- .../lumos/compose/LumosInputPreview.kt | 68 ++++++ .../socket/phosphor/lumos/compose/LumosOrb.kt | 18 +- .../phosphor/lumos/compose/LumosPointer.kt | 163 +++++++++++++ .../phosphor/lumos/compose/LumosDriverTest.kt | 26 +++ .../lumos/compose/LumosPointerMappingTest.kt | 75 ++++++ .../phosphor/lumos/compose/GifWriter.kt | 87 +++++++ .../lumos/compose/LumosInputPreviewTest.kt | 217 ++++++++++++++++++ .../lumos/compose/LumosOrbPointerTest.kt | 213 +++++++++++++++++ .../phosphor/lumos/compose/SteppedScene.kt | 41 +++- .../lumos/compose/docs/ReadmeLumosPointer.kt | 41 ++++ .../compose/docs/ReadmeLumosQuickStartTest.kt | 46 +++- .../link/socket/phosphor/lumos/OrbStepper.kt | 21 +- .../phosphor/lumos/frame/LumosCanvasFrame.kt | 8 + .../phosphor/lumos/projection/PixelLattice.kt | 45 +++- .../socket/phosphor/lumos/OrbStepperTest.kt | 59 ++++- .../projection/PixelLatticePointerTest.kt | 140 +++++++++++ 18 files changed, 1312 insertions(+), 13 deletions(-) create mode 100644 phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosInputPreview.kt create mode 100644 phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosPointer.kt create mode 100644 phosphor-lumos-compose/src/commonTest/kotlin/link/socket/phosphor/lumos/compose/LumosPointerMappingTest.kt create mode 100644 phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/GifWriter.kt create mode 100644 phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/LumosInputPreviewTest.kt create mode 100644 phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/LumosOrbPointerTest.kt create mode 100644 phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosPointer.kt create mode 100644 phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/projection/PixelLatticePointerTest.kt diff --git a/README.md b/README.md index 1b519ff..0f6264e 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,50 @@ fun ThinkingOrb() { The orb stops while it is scrolled off screen or its window is in the background, holds still when the platform asks for reduced motion, and is one labelled image to a screen reader — or hidden from one, without a label. Orbs in the same state share a clock, so a column of them breathes together. To drive a runtime and frame builder you already own, wrap them in `LiveFrameSource(runtime, builder)`; to play a recording from `:phosphor-trace`, open it with `asFrameSource()`. The snippet is compiled by `ReadmeLumosQuickStartTest`. +The orb answers the pointer on every target — hover where the platform has it, touch everywhere — and takes no gesture from its parents, so an orb in a scrolling column still scrolls it. Make the scene `interactive` and its cells part around the pointer; the projected frame carries the pointer in pixels for a material's light. A consumer drawing `LumosCanvas` directly gets the same plumbing from one modifier, `Modifier.lumosPointer`, which reports the pointer in the orb's view space and never consumes it: + +```kotlin +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import link.socket.phosphor.lumos.LiveFrameSource +import link.socket.phosphor.lumos.LumosRenderConfig +import link.socket.phosphor.lumos.compose.LumosCanvas +import link.socket.phosphor.lumos.compose.lumosPointer +import link.socket.phosphor.lumos.projection.PixelLattice +import link.socket.phosphor.palette.AtmospherePresets + +@Composable +fun PointedCanvas() { + // 1. An interactive scene: its cells part around the pointer + val source = remember { LiveFrameSource(AtmospherePresets.THINKING, LumosRenderConfig(interactive = true)) } + val lattice = remember { PixelLattice(widthPx = 160, heightPx = 160, voxelRadiusPx = 4f) } + + // 2. Your own clock: project each frame as it is stepped + var frame by remember { mutableStateOf(lattice.project(source.next(0f))) } + LaunchedEffect(source) { + var last = withFrameNanos { it } + while (true) { + withFrameNanos { now -> + frame = lattice.project(source.next((now - last) / 1_000_000_000f)) + last = now + } + } + } + + // 3. The pointer, in the orb's view space, from one modifier that never consumes it; + // the projected frame then carries it in pixels for a material's light + LumosCanvas(frame, Modifier.size(160.dp).lumosPointer { source.setInput(it) }) +} +``` + ### The orb becomes a control `:phosphor-lumos-surface` lets the orb's cells leave their slot, fly to a real layout element and become it, with the element keeping focus, click and semantics throughout and nothing ticking once it is solid: diff --git a/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosDriver.kt b/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosDriver.kt index e6cb24b..768aed9 100644 --- a/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosDriver.kt +++ b/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosDriver.kt @@ -10,12 +10,14 @@ import link.socket.phosphor.lumos.OrbStepper import link.socket.phosphor.lumos.PlatformMotionPreference import link.socket.phosphor.lumos.frame.LumosCanvasFrame import link.socket.phosphor.lumos.probe.FrameProbe +import link.socket.phosphor.signal.LumosInput /** * [OrbStepper] behind [LumosOrb], with the frame it draws held in Compose state so the canvas * follows it. The rules about time are the stepper's — the step, the cap, aligning on a rejoin * ([LumosFrameSource.align]) and on a look change ([LumosFrameSource.alignLook]) — and this only - * hands each new frame to Compose. + * hands each new frame to Compose. The pointer is the stepper's too ([OrbStepper.setInput]): it + * goes to the source, and the latest one is laid over every frame published, live or recorded. * * Main-thread only, like the source it steps. */ @@ -36,6 +38,9 @@ internal class LumosDriver( /** The frame callback a frame loop hands to `withFrameNanos`, allocated once. */ val onFrame: (Long) -> Unit = { frameTimeNanos -> step(frameTimeNanos) } + /** The input callback [lumosPointer] is given, allocated once. */ + val onInput: (LumosInput) -> Unit = { input -> setInput(input) } + /** See [OrbStepper.update]. */ fun update( config: LumosConfig, @@ -60,6 +65,12 @@ internal class LumosDriver( /** See [OrbStepper.pollHeld]. */ fun pollHeld() = publish(stepper.pollHeld()) + /** + * See [OrbStepper.setInput]. Publishes nothing: a pointer move while the orb is paused or + * under reduced motion is lit on the next frame drawn for another reason. + */ + fun setInput(input: LumosInput) = stepper.setInput(input) + // Only a new projection is written, so an unchanged frame costs Compose nothing. private fun publish(frame: LumosCanvasFrame?) { if (frame != null) canvasFrame = frame diff --git a/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosInputPreview.kt b/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosInputPreview.kt new file mode 100644 index 0000000..df308d9 --- /dev/null +++ b/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosInputPreview.kt @@ -0,0 +1,68 @@ +package link.socket.phosphor.lumos.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import link.socket.phosphor.lumos.LiveFrameSource +import link.socket.phosphor.lumos.LumosConfig +import link.socket.phosphor.lumos.LumosRenderConfig +import link.socket.phosphor.math.Vector2 +import link.socket.phosphor.palette.AtmospherePresets +import link.socket.phosphor.signal.LumosInput + +/** + * Preview composable for the pointer (PHO-83): three `interactive` THINKING orbs side by side — + * nothing pointing, a pointer at the centre, and a pointer upper right — each settled under its + * pointer, so the strip shows the cells parted around it. The pointer is handed to each scene + * directly, as [Modifier.lumosPointer] would hand it from a real pointer. + * + * Like [LumosOrbPreview], a preview for a host project's preview pane or sample app, not a test. + */ +@Composable +fun LumosInputPreview() { + Row(horizontalArrangement = Arrangement.spacedBy(INPUT_PREVIEW_GAP)) { + for (pointer in INPUT_PREVIEW_POINTERS) PreviewInputOrb(pointer) + } +} + +@Composable +private fun PreviewInputOrb(pointer: Vector2?) { + val source = + remember(pointer) { + LiveFrameSource(AtmospherePresets.THINKING, INPUT_PREVIEW_RENDER_CONFIG).also { live -> + live.next(INPUT_PREVIEW_WARM_UP_SECONDS) + live.setInput(LumosInput(pointer = pointer)) + // Long enough for the cells to part and come to rest around the pointer. + repeat(INPUT_PREVIEW_SETTLE_FRAMES) { live.next(INPUT_PREVIEW_FRAME_SECONDS) } + } + } + LumosOrb( + source = source, + config = LumosConfig(label = if (pointer == null) "Lumos, alone" else "Lumos, pointed at"), + modifier = Modifier.size(INPUT_PREVIEW_SIZE), + backgroundColor = INPUT_PREVIEW_BACKGROUND, + ) +} + +/** Where each orb of the strip is pointed at, in the orb's view space; null for nothing pointing. */ +val INPUT_PREVIEW_POINTERS: List = listOf(null, Vector2(0f, 0f), Vector2(0.5f, 0.5f)) + +/** Each orb's size. */ +val INPUT_PREVIEW_SIZE: Dp = 200.dp + +/** The gap between orbs. */ +val INPUT_PREVIEW_GAP: Dp = 16.dp + +/** The strip's background. */ +val INPUT_PREVIEW_BACKGROUND: Color = Color(0xFF111111) + +private val INPUT_PREVIEW_RENDER_CONFIG = LumosRenderConfig(interactive = true) +private const val INPUT_PREVIEW_WARM_UP_SECONDS = 1.5f +private const val INPUT_PREVIEW_FRAME_SECONDS = 1f / 30f +private const val INPUT_PREVIEW_SETTLE_FRAMES = 45 diff --git a/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosOrb.kt b/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosOrb.kt index ce02e56..9b20784 100644 --- a/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosOrb.kt +++ b/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosOrb.kt @@ -3,6 +3,7 @@ package link.socket.phosphor.lumos.compose import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.SideEffect @@ -35,6 +36,7 @@ import link.socket.phosphor.lumos.Material import link.socket.phosphor.lumos.PlatformMotionPreference import link.socket.phosphor.lumos.SurfaceStyle import link.socket.phosphor.lumos.probe.FrameProbe +import link.socket.phosphor.signal.LumosInput /** * The [LookClock] the orbs below share, so orbs of one look breathe together. One per process @@ -69,6 +71,13 @@ val LocalLookClock: ProvidableCompositionLocal = staticCompositionLoc * look's phase alone ([LumosFrameSource.alignLook]), so its spin never snaps. * - **Screen readers.** With a [LumosConfig.label], the orb is one image described by it. Without * one, screen readers skip it. + * - **The pointer.** The orb answers the pointer on every target — hover where the platform has + * it, touch everywhere — through [Modifier.lumosPointer], and takes no gesture from its parents: + * an orb in a scrolling column still scrolls it. What it reads goes to + * [LumosFrameSource.setInput], so a live scene that is `interactive` parts its cells around it, + * and the latest pointer is laid over every frame drawn, live or recorded, for a material's + * light. When the orb leaves composition, or its source is replaced, the source is told the + * pointer has gone. * * One orb per source: a source stepped by two orbs runs twice as fast. To show one orb in two * places, project its frame once and draw it with two [LumosCanvas]es. @@ -124,6 +133,12 @@ fun LumosOrb( } } + // A source left behind — replaced, or the orb gone — is told the pointer has gone, so no + // ghost pointer keeps its cells parted. + DisposableEffect(driver) { + onDispose { driver.setInput(LumosInput.NONE) } + } + Box( modifier = modifier @@ -131,7 +146,8 @@ fun LumosOrb( .onSizeChanged { driver.resize(it.width, it.height) } .onGloballyPositioned { coordinates -> onScreen = coordinates.isAttached && !coordinates.boundsInWindow().isEmpty - }, + } + .lumosPointer(config.tiltDegrees, driver.onInput), ) { HeldCanvas(driver, backgroundColor, showHalo, showGlyphOverlay, probe, config.style, config.material) } diff --git a/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosPointer.kt b/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosPointer.kt new file mode 100644 index 0000000..1ef24d6 --- /dev/null +++ b/phosphor-lumos-compose/src/commonMain/kotlin/link/socket/phosphor/lumos/compose/LumosPointer.kt @@ -0,0 +1,163 @@ +package link.socket.phosphor.lumos.compose + +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.AwaitPointerEventScope +import androidx.compose.ui.input.pointer.PointerEvent +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerInputChange +import androidx.compose.ui.input.pointer.PointerInputScope +import androidx.compose.ui.input.pointer.PointerType +import androidx.compose.ui.input.pointer.SuspendingPointerInputModifierNode +import androidx.compose.ui.node.DelegatingNode +import androidx.compose.ui.node.ModifierNodeElement +import androidx.compose.ui.platform.InspectorInfo +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.max +import kotlin.math.sin +import kotlin.math.sqrt +import link.socket.phosphor.math.Vector2 +import link.socket.phosphor.signal.LumosInput + +/** + * Report where the pointer is over this node, as a [LumosInput] in the orb's view space. Never + * consumes. + * + * [LumosOrb] carries this itself. It is for a consumer who draws [LumosCanvas] directly and wants + * the same plumbing: hand what it reports to the source's `setInput`, and the next frame answers + * it — the cells part when the scene is `interactive`, a gazing form looks, and the frame carries + * the pointer for a material's light. + * + * - **Hover where the platform has it, touch everywhere.** A mouse or stylus reports on `Enter` + * and every `Move`, and `NONE` on `Exit`; a button press does not end the hover, `pressed` + * follows the button. A touch reports on `Press` and `Move` with `pressed = true`, and `NONE` on + * `Release`. + * - **Never a gesture taken from a parent.** The node reads the final pass and consumes nothing, + * so an orb in a scrolling column still scrolls it. A change someone else consumed — a parent's + * scroll past touch slop — reports `NONE`, and the node then waits for every pointer to lift. + * - **No ghost pointer.** When the node leaves composition it reports `NONE`, so no cells stay + * parted around a pointer that is no longer there. + * - A new [onInput] on recomposition is taken up without restarting the handler. + * + * The mapping is the inverse of [link.socket.phosphor.lumos.projection.PixelLattice]'s projection: + * `x = 2·px / w − 1`, `y = 1 − 2·py / h`, with `+y` up, then — for a [tiltDegrees] other than 0 — + * un-tilted onto the front of the unit sphere, `y = sy·cos t + √(max(0, 1 − x² − sy²))·sin t`. + * That is exact on the front surface, and exact everywhere at the default tilt of 0. A point past + * the orb's square is reported as it is: the pointer can stray past the orb. + * + * Each pointer event allocates one [LumosInput] and one [Vector2]. + * + * @param tiltDegrees The tilt the orb is projected with, `LumosConfig.tiltDegrees`, so the pointer + * is read on the surface the viewer sees. Must be finite. + * @param onInput Where the pointer is, each time it changes. + */ +fun Modifier.lumosPointer( + tiltDegrees: Float = 0f, + onInput: (LumosInput) -> Unit, +): Modifier { + require(tiltDegrees.isFinite()) { "tiltDegrees must be finite, was $tiltDegrees" } + return this then LumosPointerElement(tiltDegrees, onInput) +} + +/** + * A pointer at ([px], [py]) on a node [width] × [height] pixels across, in the orb's view space: + * `[-1, 1]` across the node with `+y` up, un-tilted onto the front of the unit sphere by the tilt + * whose cosine and sine are [cosTilt] and [sinTilt]. See [Modifier.lumosPointer]. + */ +internal fun viewSpacePointer( + px: Float, + py: Float, + width: Float, + height: Float, + cosTilt: Float = 1f, + sinTilt: Float = 0f, +): Vector2 { + val x = 2f * px / width - 1f + val sy = 1f - 2f * py / height + if (sinTilt == 0f) return Vector2(x, sy) + val z = sqrt(max(0f, 1f - x * x - sy * sy)) + return Vector2(x, sy * cosTilt + z * sinTilt) +} + +private data class LumosPointerElement( + val tiltDegrees: Float, + val onInput: (LumosInput) -> Unit, +) : ModifierNodeElement() { + override fun create(): LumosPointerNode = LumosPointerNode(tiltDegrees, onInput) + + override fun update(node: LumosPointerNode) { + node.onInput = onInput + node.tilt(tiltDegrees) + } + + override fun InspectorInfo.inspectableProperties() { + name = "lumosPointer" + properties["tiltDegrees"] = tiltDegrees + } +} + +private class LumosPointerNode( + tiltDegrees: Float, + var onInput: (LumosInput) -> Unit, +) : DelegatingNode() { + private var tiltDegrees: Float = tiltDegrees + private var cosTilt: Float = cos(tiltDegrees * DEGREES_TO_RADIANS).toFloat() + private var sinTilt: Float = sin(tiltDegrees * DEGREES_TO_RADIANS).toFloat() + + init { + delegate(SuspendingPointerInputModifierNode { track() }) + } + + // The handler reads the tilt on each event, so a new tilt never restarts it. + fun tilt(degrees: Float) { + if (degrees == tiltDegrees) return + tiltDegrees = degrees + cosTilt = cos(degrees * DEGREES_TO_RADIANS).toFloat() + sinTilt = sin(degrees * DEGREES_TO_RADIANS).toFloat() + } + + private suspend fun PointerInputScope.track() { + awaitPointerEventScope { + try { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Final) + val change = event.changes.firstOrNull() ?: continue + if (change.isConsumed) { + onInput(LumosInput.NONE) + awaitLift(event) + continue + } + val hovers = change.type == PointerType.Mouse || change.type == PointerType.Stylus + when (event.type) { + PointerEventType.Exit -> onInput(LumosInput.NONE) + PointerEventType.Release -> if (hovers) report(change) else onInput(LumosInput.NONE) + PointerEventType.Enter, PointerEventType.Move, PointerEventType.Press -> report(change) + else -> Unit + } + } + } finally { + onInput(LumosInput.NONE) + } + } + } + + // Someone else took the gesture: say nothing more until every pointer has lifted. + private suspend fun AwaitPointerEventScope.awaitLift(consumed: PointerEvent) { + var event = consumed + while (event.changes.any { it.pressed }) event = awaitPointerEvent(PointerEventPass.Final) + } + + private fun AwaitPointerEventScope.report(change: PointerInputChange) { + val width = size.width + val height = size.height + if (width <= 0 || height <= 0) return + val position = change.position + val pointer = viewSpacePointer(position.x, position.y, width.toFloat(), height.toFloat(), cosTilt, sinTilt) + onInput(LumosInput(pointer = pointer, pressed = change.pressed)) + } + + private companion object { + const val DEGREES_TO_RADIANS: Double = PI / 180.0 + } +} diff --git a/phosphor-lumos-compose/src/commonTest/kotlin/link/socket/phosphor/lumos/compose/LumosDriverTest.kt b/phosphor-lumos-compose/src/commonTest/kotlin/link/socket/phosphor/lumos/compose/LumosDriverTest.kt index 9dca7e7..d54f48c 100644 --- a/phosphor-lumos-compose/src/commonTest/kotlin/link/socket/phosphor/lumos/compose/LumosDriverTest.kt +++ b/phosphor-lumos-compose/src/commonTest/kotlin/link/socket/phosphor/lumos/compose/LumosDriverTest.kt @@ -13,6 +13,8 @@ import link.socket.phosphor.lumos.LumosFrameSource import link.socket.phosphor.lumos.VoxelAmbient import link.socket.phosphor.lumos.VoxelCell import link.socket.phosphor.lumos.VoxelFrame +import link.socket.phosphor.math.Vector2 +import link.socket.phosphor.signal.LumosInput /** * What [LumosDriver] adds to the `OrbStepper` it wraps: the frame it draws, in Compose state. @@ -74,11 +76,35 @@ class LumosDriverTest { } } + @Test + fun `the pointer goes to the source and lights the next frame drawn in canvas pixels`() { + val source = StillSource() + val driver = LumosDriver(source, LookClock()) { false } + driver.resize(100, 100) + driver.step(secondsToNanos(1.0)) + val before = assertNotNull(driver.canvasFrame) + + driver.onInput(LumosInput(Vector2(0.5f, 0.5f))) + + assertEquals(listOf(LumosInput(Vector2(0.5f, 0.5f))), source.inputs) + assertSame(before, driver.canvasFrame, "a pointer alone publishes no frame") + + source.frame = frame(tick = 2L) + driver.step(secondsToNanos(1.016)) + assertEquals(Vector2(75f, 25f), assertNotNull(driver.canvasFrame).pointer) + } + private class StillSource( var frame: VoxelFrame = frame(), ) : LumosFrameSource { + val inputs = mutableListOf() + override fun next(dt: Float): VoxelFrame = frame + override fun setInput(input: LumosInput) { + inputs += input + } + override fun still(dt: Float): VoxelFrame = frame } diff --git a/phosphor-lumos-compose/src/commonTest/kotlin/link/socket/phosphor/lumos/compose/LumosPointerMappingTest.kt b/phosphor-lumos-compose/src/commonTest/kotlin/link/socket/phosphor/lumos/compose/LumosPointerMappingTest.kt new file mode 100644 index 0000000..f48f6f9 --- /dev/null +++ b/phosphor-lumos-compose/src/commonTest/kotlin/link/socket/phosphor/lumos/compose/LumosPointerMappingTest.kt @@ -0,0 +1,75 @@ +package link.socket.phosphor.lumos.compose + +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.sin +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import link.socket.phosphor.lumos.projection.PixelLattice +import link.socket.phosphor.math.Vector2 + +/** + * PHO-83: the mapping behind [lumosPointer], from a pixel on the node to the orb's view space, + * inverts [PixelLattice]'s projection: exact everywhere untilted, and on the front of the sphere + * under a tilt. + */ +class LumosPointerMappingTest { + @Test + fun `the centre is the origin and the top-left corner is minus one plus one`() { + assertEquals(Vector2(0f, 0f), viewSpacePointer(100f, 100f, 200f, 200f)) + assertEquals(Vector2(-1f, 1f), viewSpacePointer(0f, 0f, 200f, 200f)) + assertEquals(Vector2(1f, -1f), viewSpacePointer(200f, 200f, 200f, 200f)) + } + + @Test + fun `a pointer past the node strays past the orb`() { + assertEquals(Vector2(1.5f, 1.25f), viewSpacePointer(250f, -25f, 200f, 200f)) + } + + @Test + fun `a 30 degree tilt lifts the front centre by the sine of the tilt`() { + val pointer = viewSpacePointer(100f, 100f, 200f, 200f, COS_TILT, SIN_TILT) + + assertNear(0f, pointer.x, "x") + assertNear(SIN_TILT, pointer.y, "y") + } + + @Test + fun `under a tilt the mapping inverts the lattice's on the front of the sphere`() { + val lattice = PixelLattice(widthPx = 200, heightPx = 200, tiltDegrees = 30f) + val points = listOf(Vector2(0f, 0f), Vector2(0.3f, -0.4f), Vector2(-0.6f, 0.2f), Vector2(0.7f, 0.7f)) + + for (point in points) { + val px = lattice.canvasPointer(point) + val back = viewSpacePointer(px.x, px.y, 200f, 200f, COS_TILT, SIN_TILT) + assertNear(point.x, back.x, "x of $point") + assertNear(point.y, back.y, "y of $point") + } + } + + @Test + fun `untilted the mapping inverts the lattice's everywhere`() { + val lattice = PixelLattice(widthPx = 320, heightPx = 200) + val point = Vector2(1.4f, -1.2f) + + val px = lattice.canvasPointer(point) + val back = viewSpacePointer(px.x, px.y, 320f, 200f) + + assertNear(point.x, back.x, "x") + assertNear(point.y, back.y, "y") + } + + private fun assertNear( + expected: Float, + actual: Float, + label: String, + ) = assertTrue(abs(expected - actual) < 1e-4f, "$label: expected $expected, was $actual") + + private companion object { + val TILT = (30.0 * PI / 180.0) + val COS_TILT = cos(TILT).toFloat() + val SIN_TILT = sin(TILT).toFloat() + } +} diff --git a/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/GifWriter.kt b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/GifWriter.kt new file mode 100644 index 0000000..a3841db --- /dev/null +++ b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/GifWriter.kt @@ -0,0 +1,87 @@ +package link.socket.phosphor.lumos.compose + +import java.awt.image.BufferedImage +import java.io.ByteArrayInputStream +import java.io.File +import javax.imageio.IIOImage +import javax.imageio.ImageIO +import javax.imageio.ImageTypeSpecifier +import javax.imageio.ImageWriter +import javax.imageio.metadata.IIOMetadata +import javax.imageio.metadata.IIOMetadataNode +import javax.imageio.stream.ImageOutputStream +import org.jetbrains.skia.EncodedImageFormat +import org.jetbrains.skia.Image + +/** + * A looping animated GIF written frame by frame through `javax.imageio`, for the recordings the + * previews leave in `build/lumos-previews/`. Test-only: nothing in the library writes images. + * + * @param file Where the GIF goes; its directory is created. + * @param frameMillis How long each frame shows, rounded to the GIF's hundredths of a second. + */ +internal class GifWriter( + file: File, + frameMillis: Int, +) : AutoCloseable { + private val writer: ImageWriter = ImageIO.getImageWritersByFormatName("gif").next() + private val output: ImageOutputStream + private val metadata: IIOMetadata + private var frames = 0 + + init { + file.parentFile?.mkdirs() + output = ImageIO.createImageOutputStream(file) + writer.output = output + val type = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB) + metadata = writer.getDefaultImageMetadata(type, writer.defaultWriteParam) + val root = metadata.getAsTree(metadata.nativeMetadataFormatName) as IIOMetadataNode + root.child("GraphicControlExtension").apply { + setAttribute("disposalMethod", "none") + setAttribute("userInputFlag", "FALSE") + setAttribute("transparentColorFlag", "FALSE") + setAttribute("delayTime", (frameMillis / 10).coerceAtLeast(1).toString()) + setAttribute("transparentColorIndex", "0") + } + root.child("ApplicationExtensions").appendChild( + IIOMetadataNode("ApplicationExtension").apply { + setAttribute("applicationID", "NETSCAPE") + setAttribute("authenticationCode", "2.0") + // Loop forever. + userObject = byteArrayOf(1, 0, 0) + }, + ) + metadata.setFromTree(metadata.nativeMetadataFormatName, root) + writer.prepareWriteSequence(null) + } + + /** Append [image] as the next frame. */ + fun write(image: Image) { + val png = checkNotNull(image.encodeToData(EncodedImageFormat.PNG)).bytes + val decoded = ImageIO.read(ByteArrayInputStream(png)) + val rgb = BufferedImage(decoded.width, decoded.height, BufferedImage.TYPE_INT_RGB) + rgb.createGraphics().apply { + drawImage(decoded, 0, 0, null) + dispose() + } + writer.writeToSequence(IIOImage(rgb, null, metadata), writer.defaultWriteParam) + frames++ + } + + /** How many frames have been written. */ + val frameCount: Int get() = frames + + override fun close() { + writer.endWriteSequence() + output.close() + writer.dispose() + } + + private fun IIOMetadataNode.child(name: String): IIOMetadataNode { + for (i in 0 until length) { + val node = item(i) + if (node.nodeName.equals(name, ignoreCase = true)) return node as IIOMetadataNode + } + return IIOMetadataNode(name).also { appendChild(it) } + } +} diff --git a/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/LumosInputPreviewTest.kt b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/LumosInputPreviewTest.kt new file mode 100644 index 0000000..5434e67 --- /dev/null +++ b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/LumosInputPreviewTest.kt @@ -0,0 +1,217 @@ +package link.socket.phosphor.lumos.compose + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PixelMap +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.toComposeImageBitmap +import androidx.compose.ui.graphics.toPixelMap +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.dp +import java.io.File +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.sin +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue +import link.socket.phosphor.lumos.LiveFrameSource +import link.socket.phosphor.lumos.LumosConfig +import link.socket.phosphor.lumos.LumosFrameSource +import link.socket.phosphor.lumos.LumosRenderConfig +import link.socket.phosphor.palette.AtmospherePresets +import link.socket.phosphor.signal.LumosInput +import org.jetbrains.skia.EncodedImageFormat +import org.jetbrains.skia.Image + +/** + * PHO-83: [LumosInputPreview] — a settled THINKING orb with `interactive`, alone, pointed at the + * centre and pointed upper right — written to `build/lumos-previews/lumos-input-strip.png`; and the + * desktop recording: a scripted pointer path driven through [LumosOrb] with real pointer events on + * desktop Skia, about three seconds at 30 fps, written to `build/lumos-previews/lumos-input-repel.gif`. + * + * Both go through [SteppedScene], so the orbs' effects run on the test thread. + */ +class LumosInputPreviewTest { + @Test + fun `the strip shows the orb alone and parted around two pointers`() { + val scene = SteppedScene(width = STRIP_WIDTH, height = STRIP_HEIGHT) { LumosInputPreview() } + try { + val image = scene.renderUntil(STRIP_NANOS) + save(image, "lumos-input-strip.png") + val pixels = image.toComposeImageBitmap().toPixelMap() + + val alone = region(pixels, 0) + val centre = region(pixels, ORB + GAP) + val upperRight = region(pixels, 2 * (ORB + GAP)) + assertTrue(alone.any { it != BACKGROUND }, "the orb alone drew nothing") + assertTrue(centre.any { it != BACKGROUND }, "the orb pointed at the centre drew nothing") + assertTrue(upperRight.any { it != BACKGROUND }, "the orb pointed upper right drew nothing") + assertNotEquals(alone, centre, "a pointer at the centre changed nothing") + assertNotEquals(alone, upperRight, "a pointer upper right changed nothing") + assertNotEquals(centre, upperRight, "the two pointers part the cells the same way") + + // Under the pointer the cells have parted: less light around it than in the orb alone. + // The halo is the same in both, so it cancels out of the comparison. + val aloneLight = light(pixels, 0, CENTRE_BOX) + val centreLight = light(pixels, ORB + GAP, CENTRE_BOX) + println("[PHO-83] light in the centre box: alone $aloneLight, pointed $centreLight") + assertTrue(centreLight < aloneLight, "the cells did not part: $centreLight vs $aloneLight") + } finally { + scene.close() + } + } + + @Test + fun `records the cells parting around a pointer that sweeps across the orb`() { + val live = LiveFrameSource(AtmospherePresets.THINKING, LumosRenderConfig(interactive = true)) + live.next(WARM_UP_SECONDS) + val source = RecordingSource(live) + var marker: Offset? by mutableStateOf(null) + val scene = + SteppedScene(width = CLIP, height = CLIP, density = Density(1f)) { + val config = remember { LumosConfig(label = "Lumos, pointed at") } + Box(Modifier.size(CLIP.dp)) { + LumosOrb(source, config, Modifier.size(CLIP.dp), backgroundColor = BACKGROUND) + Canvas(Modifier.size(CLIP.dp)) { + marker?.let { drawCircle(MARKER, radius = MARKER_RADIUS, center = it, style = Stroke(2f)) } + } + } + } + val file = File("build/lumos-previews/lumos-input-repel.gif") + // The orb's loop draws its first frame on the frame after it is laid out. + scene.render() + var image = scene.renderNextFrame() + var changed = 0 + var previous = image.toComposeImageBitmap().toPixelMap().toList() + GifWriter(file, FRAME_MILLIS).use { gif -> + try { + for (frame in 0 until CLIP_FRAMES) { + val at = pointerAt(frame) + when { + frame == ENTER_FRAME -> scene.sendPointerEvent(PointerEventType.Enter, checkNotNull(at)) + frame == EXIT_FRAME -> scene.sendPointerEvent(PointerEventType.Exit, Offset(-1f, -1f)) + at != null -> scene.sendPointerEvent(PointerEventType.Move, at) + } + marker = at + Snapshot.sendApplyNotifications() + image = scene.renderNextFrame() + gif.write(image) + val pixels = image.toComposeImageBitmap().toPixelMap().toList() + if (pixels != previous) changed++ + previous = pixels + } + } finally { + scene.close() + } + println("[PHO-83] recorded ${gif.frameCount} frames to $file; ${source.inputs.size} inputs") + } + + // Breath and spin move the orb most frames; a step too small to move a pixel is allowed now and then. + assertTrue(changed >= CLIP_FRAMES * 3 / 4, "the orb stood still on most frames: $changed of $CLIP_FRAMES moved") + assertTrue(source.inputs.count { it.pointer != null } >= SWEEP_FRAMES, "the sweep was not reported") + assertEquals(LumosInput.NONE, source.inputs.last(), "the exit was not reported") + assertTrue(file.length() > 0, "the GIF is empty") + } + + // The scripted path: in from the left, across the centre, a loop upper right, and out. + private fun pointerAt(frame: Int): Offset? { + if (frame < ENTER_FRAME || frame >= EXIT_FRAME) return null + val sweepEnd = ENTER_FRAME + SWEEP_FRAMES + val holdEnd = sweepEnd + HOLD_FRAMES + return when { + frame < sweepEnd -> { + val t = (frame - ENTER_FRAME).toFloat() / SWEEP_FRAMES + Offset(CLIP * (0.1f + 0.4f * t), CLIP * 0.5f) + } + frame < holdEnd -> Offset(CLIP * 0.5f, CLIP * 0.5f) + else -> { + val t = (frame - holdEnd).toFloat() / (EXIT_FRAME - holdEnd) + val angle = PI.toFloat() * (1f - t) + Offset(CLIP * (0.5f + 0.25f * (1f - cos(angle)) / 2f + 0.25f * t), CLIP * (0.5f - 0.3f * sin(angle))) + } + } + } + + private fun region( + pixels: PixelMap, + left: Int, + ): List = + buildList { + for (y in 0 until STRIP_HEIGHT) for (x in left until left + ORB) add(pixels[x, y]) + } + + // Summed channel light inside a box, left/top/right/bottom relative to an orb at [left]. + private fun light( + pixels: PixelMap, + left: Int, + box: IntArray, + ): Float { + var sum = 0f + for (y in box[1] until box[3]) for (x in left + box[0] until left + box[2]) { + val pixel = pixels[x, y] + sum += pixel.red + pixel.green + pixel.blue + } + return sum + } + + private fun PixelMap.toList(): List = + buildList { + for (y in 0 until height) for (x in 0 until width) add(this@toList[x, y]) + } + + private fun save( + image: Image, + name: String, + ) { + val bytes = checkNotNull(image.encodeToData(EncodedImageFormat.PNG)).bytes + File("build/lumos-previews").apply { mkdirs() }.resolve(name).writeBytes(bytes) + } + + private class RecordingSource( + private val live: LiveFrameSource, + ) : LumosFrameSource by live { + val inputs = mutableListOf() + + override fun setInput(input: LumosInput) { + inputs += input + live.setInput(input) + } + } + + private companion object { + const val ORB = 200 + const val GAP = 16 + const val STRIP_WIDTH = 3 * ORB + 2 * GAP + const val STRIP_HEIGHT = ORB + const val STRIP_NANOS = 500_000_000L + + // A box around the centre of an orb, half the repel's radius (0.32 of the orb's) either side. + const val HOLE = 16 + val CENTRE_BOX = intArrayOf(ORB / 2 - HOLE, ORB / 2 - HOLE, ORB / 2 + HOLE, ORB / 2 + HOLE) + + const val CLIP = 240 + const val FRAME_MILLIS = 33 + const val CLIP_FRAMES = 90 + const val ENTER_FRAME = 8 + const val SWEEP_FRAMES = 24 + const val HOLD_FRAMES = 14 + const val EXIT_FRAME = 76 + const val WARM_UP_SECONDS = 1.5f + const val MARKER_RADIUS = 5f + + val BACKGROUND = INPUT_PREVIEW_BACKGROUND + val MARKER = Color.White + } +} diff --git a/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/LumosOrbPointerTest.kt b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/LumosOrbPointerTest.kt new file mode 100644 index 0000000..df6e1f7 --- /dev/null +++ b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/LumosOrbPointerTest.kt @@ -0,0 +1,213 @@ +package link.socket.phosphor.lumos.compose + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerButton +import androidx.compose.ui.input.pointer.PointerButtons +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.unit.dp +import kotlin.math.abs +import kotlin.math.sin +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import link.socket.phosphor.lumos.LiveFrameSource +import link.socket.phosphor.lumos.LumosConfig +import link.socket.phosphor.lumos.LumosFrameSource +import link.socket.phosphor.palette.AtmospherePresets +import link.socket.phosphor.signal.LumosInput + +/** + * PHO-83: [LumosOrb] answers the pointer through [lumosPointer] — hover and touch, mapped into + * the orb's view space — without taking any gesture from its parents, and tells its source the + * pointer has gone when it leaves composition. Driven through [SteppedScene]'s pointer + * passthrough, on the JVM. + */ +class LumosOrbPointerTest { + @Test + fun `hover at the centre reports the origin and at the top-left corner minus one plus one`() { + val source = RecordingSource() + val scene = SteppedScene(ORB, ORB) { LumosOrb(source, LumosConfig(), Modifier.size(ORB.dp)) } + try { + scene.render() + + scene.sendPointerEvent(PointerEventType.Enter, CENTRE) + scene.sendPointerEvent(PointerEventType.Move, CENTRE) + val centre = assertNotNull(source.inputs.lastOrNull()?.pointer, "the hover at the centre was not reported") + assertNear(0f, centre.x, "x at the centre") + assertNear(0f, centre.y, "y at the centre") + assertFalse(source.inputs.last().pressed) + + scene.sendPointerEvent(PointerEventType.Move, Offset.Zero) + val corner = assertNotNull(source.inputs.last().pointer) + assertNear(-1f, corner.x, "x at the top-left corner") + assertNear(1f, corner.y, "y at the top-left corner") + + scene.sendPointerEvent(PointerEventType.Exit, Offset(-1f, -1f)) + assertEquals(LumosInput.NONE, source.inputs.last(), "Exit reports NONE") + } finally { + scene.close() + } + } + + @Test + fun `a mouse button follows pressed without ending the hover`() { + val source = RecordingSource() + val scene = SteppedScene(ORB, ORB) { LumosOrb(source, LumosConfig(), Modifier.size(ORB.dp)) } + try { + scene.render() + scene.sendPointerEvent(PointerEventType.Enter, CENTRE) + scene.sendPointerEvent(PointerEventType.Move, CENTRE) + + scene.sendPointerEvent(PointerEventType.Press, CENTRE, PRIMARY_DOWN, PointerButton.Primary) + assertTrue(source.inputs.last().pressed, "the press is reported") + assertNotNull(source.inputs.last().pointer, "a press keeps the pointer") + + scene.sendPointerEvent(PointerEventType.Release, CENTRE, PointerButtons(), PointerButton.Primary) + assertFalse(source.inputs.last().pressed, "the release is reported") + assertNotNull(source.inputs.last().pointer, "a mouse release keeps the hover") + } finally { + scene.close() + } + } + + @Test + fun `a touch press reports pressed and a release reports NONE`() { + val source = RecordingSource() + val scene = SteppedScene(ORB, ORB) { LumosOrb(source, LumosConfig(), Modifier.size(ORB.dp)) } + try { + scene.render() + + scene.sendTouch(PointerEventType.Press, CENTRE, pressed = true) + val press = source.inputs.last() + assertTrue(press.pressed, "a touch is pressed") + assertNear(0f, assertNotNull(press.pointer).x, "x of the touch") + + scene.sendTouch(PointerEventType.Move, Offset(150f, 100f), pressed = true) + val move = source.inputs.last() + assertTrue(move.pressed) + assertNear(0.5f, assertNotNull(move.pointer).x, "x of the moved touch") + + scene.sendTouch(PointerEventType.Release, Offset(150f, 100f), pressed = false) + assertEquals(LumosInput.NONE, source.inputs.last(), "a release reports NONE") + } finally { + scene.close() + } + } + + @Test + fun `a touch drag that starts on the orb scrolls the column and the orb lets go`() { + val source = RecordingSource() + var scrolled = 0 + val scene = + SteppedScene(ORB, ORB + 100) { + val state = rememberScrollState() + scrolled = state.value + Column(Modifier.verticalScroll(state)) { + LumosOrb(source, LumosConfig(), Modifier.size(ORB.dp)) + Spacer(Modifier.height(1000.dp)) + } + } + try { + scene.render() + + scene.sendTouch(PointerEventType.Press, Offset(100f, 150f), pressed = true) + assertTrue(source.inputs.last().pressed, "the orb saw the touch land") + var y = 150f + repeat(6) { + y -= 20f + scene.sendTouch(PointerEventType.Move, Offset(100f, y), pressed = true) + scene.renderNextFrame() + } + val letGoAt = source.inputs.indexOf(LumosInput.NONE) + assertTrue(letGoAt > 0, "the orb never let go: ${source.inputs}") + assertTrue(source.inputs.drop(letGoAt).all { it == LumosInput.NONE }, "the orb reported after it let go") + + scene.sendTouch(PointerEventType.Release, Offset(100f, y), pressed = false) + scene.renderNextFrame() + + assertTrue(scrolled > 0, "the column did not scroll") + assertEquals(LumosInput.NONE, source.inputs.last()) + } finally { + scene.close() + } + } + + @Test + fun `removing the orb from composition reports NONE`() { + val source = RecordingSource() + var shown by mutableStateOf(true) + val scene = + SteppedScene(ORB, ORB) { + if (shown) LumosOrb(source, LumosConfig(), Modifier.size(ORB.dp)) + } + try { + scene.render() + scene.sendPointerEvent(PointerEventType.Enter, CENTRE) + scene.sendPointerEvent(PointerEventType.Move, CENTRE) + assertNotNull(source.inputs.last().pointer) + + shown = false + Snapshot.sendApplyNotifications() + scene.renderNextFrame() + + assertEquals(LumosInput.NONE, source.inputs.last()) + } finally { + scene.close() + } + } + + @Test + fun `a 30 degree tilt maps the front centre as the formula says`() { + val source = RecordingSource() + val config = LumosConfig(tiltDegrees = 30f) + val scene = SteppedScene(ORB, ORB) { LumosOrb(source, config, Modifier.size(ORB.dp)) } + try { + scene.render() + scene.sendPointerEvent(PointerEventType.Enter, CENTRE) + scene.sendPointerEvent(PointerEventType.Move, CENTRE) + + val pointer = assertNotNull(source.inputs.last().pointer) + assertNear(0f, pointer.x, "x") + assertNear(sin(Math.toRadians(30.0)).toFloat(), pointer.y, "y = sy·cos t + √(1 − x² − sy²)·sin t") + } finally { + scene.close() + } + } + + private fun assertNear( + expected: Float, + actual: Float, + label: String, + ) = assertTrue(abs(expected - actual) < 1e-3f, "$label: expected $expected, was $actual") + + /** A source that records what it is handed, over a live THINKING scene at a small resolution. */ + private class RecordingSource( + private val live: LiveFrameSource = LiveFrameSource(AtmospherePresets.THINKING.copy(resolution = 3)), + ) : LumosFrameSource by live { + val inputs = mutableListOf() + + override fun setInput(input: LumosInput) { + inputs += input + live.setInput(input) + } + } + + private companion object { + const val ORB = 200 + val CENTRE = Offset(100f, 100f) + val PRIMARY_DOWN = PointerButtons(isPrimaryPressed = true) + } +} diff --git a/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/SteppedScene.kt b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/SteppedScene.kt index 1e9bdf1..856441e 100644 --- a/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/SteppedScene.kt +++ b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/SteppedScene.kt @@ -1,7 +1,15 @@ package link.socket.phosphor.lumos.compose import androidx.compose.runtime.Composable +import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.ImageComposeScene +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerButton +import androidx.compose.ui.input.pointer.PointerButtons +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerId +import androidx.compose.ui.input.pointer.PointerType +import androidx.compose.ui.scene.ComposeScenePointer import androidx.compose.ui.unit.Density import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.StandardTestDispatcher @@ -22,8 +30,11 @@ import org.jetbrains.skia.Image * Here every effect is queued on a [StandardTestDispatcher] and run by [render], on the thread that * calls it. Each frame advances the scheduler by the frame's length, so `delay`s elapse in step with * the frames the orb sees. + * + * Pointer events pass straight through to the scene ([sendPointerEvent], [sendTouch]): a pointer + * handler resumes inside the dispatch, so what it reports is reported before the call returns. */ -@OptIn(ExperimentalCoroutinesApi::class) +@OptIn(ExperimentalCoroutinesApi::class, ExperimentalComposeUiApi::class) internal class SteppedScene( width: Int, height: Int, @@ -65,10 +76,38 @@ internal class SteppedScene( return image } + /** A mouse at [position]: `Enter`, `Move`, `Exit`, or `Press` and `Release` of [button]. */ + fun sendPointerEvent( + eventType: PointerEventType, + position: Offset, + buttons: PointerButtons = PointerButtons(), + button: PointerButton? = null, + type: PointerType = PointerType.Mouse, + ) = scene.sendPointerEvent( + eventType = eventType, + position = position, + buttons = buttons, + button = button, + type = type, + timeMillis = nowNanos / NANOS_PER_MILLI, + ) + + /** One finger at [position]: `Press`, then `Move`s while [pressed], then `Release`. */ + fun sendTouch( + eventType: PointerEventType, + position: Offset, + pressed: Boolean, + ) = scene.sendPointerEvent( + eventType = eventType, + pointers = listOf(ComposeScenePointer(PointerId(TOUCH_ID), position, pressed, PointerType.Touch)), + timeMillis = nowNanos / NANOS_PER_MILLI, + ) + override fun close() = scene.close() private companion object { const val FRAME_NANOS = 33_333_333L const val NANOS_PER_MILLI = 1_000_000L + const val TOUCH_ID = 1L } } diff --git a/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosPointer.kt b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosPointer.kt new file mode 100644 index 0000000..7e94cd9 --- /dev/null +++ b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosPointer.kt @@ -0,0 +1,41 @@ +package link.socket.phosphor.lumos.compose.docs + +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import link.socket.phosphor.lumos.LiveFrameSource +import link.socket.phosphor.lumos.LumosRenderConfig +import link.socket.phosphor.lumos.compose.LumosCanvas +import link.socket.phosphor.lumos.compose.lumosPointer +import link.socket.phosphor.lumos.projection.PixelLattice +import link.socket.phosphor.palette.AtmospherePresets + +@Composable +fun PointedCanvas() { + // 1. An interactive scene: its cells part around the pointer + val source = remember { LiveFrameSource(AtmospherePresets.THINKING, LumosRenderConfig(interactive = true)) } + val lattice = remember { PixelLattice(widthPx = 160, heightPx = 160, voxelRadiusPx = 4f) } + + // 2. Your own clock: project each frame as it is stepped + var frame by remember { mutableStateOf(lattice.project(source.next(0f))) } + LaunchedEffect(source) { + var last = withFrameNanos { it } + while (true) { + withFrameNanos { now -> + frame = lattice.project(source.next((now - last) / 1_000_000_000f)) + last = now + } + } + } + + // 3. The pointer, in the orb's view space, from one modifier that never consumes it; + // the projected frame then carries it in pixels for a material's light + LumosCanvas(frame, Modifier.size(160.dp).lumosPointer { source.setInput(it) }) +} diff --git a/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosQuickStartTest.kt b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosQuickStartTest.kt index b5734ca..23f001b 100644 --- a/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosQuickStartTest.kt +++ b/phosphor-lumos-compose/src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosQuickStartTest.kt @@ -11,6 +11,8 @@ import kotlin.test.assertTrue /** * Keeps the README's Lumos quick start honest. `ReadmeLumosQuickStart.kt` holds the snippet with * exactly its imports: it must compile, it must draw an orb, and the README must show it as is. + * `ReadmeLumosPointer.kt` is the section's second snippet — a consumer drawing `LumosCanvas` + * itself, with `interactive` and `lumosPointer` — held to the same rule. */ class ReadmeLumosQuickStartTest { @Test @@ -34,22 +36,56 @@ class ReadmeLumosQuickStartTest { } @Test - fun readmeShowsTheCompiledSnippet() { - val snippet = File(SNIPPET).readText().substringAfter("\n").trim() + fun pointedCanvasDrawsAnOrb() { + val scene = ImageComposeScene(width = 160, height = 160, density = Density(1f)) { PointedCanvas() } + try { + var now = 0L + repeat(10) { + scene.render(now) + now += 16_666_667L + } + val pixels = scene.render(now).toComposeImageBitmap().toPixelMap() + + assertTrue( + (0 until 160).any { x -> (0 until 160).any { y -> pixels[x, y].alpha > 0f } }, + "the pointed canvas drew nothing", + ) + } finally { + scene.close() + } + } + + @Test + fun readmeShowsTheCompiledSnippets() { val readme = File("../README.md").readText() val section = readme.indexOf(HEADING) check(section >= 0) { "README has no \"$HEADING\" section" } - val start = readme.indexOf("```kotlin\nimport ", section) + "```kotlin\n".length - val end = readme.indexOf("\n```", start) + val quickStart = readme.kotlinBlock(from = section) assertTrue( - readme.substring(start, end).trim() == snippet, + readme.substring(quickStart).trim() == snippet(SNIPPET), "README's Lumos quick start no longer matches $SNIPPET", ) + + val pointer = readme.kotlinBlock(from = quickStart.last) + assertTrue( + readme.substring(pointer).trim() == snippet(POINTER_SNIPPET), + "README's pointer snippet no longer matches $POINTER_SNIPPET", + ) + } + + private fun snippet(path: String) = File(path).readText().substringAfter("\n").trim() + + // The first fenced Kotlin block that starts with an import at or after [from]. + private fun String.kotlinBlock(from: Int): IntRange { + val start = indexOf("```kotlin\nimport ", from) + "```kotlin\n".length + val end = indexOf("\n```", start) + return start until end } private companion object { const val HEADING = "### A Lumos orb in Compose" const val SNIPPET = "src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosQuickStart.kt" + const val POINTER_SNIPPET = "src/jvmTest/kotlin/link/socket/phosphor/lumos/compose/docs/ReadmeLumosPointer.kt" } } diff --git a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/OrbStepper.kt b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/OrbStepper.kt index bbb28be..a680a40 100644 --- a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/OrbStepper.kt +++ b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/OrbStepper.kt @@ -5,6 +5,7 @@ import kotlin.math.min import link.socket.phosphor.lumos.frame.LumosCanvasFrame import link.socket.phosphor.lumos.probe.FrameProbe import link.socket.phosphor.lumos.projection.PixelLattice +import link.socket.phosphor.signal.LumosInput /** * The clock and the held frame behind a pixel-surface orb, with no framework in them, so every @@ -31,6 +32,13 @@ import link.socket.phosphor.lumos.projection.PixelLattice * change, so a surface hands only new frames on: Compose's `LumosOrb` puts them in its state. * [frame] is always the one drawn last. * + * [setInput] hands the pointer to the source and keeps it: from then on every frame projected + * here carries this pointer ([LumosCanvasFrame.pointer]) in place of whatever the source's frame + * carries, so a still, which carries none, and a recording, which cannot answer, are lit where the + * person points as a live frame is — and a pointer that has left lights nothing, even on a live + * frame built before it left. A surface that never calls it leaves the frame's own pointer alone. + * A pointer alone projects nothing: the next frame carries it. + * * Main-thread only, like the source it steps. * * @param source What the orb draws. @@ -73,6 +81,8 @@ class OrbStepper( private var platformReduced: Boolean = platformReducesMotion() private var platformCheckedNanos: Long = NEVER + private var input: LumosInput? = null + /** Whether the orb holds still: its config asks, or the platform does. */ val reducedMotion: Boolean get() = config.reducedMotion || platformReduced @@ -114,6 +124,15 @@ class OrbStepper( return reproject() } + /** + * What the person is doing to the surface: hand it to the source ([LumosFrameSource.setInput]) + * and light every frame from here on with its pointer. Projects nothing by itself. + */ + fun setInput(input: LumosInput) { + this.input = input + source.setInput(input) + } + /** The orb starts or resumes stepping: the next step aligns its source to its look's clock. */ fun rejoin() { rejoining = true @@ -199,7 +218,7 @@ class OrbStepper( target: PixelLattice, voxels: VoxelFrame, ): LumosCanvasFrame { - val projected = target.project(voxels) + val projected = target.project(voxels, (input ?: voxels.input)?.pointer) frame = projected projectedWith = target return projected diff --git a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/frame/LumosCanvasFrame.kt b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/frame/LumosCanvasFrame.kt index f5b12c4..1bd2d82 100644 --- a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/frame/LumosCanvasFrame.kt +++ b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/frame/LumosCanvasFrame.kt @@ -2,8 +2,10 @@ package link.socket.phosphor.lumos.frame import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import kotlinx.serialization.Transient import link.socket.phosphor.lumos.VoxelAmbient import link.socket.phosphor.lumos.VoxelGlyphState +import link.socket.phosphor.math.Vector2 /** * Serializable 2D projection of a VoxelFrame shaped for pixel-canvas rendering. @@ -23,6 +25,11 @@ import link.socket.phosphor.lumos.VoxelGlyphState * for halo and glow rendering. * @property glyph Active glyph state, if any. Passed through for glyph-aware overlay rendering. * @property tick Monotonic frame counter passed through from source frame. + * @property pointer Where the person points, in canvas pixels with Y down, for a material's light: + * [link.socket.phosphor.lumos.VoxelFrame.input]'s pointer carried through the projection — the + * front of the orb at that view-space point, tilted as the voxels are — or the pointer the + * driver laid over the frame, so a recorded orb is lit like a live one. Null when nothing + * points. Never serialized, like the input it comes from. */ @Serializable @SerialName("link.socket.phosphor.lumos.compose.frame.LumosCanvasFrame") @@ -33,6 +40,7 @@ data class LumosCanvasFrame( val ambient: VoxelAmbient, val glyph: VoxelGlyphState? = null, val tick: Long, + @Transient val pointer: Vector2? = null, ) { /** * Projected 2D voxel with rendering parameters suitable for Compose Canvas. diff --git a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/projection/PixelLattice.kt b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/projection/PixelLattice.kt index 38b7325..cbcee52 100644 --- a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/projection/PixelLattice.kt +++ b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/projection/PixelLattice.kt @@ -2,7 +2,9 @@ package link.socket.phosphor.lumos.projection import kotlin.math.PI import kotlin.math.cos +import kotlin.math.max import kotlin.math.sin +import kotlin.math.sqrt import link.socket.phosphor.lumos.OrbViewport import link.socket.phosphor.lumos.VoxelAmbient import link.socket.phosphor.lumos.VoxelFrame @@ -11,6 +13,7 @@ import link.socket.phosphor.lumos.frame.LumosCanvasFrame.CanvasVoxel import link.socket.phosphor.lumos.probe.FramePhase import link.socket.phosphor.lumos.probe.FrameProbe import link.socket.phosphor.lumos.probe.measure +import link.socket.phosphor.math.Vector2 /** * Orthographic projection of a [VoxelFrame] to a [LumosCanvasFrame] for pixel-canvas rendering. @@ -96,15 +99,50 @@ class PixelLattice( * trace carries it as a live frame does; an atmosphere that also rotates about X tips the * true direction off this one. * - * Ambient and glyph state pass through unchanged. + * Ambient and glyph state pass through unchanged. [pointer] — by default the frame's own + * [VoxelFrame.input] pointer — is carried onto [LumosCanvasFrame.pointer] in canvas pixels: + * the point on the front of the unit sphere under it, tilted and placed as the voxels are, + * so a material's light lands where the person points. A driver passes the pointer it holds + * itself to light a still or a recorded frame, which carry none. + * + * @param frame The frame to project. + * @param pointer Where the person points, in the orb's view space before the tilt; see + * [link.socket.phosphor.signal.LumosInput.pointer]. Defaults to the frame's own. + */ + fun project( + frame: VoxelFrame, + pointer: Vector2? = frame.input?.pointer, + ): LumosCanvasFrame = probe.measure(FramePhase.PROJECT) { projectFrame(frame, pointer) } + + /** + * Where a view-space [pointer] lands on this canvas, in pixels with Y down: the forward + * mapping [project] applies to a voxel on the front of the unit sphere at that point, so the + * light sits on the surface the person points at. A pointer past the rim maps as if on the + * orb's equatorial plane. */ - fun project(frame: VoxelFrame): LumosCanvasFrame = probe.measure(FramePhase.PROJECT) { projectFrame(frame) } + fun canvasPointer(pointer: Vector2): Vector2 { + val x = pointer.x + var y = pointer.y + if (tilted) { + val z = sqrt(max(0f, 1f - x * x - y * y)) + y = y * cosTilt - z * sinTilt + } + val invAspect = 1f / aspectRatio + return if (viewport == null) { + Vector2((x + 1f) * 0.5f * widthPx, (1f - (y + 1f) * 0.5f) * heightPx * invAspect) + } else { + Vector2(viewport.centerXPx + x * viewport.radiusPx, viewport.centerYPx - y * viewport.radiusPx * invAspect) + } + } // Reusable sort keys: (order-preserving z bits << 32) | index into `scratch`. Grown, never shrunk. private var keys = LongArray(0) private var scratch = arrayOfNulls(0) - private fun projectFrame(frame: VoxelFrame): LumosCanvasFrame { + private fun projectFrame( + frame: VoxelFrame, + pointer: Vector2?, + ): LumosCanvasFrame { val cells = frame.cells val ambient = frame.ambient @@ -193,6 +231,7 @@ class PixelLattice( ambient = ambient, glyph = frame.glyph, tick = frame.tick, + pointer = pointer?.let(::canvasPointer), ) } diff --git a/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/OrbStepperTest.kt b/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/OrbStepperTest.kt index e38c4ed..b8bcfbf 100644 --- a/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/OrbStepperTest.kt +++ b/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/OrbStepperTest.kt @@ -8,12 +8,14 @@ import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue import link.socket.phosphor.lumos.probe.FrameProbe +import link.socket.phosphor.math.Vector2 +import link.socket.phosphor.signal.LumosInput /** * PHO-53: the rules a pixel-surface orb keeps about time — speed, the cap on a step, alignment to * a shared look clock, reduced motion, the paused redraw — and the projection it reuses. Moved * with [OrbStepper] out of `LumosOrb`'s driver (PHO-85). PHO-79: a look change aligns the look - * alone. + * alone. PHO-83: the pointer goes to the source and lights every frame projected after it. */ class OrbStepperTest { @Test @@ -372,6 +374,54 @@ class OrbStepperTest { assertNull(stepper.hold(), "a frame is already drawn") } + @Test + fun `the pointer goes to the source and projects nothing by itself`() { + val source = RecordingSource() + val stepper = OrbStepper(source, LookClock()) { false } + stepper.resize(100, 100) + stepper.step(secondsToNanos(1.0)) + val pointing = LumosInput(Vector2(0.5f, 0.5f)) + + stepper.setInput(pointing) + + assertEquals(listOf(pointing), source.inputs) + assertNull(stepper.frame?.pointer, "the frame drawn before the pointer is not redrawn") + } + + @Test + fun `the latest pointer lights every frame projected after it — live or still or recorded`() { + val source = RecordingSource() + val stepper = OrbStepper(source, LookClock()) { false } + stepper.resize(100, 100) + stepper.setInput(LumosInput(Vector2(0.5f, 0.5f))) + + source.frame = frame(tick = 2L) + val live = assertNotNull(stepper.step(secondsToNanos(1.0))) + assertEquals(Vector2(75f, 25f), live.pointer, "a frame carrying no input is lit by the stepper's pointer") + + stepper.update(LumosConfig(reducedMotion = true), FrameProbe.Disabled) + source.frame = frame(tick = 3L) + val still = assertNotNull(stepper.step(secondsToNanos(1.016))) + assertEquals(Vector2(75f, 25f), still.pointer, "a still is lit too") + + stepper.setInput(LumosInput.NONE) + source.frame = frame(tick = 4L, input = LumosInput(Vector2(-0.5f, 0f))) + val gone = assertNotNull(stepper.step(secondsToNanos(1.032))) + assertNull(gone.pointer, "a pointer that left lights nothing, even on a frame built before it left") + } + + @Test + fun `a stepper never handed input leaves the frame's own pointer alone`() { + val source = RecordingSource(frame = frame(input = LumosInput(Vector2(-1f, 1f)))) + val stepper = OrbStepper(source, LookClock()) { false } + stepper.resize(100, 100) + + val projected = assertNotNull(stepper.step(secondsToNanos(1.0))) + + assertEquals(Vector2(0f, 0f), projected.pointer) + assertTrue(source.inputs.isEmpty()) + } + private class RecordingSource( var key: String? = "idle", var frame: VoxelFrame = frame(), @@ -380,8 +430,13 @@ class OrbStepperTest { val stills = mutableListOf() val aligned = mutableListOf() val alignedLooks = mutableListOf() + val inputs = mutableListOf() var revisionValue = 0L + override fun setInput(input: LumosInput) { + inputs += input + } + override fun next(dt: Float): VoxelFrame { steps += dt return frame @@ -413,6 +468,7 @@ class OrbStepperTest { fun frame( tick: Long = 1L, cellY: Float = 0f, + input: LumosInput? = null, ): VoxelFrame = VoxelFrame( tick = tick, @@ -429,6 +485,7 @@ class OrbStepperTest { orbRotationY = 0f, orbRotationZ = 0f, ), + input = input, ) } } diff --git a/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/projection/PixelLatticePointerTest.kt b/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/projection/PixelLatticePointerTest.kt new file mode 100644 index 0000000..93eed25 --- /dev/null +++ b/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/projection/PixelLatticePointerTest.kt @@ -0,0 +1,140 @@ +package link.socket.phosphor.lumos.projection + +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.sin +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import link.socket.phosphor.lumos.OrbViewport +import link.socket.phosphor.lumos.VoxelAmbient +import link.socket.phosphor.lumos.VoxelCell +import link.socket.phosphor.lumos.VoxelFrame +import link.socket.phosphor.math.Vector2 +import link.socket.phosphor.signal.LumosInput + +/** + * PHO-83: [PixelLattice.project] carries the pointer onto the canvas frame in pixels — the frame's + * own by default, or the one the driver holds — mapped as a voxel on the front of the unit sphere + * at that view-space point would be: Y flipped, tilted, placed in the viewport. + */ +class PixelLatticePointerTest { + @Test + fun `a frame with no input carries no pointer`() { + assertNull(lattice().project(frameOf()).pointer) + } + + @Test + fun `the frame's pointer lands in canvas pixels with Y down`() { + val frame = frameOf(input = LumosInput(Vector2(0.5f, 0.5f))) + + val pointer = assertNotNull(lattice().project(frame).pointer) + + assertNear(150f, pointer.x, "x") + assertNear(50f, pointer.y, "y") + } + + @Test + fun `the centre maps to the canvas centre and the top-left corner to the top-left pixel`() { + val lattice = lattice() + + assertEquals(Vector2(100f, 100f), lattice.canvasPointer(Vector2(0f, 0f))) + assertEquals(Vector2(0f, 0f), lattice.canvasPointer(Vector2(-1f, 1f))) + } + + @Test + fun `a pointer handed to project replaces the frame's own`() { + val frame = frameOf(input = LumosInput(Vector2(0.5f, 0.5f))) + + val replaced = assertNotNull(lattice().project(frame, Vector2(-0.5f, -0.5f)).pointer) + assertNear(50f, replaced.x, "x") + assertNear(150f, replaced.y, "y") + + assertNull(lattice().project(frame, null).pointer, "null clears the frame's pointer") + } + + @Test + fun `a tilt carries the pointer where the front of the orb went`() { + val tilted = PixelLattice(widthPx = SIZE, heightPx = SIZE, tiltDegrees = 30f) + val front = tilted.project(frameOf(cell(0f, 0f, 1f))).voxels.single() + + val pointer = tilted.canvasPointer(Vector2(0f, 0f)) + + assertNear(front.screenX, pointer.x, "x") + assertNear(front.screenY, pointer.y, "y") + assertNear(SIZE / 2f + SIZE / 2f * sin(TILT), pointer.y, "below the centre by sin(tilt)") + } + + @Test + fun `a tilt leaves a pointer on the rim on the rim`() { + val tilted = PixelLattice(widthPx = SIZE, heightPx = SIZE, tiltDegrees = 30f) + val rim = tilted.project(frameOf(cell(0f, -1f, 0f))).voxels.single() + + val pointer = tilted.canvasPointer(Vector2(0f, -1f)) + + assertNear(rim.screenX, pointer.x, "x") + assertNear(rim.screenY, pointer.y, "y") + } + + @Test + fun `a pointer past the rim maps on the equatorial plane`() { + val tilted = PixelLattice(widthPx = SIZE, heightPx = SIZE, tiltDegrees = 30f) + + val pointer = tilted.canvasPointer(Vector2(1.5f, 0f)) + + assertNear(250f, pointer.x, "x") + assertNear(100f, pointer.y, "y") + } + + @Test + fun `a viewport places the pointer about its centre`() { + val lattice = + PixelLattice(widthPx = 1000, heightPx = 400, viewport = OrbViewport(600f, 200f, 100f)) + + assertEquals(Vector2(600f, 200f), lattice.canvasPointer(Vector2(0f, 0f))) + assertEquals(Vector2(700f, 100f), lattice.canvasPointer(Vector2(1f, 1f))) + } + + @Test + fun `the aspect ratio scales the pointer's Y as it scales the voxels`() { + val lattice = PixelLattice(widthPx = SIZE, heightPx = SIZE, aspectRatio = 2f) + val top = lattice.project(frameOf(cell(0f, 1f, 0f))).voxels.single() + + val pointer = lattice.canvasPointer(Vector2(0f, 1f)) + + assertNear(top.screenY, pointer.y, "y") + } + + private fun lattice() = PixelLattice(widthPx = SIZE, heightPx = SIZE) + + private fun cell( + x: Float, + y: Float, + z: Float, + ) = VoxelCell(x = x, y = y, z = z, scale = 1f, red = 1f, green = 1f, blue = 1f) + + private fun frameOf( + vararg cells: VoxelCell, + input: LumosInput? = null, + ) = VoxelFrame( + tick = 1L, + timestampEpochMillis = 0L, + resolution = 10, + cells = cells.toList(), + ambient = VoxelAmbient(0f, 0f, 0f, 0f, orbRotationX = 0f, orbRotationY = 0f, orbRotationZ = 0f), + input = input, + ) + + private fun assertNear( + expected: Float, + actual: Float, + label: String, + ) = assertTrue(abs(expected - actual) < 1e-3f, "$label: expected $expected, was $actual") + + private companion object { + const val SIZE = 200 + val TILT = (30.0 * PI / 180.0).toFloat() + } +}