diff --git a/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceOrb.kt b/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceOrb.kt index b0012fd..0e95865 100644 --- a/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceOrb.kt +++ b/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceOrb.kt @@ -2,6 +2,9 @@ package link.socket.phosphor.lumos.surface import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.boundsInRoot @@ -14,9 +17,10 @@ import link.socket.phosphor.lumos.probe.FrameProbe * * While [LumosSurfaceState.phase] is [SurfacePhase.Orb] this composes a `LumosOrb` on the state's * source and config, which steps and draws it as any orb. Its bounds are published as the - * state's viewport, so the cells leave from where the orb is laid out. The frame an assembly - * starts flying, the orb leaves the composition — its loop ends, and the surface's overlay takes - * the source over — and the slot stays, empty and the same size, so nothing around it reflows + * state's viewport, so the cells leave from where the orb is laid out. It keeps the orb through + * [LumosSurfaceState.assembleInto] until the surface's overlay has the flight's first frame to + * draw; then the orb leaves the composition — its loop ends, and the overlay has the source — + * and the slot stays, empty and the same size, so nothing around it reflows * and the orb has somewhere to come back to on [LumosSurfaceState.release]. * * Give the slot a size, as a `LumosOrb` needs one; the orb fills it. The orb's halo stops with @@ -38,8 +42,10 @@ fun LumosSurfaceOrb( showGlyphOverlay: Boolean = true, probe: FrameProbe = FrameProbe.Disabled, ) { + // Derived, so the overlay's new frame each flight step does not recompose the slot. + val orbInSlot by remember(state) { derivedStateOf { state.orbInSlot } } Box(modifier = modifier.onGloballyPositioned { state.slotPositioned(it.boundsInRoot()) }) { - if (state.phase is SurfacePhase.Orb) { + if (orbInSlot) { LumosOrb( source = state.source, config = state.config, diff --git a/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfacePreview.kt b/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfacePreview.kt index 2bc0732..2d90f4b 100644 --- a/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfacePreview.kt +++ b/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfacePreview.kt @@ -18,13 +18,16 @@ import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.delay +import link.socket.phosphor.lumos.Forms import link.socket.phosphor.lumos.LiveFrameSource import link.socket.phosphor.lumos.LumosConfig import link.socket.phosphor.lumos.SurfaceStyle +import link.socket.phosphor.lumos.counted import link.socket.phosphor.palette.AtmospherePresets /** @@ -42,19 +45,46 @@ fun LumosSurfacePreview() { LumosSurfacePreview(state) } +/** + * The Turn-on moment at Socket's hero size: `LumosTabOrb`'s 160 px orb on the presets' + * resolution 10, 4,801 cells, into the same 128 × 40 button. A cell every 1.1 px on the button. + */ +@Composable +fun LumosSurfaceHeroPreview() { + val state = remember { heroSurfaceState() } + LumosSurfacePreview(state, orbSize = HERO_ORB_SIZE, orbTop = HERO_ORB_TOP) +} + +/** + * The Turn-on moment at Socket's inline size: the 20 px orb on `Forms.Fibonacci` at 80 cells, + * into the same 128 × 40 button, with half its cells on the outline so the edge still reads. + */ +@Composable +fun LumosSurfaceInlinePreview() { + val state = remember { inlineSurfaceState() } + LumosSurfacePreview(state, orbSize = INLINE_ORB_SIZE, orbTop = INLINE_ORB_TOP) +} + /** * [LumosSurfacePreview] on [state], assembling [assembleAfterSeconds] in; [onTurnOn] is the * button's click. + * + * @param orbSize The orb's slot, top centre; 128 dp by default. + * @param orbTop The slot's distance from the top. + * @param surplus What the assembly does with the cells the button does not need. */ @Composable fun LumosSurfacePreview( state: LumosSurfaceState, assembleAfterSeconds: Float = PREVIEW_ASSEMBLE_AT_SECONDS, onTurnOn: () -> Unit = {}, + orbSize: Dp = PREVIEW_ORB_SIZE, + orbTop: Dp = PREVIEW_ORB_TOP, + surplus: SurfaceSurplus = SurfaceSurplus.Keep, ) { LaunchedEffect(state) { delay((assembleAfterSeconds * 1000f).toLong().milliseconds) - state.assembleInto(PREVIEW_TARGET, tint = PREVIEW_ACCENT) + state.assembleInto(PREVIEW_TARGET, tint = PREVIEW_ACCENT, surplus = surplus) } LumosSurface( state = state, @@ -62,7 +92,7 @@ fun LumosSurfacePreview( ) { LumosSurfaceOrb( state = state, - modifier = Modifier.align(Alignment.TopCenter).padding(top = PREVIEW_ORB_TOP).size(PREVIEW_ORB_SIZE), + modifier = Modifier.align(Alignment.TopCenter).padding(top = orbTop).size(orbSize), showHalo = false, ) Box( @@ -92,6 +122,23 @@ fun previewSurfaceState(): LumosSurfaceState = config = LumosConfig(style = SurfaceStyle.Dots), ) +/** [LumosSurfaceHeroPreview]'s state: an IDLE orb at the presets' resolution 10, drawn in [style]. */ +fun heroSurfaceState(style: SurfaceStyle = SurfaceStyle.Dots): LumosSurfaceState = + LumosSurfaceState( + source = LiveFrameSource(AtmospherePresets.IDLE.copy(resolution = HERO_RESOLUTION)), + config = LumosConfig(style = style), + ) + +/** [LumosSurfaceInlinePreview]'s state: an IDLE orb on the inline orb's 80-cell Fibonacci sphere, drawn in [style]. */ +fun inlineSurfaceState(style: SurfaceStyle = SurfaceStyle.Dots): LumosSurfaceState = + LumosSurfaceState( + source = + LiveFrameSource(AtmospherePresets.IDLE).also { live -> + live.builder.form = Forms.Fibonacci.counted(Forms.inlineOrbCount(INLINE_ORB_PX)) + }, + config = LumosConfig(style = style), + ) + /** The preview's target id. */ const val PREVIEW_TARGET: String = "turn-on" @@ -105,6 +152,12 @@ internal val PREVIEW_WIDTH = 400.dp internal val PREVIEW_HEIGHT = 260.dp internal val PREVIEW_ORB_TOP = 36.dp internal val PREVIEW_ORB_SIZE = 128.dp +internal const val HERO_RESOLUTION: Int = 10 +internal val HERO_ORB_TOP = 12.dp +internal val HERO_ORB_SIZE = 160.dp +internal const val INLINE_ORB_PX: Int = 20 +internal val INLINE_ORB_TOP = 90.dp +internal val INLINE_ORB_SIZE = INLINE_ORB_PX.dp internal val PREVIEW_PADDING = 24.dp internal val PREVIEW_BUTTON_WIDTH = 128.dp internal val PREVIEW_BUTTON_HEIGHT = 40.dp diff --git a/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceState.kt b/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceState.kt index 466bc2d..64e6d84 100644 --- a/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceState.kt +++ b/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceState.kt @@ -13,13 +13,17 @@ import link.socket.phosphor.lumos.LiveFrameSource import link.socket.phosphor.lumos.LookClock import link.socket.phosphor.lumos.LumosConfig import link.socket.phosphor.lumos.LumosForm +import link.socket.phosphor.lumos.LumosFrameSource import link.socket.phosphor.lumos.OrbStepper import link.socket.phosphor.lumos.OrbViewport import link.socket.phosphor.lumos.PixelForm import link.socket.phosphor.lumos.PlatformMotionPreference import link.socket.phosphor.lumos.RectPx +import link.socket.phosphor.lumos.SurfaceStyle +import link.socket.phosphor.lumos.VoxelFrame import link.socket.phosphor.lumos.frame.LumosCanvasFrame import link.socket.phosphor.lumos.probe.FrameProbe +import link.socket.phosphor.signal.LumosInput /** * Owns an assembly: the orb's source and where it sits, the pixel form the cells fly to, the @@ -30,15 +34,22 @@ import link.socket.phosphor.lumos.probe.FrameProbe * from anywhere. The [phase] says where things are, and every target reads [alphaFor]. * * - **One driver per source.** While the phase is [SurfacePhase.Orb], [LumosSurfaceOrb] composes a - * `LumosOrb` on [source] and that orb steps it. The frame [assembleInto] starts flying, the slot - * drops its orb and this state's own [OrbStepper] takes the source over, projecting it at the - * [viewport] on the surface; the two never run together. On [SurfacePhase.Solid] nothing steps. + * `LumosOrb` on [source] and that orb steps it. It keeps it through [assembleInto] until the + * flight starts, and the frame it does, an [OrbStepper] of this state's own takes the source over, + * projecting it at the [viewport] on the surface, and the slot drops its orb once the overlay has + * that frame to draw: the orb never blinks out between the two. On that one frame both step the + * source, but the overlay's stepper is new each flight and its first step is `dt = 0`, so the + * orb still moves by one frame's time. On [SurfacePhase.Solid] nothing steps. * - **Measured arrival.** Each frame, [arrival] is the mean distance in pixels of the projected * cells outside the target's rounded rectangle, through Dots' window `(8 − meanErr) / 6`, * smoothstepped. Never the morph's own progress, which ignores the choreography's arc. The * control's alpha is the arrival; the cells grow `× (1 + 0.6 · arrival)` and fade * `× (1 − arrival)` on the same curve, and lerp toward a tint when one is given. Solid when * arrival reaches 1 or the morph settles, whichever first. + * - **Count.** By default every cell flies, however densely that packs the control; with + * [SurfaceSurplus.Fade] the cells the control does not need fade out under the burst and are + * dropped when the morph starts. A count too small to draw the control's edge puts more of its + * cells on the outline; see `PixelForm.outlineFraction`. * - **Follow.** The form reads the target's live bounds every step, so a control that scrolls * mid-flight is tracked with the spring's own momentum. * - **Reduced motion.** `config.reducedMotion || PlatformMotionPreference.reduceMotion`, read once @@ -56,12 +67,14 @@ import link.socket.phosphor.lumos.probe.FrameProbe * @param viewport Where the orb's unit sphere sits, in the surface's pixels. Null, the default, * measures it from [LumosSurfaceOrb]'s slot; a host with no slot passes one. * @param config How the orb is driven and drawn, shared by the slot's orb and the overlay so the - * cells keep their speed, size, tilt and style across the switch. + * cells keep their speed, size, tilt and style across the switch. [SurfaceStyle.Dots] by default, + * not `LumosConfig`'s Squares: at the inline orb's 20 px, Squares on a button merge into a slab + * with holes, and Dots stay cells (PHO-76). */ class LumosSurfaceState( val source: LiveFrameSource, viewport: OrbViewport? = null, - val config: LumosConfig = LumosConfig(), + val config: LumosConfig = LumosConfig(style = SurfaceStyle.Dots), ) { /** Where the surface is. Compose state. */ var phase: SurfacePhase by mutableStateOf(SurfacePhase.Orb) @@ -111,10 +124,28 @@ class LumosSurfaceState( /** The platform's reduced-motion request; a test replaces it. */ internal var platformReducesMotion: () -> Boolean = { PlatformMotionPreference.reduceMotion } - /** The form the cells are flying to, from the frame the morph starts until Solid. */ + /** The share of a count's cells the form puts on the control's outline; a test replaces it. */ + internal var outlineFraction: (RectPx, Int) -> Float = PixelForm::outlineFraction + + /** The form the cells are flying to, from the frame the flight starts until Solid. */ internal var form: PixelForm.RoundedRect? = null private set + /** + * Under [SurfaceSurplus.Fade], which of the orb's cells are fading, by index, until the morph + * drops them; otherwise null. + */ + internal var surplus: BooleanArray? = null + private set + + /** How far [surplus] has faded, `0..1`. */ + internal var surplusFade: Float = 0f + private set + + // What this state's stepper steps: the source, with the surplus faded while it is. The + // projection sorts by depth, so the fade is applied here, where cell i is still cell i. + private val fadingSource = FadingSource() + private var solidIds: Set by mutableStateOf(emptySet()) private val targets = HashMap() private var stepper: OrbStepper? = null @@ -126,6 +157,10 @@ class LumosSurfaceState( private var request: Request? = null private var homeForm: LumosForm? = null + // A fade in flight: the cells that stay, out of the surplus mask's count, and when the fade began. + private var survivors: IntArray? = null + private var fadeStartNanos: Long = 0L + /** * Target [id]'s alpha: 1 once the cells have become it, the [arrival] while they are on * their way, and 0 otherwise. A target is invisible until it is assembled; it is laid out and @@ -152,6 +187,8 @@ class LumosSurfaceState( * completes before it does. * @param tint A colour the cells lerp toward on the arrival curve, so the hand-off reads as * one material changing state; null leaves their colours alone. + * @param surplus What to do with the cells the control does not need; every cell flies by + * default. Under [SurfaceSurplus.Fade] the morph starts once the surplus has faded. * @throws IllegalArgumentException when [burst] is not finite or [durationSeconds] is not * positive and finite. */ @@ -160,6 +197,7 @@ class LumosSurfaceState( burst: Float = DEFAULT_BURST, durationSeconds: Float = DEFAULT_DURATION_SECONDS, tint: Color? = null, + surplus: SurfaceSurplus = SurfaceSurplus.Keep, ) { require(burst.isFinite()) { "burst must be finite, was $burst" } require(durationSeconds > 0f && durationSeconds.isFinite()) { @@ -174,7 +212,7 @@ class LumosSurfaceState( } this.tint = tint arrival = 0f - request = Request(id, burst, durationSeconds) + request = Request(id, burst, durationSeconds, surplus) phase = SurfacePhase.Assembling(id) } @@ -196,15 +234,16 @@ class LumosSurfaceState( phase = SurfacePhase.Orb } + /** + * Whether [LumosSurfaceOrb]'s slot draws the orb: as an orb, and through an assembly until the + * overlay has the flight's first frame to draw, so nothing blinks out between the two. Compose state. + */ + internal val orbInSlot: Boolean + get() = phase is SurfacePhase.Orb || (phase is SurfacePhase.Assembling && canvasFrame == null) + /** The surface composed under [clock]: the stepper that takes the source over steps on it. */ internal fun attach(clock: LookClock) { - if (this.clock === clock) return this.clock = clock - stepper = - OrbStepper(source, clock, platformReducesMotion).also { - it.update(config, FrameProbe.Disabled) - if (widthPx > 0 && heightPx > 0) it.resize(widthPx, heightPx) - } } /** Where the surface's box sits in the composition root; targets and the slot are measured relative to it. */ @@ -247,14 +286,14 @@ class LumosSurfaceState( } /** - * One frame of flight: start the morph if the target and viewport have just become known, - * follow the target, step and project the source, measure arrival, and finish when the cells - * have arrived or the spring has settled. + * One frame of flight: start the flight if the target and viewport have just become known, + * fade any surplus and then start the morph, follow the target, step and project the source, + * measure arrival, and finish when the cells have arrived or the spring has settled. */ internal fun step(frameTimeNanos: Long) { val assembling = phase as? SurfacePhase.Assembling ?: return val request = request ?: return - val stepper = stepper ?: return + val clock = clock ?: return val target = targets[assembling.id] ?: return if (widthPx <= 0 || heightPx <= 0) return val builder = source.builder @@ -264,17 +303,29 @@ class LumosSurfaceState( val viewport = viewport ?: return val rect = target.rectPx(originX, originY) ?: return target.dirty = false - PixelForm.roundedRect(rect, viewport).also { started -> + val count = builder.currentCount + val keep = (request.surplus as? SurfaceSurplus.Fade)?.keep(rect, count) ?: count + PixelForm.roundedRect(rect, viewport, outlineFraction(rect, keep)).also { started -> form = started homeForm = builder.form - stepper.place(viewport) - stepper.rejoin() + // New each flight, so its first step is dt = 0: the slot's orb has stepped this frame. + stepper = + OrbStepper(fadingSource, clock, platformReducesMotion).also { + it.update(config, FrameProbe.Disabled) + it.resize(widthPx, heightPx) + it.place(viewport) + it.rejoin() + } builder.burst(request.burst) - builder.morphTo( - form = started, - choreography = Choreography.FLOW, - durationSeconds = request.durationSeconds, - ) + if (keep < count) { + val kept = evenSurvivors(count, keep) + survivors = kept + surplus = BooleanArray(count) { true }.also { mask -> for (i in kept) mask[i] = false } + surplusFade = 0f + fadeStartNanos = frameTimeNanos + } else { + morph(started, count, request) + } } } if (target.dirty) { @@ -282,20 +333,52 @@ class LumosSurfaceState( target.dirty = false } + val fading = survivors + if (fading != null) { + val fade = request.surplus as SurfaceSurplus.Fade + val elapsedNanos = (frameTimeNanos - fadeStartNanos).coerceAtLeast(0L) + surplusFade = (elapsedNanos / fade.duration.inWholeNanoseconds.toDouble()).toFloat().coerceAtMost(1f) + if (surplusFade >= 1f) { + // Faded out under the burst: the morph drops them, and nothing visible is cut. A + // resolution change mid-fade was a cut already, so the survivors no longer apply. + val stillCounted = builder.currentCount == surplus?.size + morph(flying, fading.size, request, fading.takeIf { stillCounted }) + survivors = null + surplus = null + } + } + + val stepper = stepper ?: return stepper.step(frameTimeNanos)?.let { canvasFrame = it } val frame = stepper.frame ?: return val arrived = arrivalOf(frame, flying.rect) arrival = arrived - if (arrived >= 1f || !builder.isMorphing) finish(assembling.id) + if (survivors == null && (arrived >= 1f || !builder.isMorphing)) finish(assembling.id) } + private fun morph( + form: PixelForm.RoundedRect, + count: Int, + request: Request, + survivors: IntArray? = null, + ) = source.builder.morphTo( + form = form, + count = count, + choreography = Choreography.FLOW, + durationSeconds = request.durationSeconds, + survivors = survivors, + ) + private fun finish(id: String) { // A cut, back to the form the orb wore: nothing draws the cells now, so nothing jumps. homeForm?.let { source.builder.form = it } homeForm = null form = null + survivors = null + surplus = null + surplusFade = 0f request = null - stepper?.place(null) + stepper = null canvasFrame = null arrival = 1f solidIds = solidIds + id @@ -326,10 +409,38 @@ class LumosSurfaceState( return t * t * (3f - 2f * t) } + private inner class FadingSource : LumosFrameSource { + override val revision: Long get() = source.revision + override val lookKey: String? get() = source.lookKey + + override fun next(dt: Float): VoxelFrame = faded(source.next(dt)) + + override fun still(dt: Float): VoxelFrame = faded(source.still(dt)) + + override fun align(lookTime: Double) = source.align(lookTime) + + override fun alignLook(lookTime: Double) = source.alignLook(lookTime) + + override fun setInput(input: LumosInput) = source.setInput(input) + + private fun faded(frame: VoxelFrame): VoxelFrame { + val mask = surplus ?: return frame + if (mask.size != frame.cells.size) return frame + val keep = 1f - surplusFade + return frame.copy( + cells = + frame.cells.mapIndexed { i, cell -> + if (mask[i]) cell.copy(alpha = (cell.alpha ?: 1f) * keep) else cell + }, + ) + } + } + private class Request( val id: String, val burst: Float, val durationSeconds: Float, + val surplus: SurfaceSurplus, ) // A target's last bounds, in root pixels, updated in place so a scrolling target allocates diff --git a/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/SurfaceSurplus.kt b/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/SurfaceSurplus.kt new file mode 100644 index 0000000..5b80162 --- /dev/null +++ b/phosphor-lumos-surface/src/commonMain/kotlin/link/socket/phosphor/lumos/surface/SurfaceSurplus.kt @@ -0,0 +1,72 @@ +package link.socket.phosphor.lumos.surface + +import kotlin.math.roundToInt +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import link.socket.phosphor.lumos.PixelForm +import link.socket.phosphor.lumos.RectPx + +/** + * What an assembly does with the cells a control does not need: the orb's count against the + * count that reads as cells on the control. + * + * The 160 px hero orb runs the lattice at resolution 10, 4,801 cells. Into a 128 × 40 button + * that is a cell every 1.1 px, which reads as a fill rather than cells; 1,141 cells, a cell every + * 2.3 px, still read as cells (PHO-68). The 20 px inline orb has 80, fewer than any control needs, + * so neither rule changes it. + */ +sealed interface SurfaceSurplus { + /** Every cell flies to the control, however densely that packs it. The default. */ + data object Keep : SurfaceSurplus + + /** + * Keep the cells a fill at [spacingPx] needs, spread evenly through the orb, and fade the + * rest out over [duration] while the burst throws them, before the morph starts and drops + * them. Nothing is cut that is still visible. A control that needs every cell keeps them all. + * + * @property duration How long the surplus takes to fade; the morph starts when it has. + * @property spacingPx The fill's spacing on the control, in pixels; see [PixelForm.roundedRect]. + */ + data class Fade( + val duration: Duration = DEFAULT_DURATION, + val spacingPx: Float = DEFAULT_SPACING_PX, + ) : SurfaceSurplus { + init { + require(duration.isPositive() && duration.isFinite()) { "duration must be > 0 and finite, was $duration" } + require(spacingPx > 0f && spacingPx.isFinite()) { "spacingPx must be > 0 and finite, was $spacingPx" } + } + + /** + * How many of [count] cells [rect] keeps: its fill at [spacingPx] over the share of cells + * [perimeterFraction] leaves inside the outline, never more than [count] and never fewer than 1. + */ + fun keep( + rect: RectPx, + count: Int, + perimeterFraction: Float = PixelForm.PERIMETER_FRACTION, + ): Int { + val fill = rect.area / (spacingPx * spacingPx) + val wanted = (fill / (1f - perimeterFraction).coerceAtLeast(MIN_FILL_SHARE)).roundToInt() + return wanted.coerceIn(1, count) + } + + companion object { + /** The fade's default length: 200 ms. */ + val DEFAULT_DURATION: Duration = 200.milliseconds + + /** PHO-68's prototype spacing, which read as cells on a 128 × 40 button: 2.3 px. */ + const val DEFAULT_SPACING_PX: Float = 2.3f + + private const val MIN_FILL_SHARE: Float = 0.05f + } + } +} + +/** + * [keep] indices of `0 until count`, ascending, at an even stride, so the cells kept are spread + * through the orb rather than one side of it: index `⌊i · count / keep⌋` for each `i`. + */ +internal fun evenSurvivors( + count: Int, + keep: Int, +): IntArray = IntArray(keep) { i -> (i.toLong() * count / keep).toInt() } diff --git a/phosphor-lumos-surface/src/commonTest/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceStateTest.kt b/phosphor-lumos-surface/src/commonTest/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceStateTest.kt index 9de24e1..ccdc3c6 100644 --- a/phosphor-lumos-surface/src/commonTest/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceStateTest.kt +++ b/phosphor-lumos-surface/src/commonTest/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceStateTest.kt @@ -13,6 +13,8 @@ import link.socket.phosphor.lumos.LiveFrameSource import link.socket.phosphor.lumos.LookClock import link.socket.phosphor.lumos.LumosConfig import link.socket.phosphor.lumos.OrbViewport +import link.socket.phosphor.lumos.RectPx +import link.socket.phosphor.lumos.SurfaceStyle import link.socket.phosphor.palette.AtmospherePresets /** @@ -121,6 +123,125 @@ class LumosSurfaceStateTest { assertTrue(seen.zipWithNext().all { (a, b) -> b >= a - 0.25f }, "arrival fell back hard: $seen") } + @Test + fun `the slot keeps its orb until the overlay has a frame to draw`() { + val state = surface() + assertTrue(state.orbInSlot) + state.assembleInto(TARGET) + + state.run(frames = 3) + assertTrue(state.orbInSlot, "the flight waits for the target's bounds and the orb stays") + + state.targetPositioned(TARGET, BUTTON, CORNER) + state.run(frames = 1) + assertNotNull(state.canvasFrame) + assertFalse(state.orbInSlot, "the overlay has the cells") + + state.run(frames = 4 * FPS) + assertEquals(SurfacePhase.Solid(TARGET), state.phase) + assertFalse(state.orbInSlot) + state.release() + assertTrue(state.orbInSlot) + } + + @Test + fun `the surface draws Dots by default`() { + assertEquals(SurfaceStyle.Dots, LumosSurfaceState(LiveFrameSource(AtmospherePresets.IDLE)).config.style) + } + + @Test + fun `every cell flies by default`() { + val state = surface() + val count = state.source.builder.currentCount + state.assembleInto(TARGET) + state.targetPositioned(TARGET, BUTTON, CORNER) + + state.run(frames = 1) + + assertTrue(state.source.builder.isMorphing) + assertEquals(count, state.source.builder.currentCount) + assertNull(state.surplus) + } + + @Test + fun `a faded surplus flies and fades under the burst then the morph keeps the rest`() { + val state = surface() + val builder = state.source.builder + val home = builder.form + val count = builder.currentCount + val fade = SurfaceSurplus.Fade(spacingPx = 8f) + val keep = fade.keep(BUTTON_RECT, count) + assertTrue(keep < count, "the test needs a surplus: keeps $keep of $count") + state.assembleInto(TARGET, surplus = fade) + state.targetPositioned(TARGET, BUTTON, CORNER) + + state.run(frames = 1) + + val mask = assertNotNull(state.surplus, "the fade starts with the flight") + assertEquals(count - keep, mask.count { it }) + assertEquals(count, builder.currentCount, "nothing is dropped while it fades") + assertTrue(builder.isMorphing, "the burst is in flight") + assertSame(home, builder.form, "the morph waits for the fade") + // Survivors are spread through the orb, not one side of it: both halves of the index range keep cells. + assertTrue(mask.take(count / 2).any { !it } && mask.drop(count / 2).any { !it }) + val drawn = assertNotNull(state.canvasFrame) + assertTrue(drawn.voxels.isNotEmpty()) + + state.run(frames = 3) + assertTrue(state.surplusFade > 0f && state.surplusFade < 1f, "fading, at ${state.surplusFade}") + + state.run(frames = 4) + assertNull(state.surplus, "faded out after 200 ms") + assertEquals(keep, builder.currentCount, "the morph dropped the surplus") + assertNotNull(state.form) + + state.run(frames = 4 * FPS) + assertEquals(SurfacePhase.Solid(TARGET), state.phase) + assertSame(home, builder.form, "the builder is cut back to the orb's form") + assertEquals(count, builder.currentCount) + } + + @Test + fun `a faded surplus dims the frame the overlay draws while it fades`() { + val state = surface() + state.assembleInto(TARGET, surplus = SurfaceSurplus.Fade(spacingPx = 8f)) + state.targetPositioned(TARGET, BUTTON, CORNER) + state.run(frames = 1) + val unfaded = assertNotNull(state.canvasFrame).voxels.sumOf { it.alpha.toDouble() } + + state.run(frames = 3) + + // About five in eight cells are leaving, at half alpha by now: the frame's ink falls by about a third. + assertTrue(state.surplusFade in 0.4f..0.6f, "fading, at ${state.surplusFade}") + val fading = assertNotNull(state.canvasFrame).voxels.sumOf { it.alpha.toDouble() } + assertTrue(fading < 0.8 * unfaded, "the frame did not dim: $fading of $unfaded") + } + + @Test + fun `a control that needs every cell keeps them all under Fade`() { + val state = surface() + val count = state.source.builder.currentCount + state.assembleInto(TARGET, surplus = SurfaceSurplus.Fade()) + state.targetPositioned(TARGET, BUTTON, CORNER) + + state.run(frames = 1) + + assertNull(state.surplus) + assertTrue(state.source.builder.isMorphing) + assertEquals(count, state.source.builder.currentCount) + } + + @Test + fun `Fade keeps the fill its spacing needs — at most the count and at least one`() { + val fade = SurfaceSurplus.Fade() + // PHO-68's button: 1,168 cells at 2.3 px, Dots' 18 % on the outline. + assertEquals(1168, fade.keep(BUTTON_RECT, 4801)) + assertEquals(500, fade.keep(BUTTON_RECT, 500)) + assertEquals(1, SurfaceSurplus.Fade(spacingPx = 1000f).keep(BUTTON_RECT, 4801)) + assertEquals(listOf(0, 3, 6), evenSurvivors(9, 3).toList()) + assertEquals(listOf(0, 2, 5, 7), evenSurvivors(10, 4).toList()) + } + @Test fun `a moving target is followed`() { val state = surface() @@ -274,5 +395,6 @@ class LumosSurfaceStateTest { // The orb's slot: centre (200, 100), radius 64. The button: 128 × 40 at the bottom right. val SLOT = Rect(136f, 36f, 264f, 164f) val BUTTON = Rect(248f, 196f, 376f, 236f) + val BUTTON_RECT = RectPx(248f, 196f, 128f, 40f, CORNER) } } diff --git a/phosphor-lumos-surface/src/jvmTest/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceSizesTest.kt b/phosphor-lumos-surface/src/jvmTest/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceSizesTest.kt new file mode 100644 index 0000000..505aa2e --- /dev/null +++ b/phosphor-lumos-surface/src/jvmTest/kotlin/link/socket/phosphor/lumos/surface/LumosSurfaceSizesTest.kt @@ -0,0 +1,261 @@ +package link.socket.phosphor.lumos.surface + +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Canvas +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.PixelMap +import androidx.compose.ui.graphics.drawscope.CanvasDrawScope +import androidx.compose.ui.graphics.toComposeImageBitmap +import androidx.compose.ui.graphics.toPixelMap +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue +import link.socket.phosphor.lumos.Forms +import link.socket.phosphor.lumos.PixelForm +import link.socket.phosphor.lumos.RectPx +import link.socket.phosphor.lumos.SurfaceStyle +import link.socket.phosphor.lumos.compose.drawVoxels +import link.socket.phosphor.lumos.compose.painter +import link.socket.phosphor.lumos.frame.LumosCanvasFrame +import org.jetbrains.skia.EncodedImageFormat +import org.jetbrains.skia.Image + +/** + * PHO-76: the surface at Socket's two sizes. The Turn-on moment is recorded at 30 fps for the + * 160 px hero orb (resolution 10, 4,801 cells) with every cell kept and with the surplus faded, + * and for the 20 px inline orb (80 Fibonacci cells), each as Dots and as Squares, into + * `build/lumos-surface-sizes//frame-NNN.png`. Each clip must settle solid with the slot + * empty. The overlay's draw time at 4,801 cells, mid-flight, is printed for the record. + */ +class LumosSurfaceSizesTest { + @Test + fun `the hero orb assembles with every cell kept`() { + for (style in STYLES) { + val clip = record("hero-dense-${style.name()}", heroSurfaceState(style), HERO_ORB_SIZE, HERO_ORB_TOP) + assertEquals(Forms.Lattice(HERO_RESOLUTION).count, clip.flightCounts.single(), "every cell flies") + } + } + + @Test + fun `the hero orb assembles with the surplus faded`() { + val keep = SurfaceSurplus.Fade().keep(BUTTON_RECT, Forms.Lattice(HERO_RESOLUTION).count) + for (style in STYLES) { + val clip = + record( + "hero-fade-${style.name()}", + heroSurfaceState(style), + HERO_ORB_SIZE, + HERO_ORB_TOP, + surplus = SurfaceSurplus.Fade(), + ) + assertEquals( + Forms.Lattice(HERO_RESOLUTION).count, + clip.flightCounts.first(), + "the surplus flies while it fades", + ) + assertEquals(keep, clip.flightCounts.last(), "only the kept cells reach the button") + } + } + + @Test + fun `the inline orb assembles with its outline thickened`() { + assertTrue(PixelForm.outlineFraction(BUTTON_RECT, INLINE_COUNT) > 0.5f) + for (style in STYLES) { + val clip = record("inline-${style.name()}", inlineSurfaceState(style), INLINE_ORB_SIZE, INLINE_ORB_TOP) + assertEquals(listOf(INLINE_COUNT), clip.flightCounts, "the inline orb's 80 cells fly") + } + // For comparison: Dots' 18 % share, 14 cells round a 322 px outline. + val thin = + inlineSurfaceState(SurfaceStyle.Dots).also { + it.outlineFraction = { + _, + _, + -> + PixelForm.PERIMETER_FRACTION + } + } + record("inline-dots-outline-18", thin, INLINE_ORB_SIZE, INLINE_ORB_TOP) + } + + @Test + fun `reports the overlay's draw time at 4801 cells`() { + for (style in STYLES) { + for (surplus in listOf(SurfaceSurplus.Keep, SurfaceSurplus.Fade())) { + val state = heroSurfaceState(style) + val clip = record(null, state, HERO_ORB_SIZE, HERO_ORB_TOP, surplus = surplus) + val (frame, arrival) = clip.midFlight + val painter = HandOffPainter(state.config.material.painter(style.painter())) + painter.arrival = arrival + painter.tint = PREVIEW_ACCENT + val bitmap = ImageBitmap(WIDTH, HEIGHT) + val canvas = Canvas(bitmap) + val scope = CanvasDrawScope() + val ms = + (0 until BENCH_ITERATIONS).map { + val t = System.nanoTime() + scope.draw(Density(1f), LayoutDirection.Ltr, canvas, Size(WIDTH.toFloat(), HEIGHT.toFloat())) { + drawVoxels(frame, painter) + } + (System.nanoTime() - t) / 1e6 + }.drop(BENCH_WARM_UP).sorted() + val name = if (surplus is SurfaceSurplus.Fade) "fade" else "dense" + println( + "[PHO-76] overlay ${style.name()} $name: ${frame.voxels.size} voxels at ${WIDTH}x$HEIGHT, " + + "arrival ${"%.2f".format(arrival)}, " + + "DRAW p50=${"%.2f".format(ms[ms.size / 2])} ms p95=${"%.2f".format(ms[ms.size * 95 / 100])} ms", + ) + } + } + } + + private class Clip( + val flightCounts: List, + val midFlight: Pair, + ) + + // Record one Turn-on into build/lumos-surface-sizes/, or nowhere when name is null, and + // check that it settles solid with the slot empty and the button drawn. + private fun record( + name: String?, + state: LumosSurfaceState, + orbSize: Dp, + orbTop: Dp, + surplus: SurfaceSurplus = SurfaceSurplus.Keep, + ): Clip { + val dir = + name?.let { + File("build/lumos-surface-sizes/$it").apply { + mkdirs() + listFiles()?.forEach(File::delete) + } + } + val scene = + SteppedScene( + WIDTH, + HEIGHT, + ) { LumosSurfacePreview(state, orbSize = orbSize, orbTop = orbTop, surplus = surplus) } + try { + var index = 0 + var image = scene.render() + val counts = mutableListOf() + var midFlight: Pair? = null + var solidAtNanos = -1L + var blank = 0 + var lastInk: FloatArray? = null + var largestShift = 0f + while (scene.nowNanos < RECORD_NANOS) { + dir?.resolve("frame-%03d.png".format(index++))?.writeBytes(png(image)) + val ink = meanInk(image) + // Blank once the orb has drawn: the frames before its first step are empty by design. + if (ink == null && lastInk != null) blank++ + // The mean colour of what is drawn, frame to frame, from the orb until the hand-off + // begins: the cells keep their colours as they leave, and the tint comes in with arrival. + val last = lastInk + if (ink != null && last != null && state.arrival == 0f) { + largestShift = maxOf(largestShift, (0..2).maxOf { abs(ink[it] - last[it]) }) + } + lastInk = ink + when (state.phase) { + is SurfacePhase.Assembling -> + state.canvasFrame?.let { frame -> + // The builder's count, not the frame's: a cell the burst throws off the surface is culled. + val count = state.source.builder.currentCount + if (counts.lastOrNull() != count) counts += count + if (midFlight == null && state.arrival >= MID_FLIGHT) midFlight = frame to state.arrival + } + is SurfacePhase.Solid -> if (solidAtNanos < 0) solidAtNanos = scene.nowNanos + SurfacePhase.Orb -> Unit + } + image = scene.renderNextFrame() + } + println( + "[PHO-76] ${name ?: "bench"}: $index frames, flight counts $counts, " + + "solid at ${solidAtNanos / 1e9} s, " + + "largest colour shift before hand-off ${"%.3f".format(largestShift)}", + ) + + assertEquals(0, blank, "${name ?: "bench"} drew $blank blank frames") + assertTrue(largestShift < MAX_COLOUR_SHIFT, "the colour jumped by $largestShift in one frame") + + assertIs(state.phase, "${name ?: "bench"} should settle within ${RECORD_NANOS / 1e9} s") + assertTrue(counts.isNotEmpty(), "the overlay never drew a frame in flight") + val settled = image.toComposeImageBitmap().toPixelMap() + assertTrue(region(settled, BUTTON).any { it != PREVIEW_BACKGROUND }, "the solid button drew nothing") + assertTrue( + region(settled, slot(orbSize, orbTop)).all { it == PREVIEW_BACKGROUND }, + "the slot is not empty once solid", + ) + return Clip(counts, checkNotNull(midFlight) { "arrival never reached $MID_FLIGHT" }) + } finally { + scene.close() + } + } + + // The mean colour, 0..1 per channel, of the pixels that are not background; null when there are none. + private fun meanInk(image: Image): FloatArray? { + val pixels = image.toComposeImageBitmap().toPixelMap() + var n = 0 + val sum = FloatArray(3) + for (y in 0 until pixels.height) { + for (x in 0 until pixels.width) { + val c = pixels[x, y] + if (c == PREVIEW_BACKGROUND) continue + sum[0] += c.red + sum[1] += c.green + sum[2] += c.blue + n++ + } + } + return if (n == 0) null else FloatArray(3) { sum[it] / n } + } + + private fun png(image: Image): ByteArray = checkNotNull(image.encodeToData(EncodedImageFormat.PNG)).bytes + + private fun slot( + size: Dp, + top: Dp, + ): IntArray { + val side = size.value.toInt() + val left = (WIDTH - side) / 2 + return intArrayOf(left, top.value.toInt(), left + side, top.value.toInt() + side) + } + + private fun region( + pixels: PixelMap, + box: IntArray, + ): List { + val (left, top, right, bottom) = box + return buildList { + for (y in top until bottom) for (x in left until right) add(pixels[x, y]) + } + } + + private fun SurfaceStyle.name(): String = this::class.simpleName!!.lowercase() + + private companion object { + const val WIDTH = 400 + const val HEIGHT = 260 + const val RECORD_NANOS = 3_600_000_000L + const val MID_FLIGHT = 0.5f + + // The largest change in the drawn mean colour between two frames before the hand-off. The + // colour cut this guards against moved it by about 0.2 in one frame. + const val MAX_COLOUR_SHIFT = 0.12f + const val INLINE_COUNT = 80 + const val BENCH_ITERATIONS = 220 + const val BENCH_WARM_UP = 20 + + val STYLES = listOf(SurfaceStyle.Dots, SurfaceStyle.Squares) + + // The button, left/top/right/bottom, and as the rect the surface measures. + val BUTTON = intArrayOf(248, 196, 376, 236) + val BUTTON_RECT = RectPx(248f, 196f, 128f, 40f, PREVIEW_CORNER_PX) + } +} diff --git a/phosphor-lumos/build.gradle.kts b/phosphor-lumos/build.gradle.kts index 5f190cf..c95b3da 100644 --- a/phosphor-lumos/build.gradle.kts +++ b/phosphor-lumos/build.gradle.kts @@ -39,7 +39,8 @@ val isPublishingToMavenLocal = it == "publishToMavenLocal" || it.endsWith(":publishToMavenLocal") } -// Per-test timeout for the browser runners; mocha's default is 2 s. +// Per-test timeout for the JS browser runner; mocha's default is 2 s. The wasmJs runner ignores +// useMocha and takes the same 60 s from karma.config.d/mocha-timeout.js. val browserTestTimeout = "60s" kotlin { @@ -73,11 +74,8 @@ kotlin { @OptIn(ExperimentalWasmDsl::class) wasmJs { - browser { - testTask { - useMocha { timeout = browserTestTimeout } - } - } + // No useMocha here: KGP skips it on a wasm target. The timeout is in karma.config.d. + browser() binaries.executable() } diff --git a/phosphor-lumos/karma.config.d/mocha-timeout.js b/phosphor-lumos/karma.config.d/mocha-timeout.js new file mode 100644 index 0000000..94e457a --- /dev/null +++ b/phosphor-lumos/karma.config.d/mocha-timeout.js @@ -0,0 +1,6 @@ +// The wasmJs browser tests' per-test timeout. KGP ignores `useMocha { timeout }` on a wasm target +// (it logs that Mocha is unsupported for Wasm and skips the block), so without this they run at +// karma-mocha's 2 s default and an overrun fails as a bare `Error`. Merged into `client.mocha`, not +// over `client`, which carries KGP's own arguments. The JS target's useMocha sets the same 60 s. +config.client = config.client || {}; +config.client.mocha = Object.assign({}, config.client.mocha, { timeout: 60000 }); diff --git a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/PixelForm.kt b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/PixelForm.kt index a5c29b7..0623161 100644 --- a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/PixelForm.kt +++ b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/PixelForm.kt @@ -86,6 +86,15 @@ object PixelForm { * Dots' element target: [perimeterFraction] of the cells on the rounded * perimeter, the rest on a grid clipped to it. * + * The spacing a count yields is [fillSpacingPx] inside and + * [outlineSpacingPx] round the edge. On a 128 × 40 button with 8 px + * corners at the default share: 4,801 cells, the hero orb's lattice at + * resolution 10, fill it every 1.1 px, which reads as a solid fill; 1,141, + * resolution 6, every 2.3 px, which reads as cells; and the inline orb's + * 80 every 8.8 px, with 14 cells 23 px apart on the outline, which no + * longer reads as an edge — [outlineFraction] gives a small count the + * share that keeps it one. + * * @param rect The element in root pixels; see [RoundedRect.rect]. * @param viewport Where the orb sits in the same root. * @param perimeterFraction Share of the cells traced on the outline, `0..1`. @@ -97,6 +106,66 @@ object PixelForm { perimeterFraction: Float = PERIMETER_FRACTION, ): RoundedRect = RoundedRect(rect, viewport, perimeterFraction) + /** + * The mean spacing in pixels of the grid [roundedRect] fills [rect] with + * when [count] cells lay out on it: `√(area / fill)`, where the fill is + * the cells not on the outline. The outline's spacing when every cell is + * on it. + */ + fun fillSpacingPx( + rect: RectPx, + count: Int, + perimeterFraction: Float = PERIMETER_FRACTION, + ): Float { + require(count >= 1) { "count must be >= 1, was $count" } + val outline = outlineCount(count, perimeterFraction) + val fill = count - outline + return if (fill >= 1) sqrt(rect.area / fill) else perimeterLength(rect) / outline + } + + /** + * The arc-length spacing in pixels of the cells [roundedRect] traces round + * [rect]'s outline at [count]; infinite when no cell is on it. + */ + fun outlineSpacingPx( + rect: RectPx, + count: Int, + perimeterFraction: Float = PERIMETER_FRACTION, + ): Float { + require(count >= 1) { "count must be >= 1, was $count" } + val outline = outlineCount(count, perimeterFraction) + return if (outline >= 1) perimeterLength(rect) / outline else Float.POSITIVE_INFINITY + } + + /** + * The share of [count] cells to put on [rect]'s outline so that it reads + * as an edge: [PERIMETER_FRACTION] at Dots' counts, and more as the count + * falls, so the outline's cells stay [OUTLINE_DENSITY] times as close as + * the fill's, about the ratio Dots' share gives 1,141 cells on a 128 × 40 + * button. Never below [PERIMETER_FRACTION]; 0.52 for the inline orb's 80 + * cells on that button. + */ + fun outlineFraction( + rect: RectPx, + count: Int, + ): Float { + require(count >= 1) { "count must be >= 1, was $count" } + // fill spacing = OUTLINE_DENSITY · outline spacing, solved for the share f: + // area · count · f² + b · f − b = 0, with b = (OUTLINE_DENSITY · perimeter)². + val a = rect.area.toDouble() * count + val b = (OUTLINE_DENSITY.toDouble() * perimeterLength(rect)).let { it * it } + val share = (-b + sqrt(b * b + 4.0 * a * b)) / (2.0 * a) + return share.toFloat().coerceIn(PERIMETER_FRACTION, 1f) + } + + /** How much closer [outlineFraction] keeps the outline's cells than the fill's. */ + const val OUTLINE_DENSITY: Float = 1.5f + + private fun outlineCount( + count: Int, + perimeterFraction: Float, + ): Int = (count * perimeterFraction).roundToInt().coerceIn(0, count) + /** * A rounded rectangle in root pixels as a form; see [roundedRect]. * diff --git a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/VoxelFrameBuilder.kt b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/VoxelFrameBuilder.kt index a5f39f4..547497d 100644 --- a/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/VoxelFrameBuilder.kt +++ b/phosphor-lumos/src/commonMain/kotlin/link/socket/phosphor/lumos/VoxelFrameBuilder.kt @@ -458,6 +458,9 @@ class VoxelFrameBuilder( // The framing the morph left from, blended toward the new form's by the morph's progress. private var morphFramingFrom: Framing = Framing.NONE + // The pattern the morph left from, blended toward the new form's the same way; see MixFrom. + private var morphMixFrom: MixFrom? = null + // The last frame time the form was sampled at, so morphTo samples the form where build did. private var lastTimeSeconds: Float = 0f @@ -527,14 +530,21 @@ class VoxelFrameBuilder( * unit-sphere space before the atmosphere's pulse, squash and bump, which * keep applying on top: the skin rides the body. A [FramedForm]'s scale and * cell size blend across with the spring's own progress, and so does a - * [FramedForm.rigid] form's hold on the skin. Once settled, the - * builder renders the new form exactly as it renders any form at rest, with - * no per-frame cost and with its cells in the matched order — which is what + * [FramedForm.rigid] form's hold on the skin. So does each cell's colour: + * the atmosphere's pattern is read where the cell sat in the form it left + * and where it is heading, and mixed by the same progress, so a form whose + * pattern reads differently does not recolour the orb on the first frame. + * A spawned cell starts from the colour of the cell it springs out of. + * Once settled, the builder renders the new form exactly as it renders any + * form at rest, with no per-frame cost and with its cells in the matched order — which is what * keeps a trace's per-index delta coding and a crossfade's cell pairing * working across the change. * * Equal counts are the common case. With a smaller [count], the cells with - * the highest indices are dropped and the rest are matched. With a larger + * the highest indices are dropped and the rest are matched, unless + * [survivors] names the ones to keep. On the lattice the highest indices + * are one side of the orb, so dropping a spread of cells takes a + * [survivors] list at an even stride. With a larger * one, the cells that exist are matched first and the new form's leftover * positions become new cells, which start at the current position of the * nearest existing cell and spring out from there. Either way, the frame on @@ -562,8 +572,13 @@ class VoxelFrameBuilder( * @param durationSeconds How long the spring takes to settle. `0` snaps. * @param easingName An `Easing.byName` identifier that reshapes the arc's * envelope only; null or unknown leaves it linear. The spring is not eased. - * @throws IllegalArgumentException when [count] is not positive or - * [durationSeconds] is negative. + * @param survivors When the new form has fewer cells than the orb, the + * cells that stay, by index, ascending: survivor `i` becomes cell `i`. + * Null, the default, keeps the lowest indices. Ignored unless the count + * shrinks. + * @throws IllegalArgumentException when [count] is not positive, + * [durationSeconds] is negative, or [survivors] is not as many strictly + * ascending indices of today's cells as the new form has. */ fun morphTo( form: LumosForm, @@ -571,6 +586,7 @@ class VoxelFrameBuilder( choreography: Choreography = Choreography.FLOW, durationSeconds: Float = DEFAULT_MORPH_SECONDS, easingName: String? = null, + survivors: IntArray? = null, ) { require(count >= 1) { "count must be >= 1, was $count" } require(durationSeconds >= 0f && durationSeconds.isFinite()) { @@ -583,8 +599,22 @@ class VoxelFrameBuilder( val fromPermutation = permutation val fromMorph = morph val fromCount = fromSample.count + val toSample = sampleForm(target, lastTimeSeconds, phases, gaze = gaze) + val toCount = toSample.count + val matched = minOf(fromCount, toCount) + // Which of today's cells each surviving cell was: the lowest indices, or the survivors given. + val kept = survivors?.takeIf { toCount < fromCount } + if (kept != null) { + require(kept.size == toCount) { "survivors must name $toCount cells, named ${kept.size}" } + for (i in kept.indices) { + require(kept[i] in 0 until fromCount && (i == 0 || kept[i] > kept[i - 1])) { + "survivors must be ascending indices below $fromCount, found ${kept[i]} at $i" + } + } + } val origins = - List(fromCount) { i -> + List(matched) { k -> + val i = kept?.get(k) ?: k if (fromMorph != null) { Vector3(fromMorph.positions[3 * i], fromMorph.positions[3 * i + 1], fromMorph.positions[3 * i + 2]) } else { @@ -593,37 +623,45 @@ class VoxelFrameBuilder( } val framingFrom = effectiveFraming(fromSample) - val toSample = sampleForm(target, lastTimeSeconds, phases, gaze = gaze) - val toCount = toSample.count - val matched = minOf(fromCount, toCount) - val assignment = matcher.match(origins.subList(0, matched), toSample.positions) + val assignment = matcher.match(origins, toSample.positions) val nextPermutation = IntArray(toCount) assignment.copyInto(nextPermutation) + // The sample index each cell was coloured by in the form being left; a spawned cell takes its parent's. + val mixFromIndex = IntArray(toCount) { -1 } + for (k in 0 until matched) { + val i = kept?.get(k) ?: k + mixFromIndex[k] = fromPermutation?.get(i) ?: i + } val body = FormMorph(toCount) - for (i in 0 until matched) { - val origin = origins[i] - body.positions[3 * i] = origin.x - body.positions[3 * i + 1] = origin.y - body.positions[3 * i + 2] = origin.z + for (k in 0 until matched) { + val origin = origins[k] + body.positions[3 * k] = origin.x + body.positions[3 * k + 1] = origin.y + body.positions[3 * k + 2] = origin.z if (fromMorph != null) { - body.velocities[3 * i] = fromMorph.velocities[3 * i] - body.velocities[3 * i + 1] = fromMorph.velocities[3 * i + 1] - body.velocities[3 * i + 2] = fromMorph.velocities[3 * i + 2] + val i = kept?.get(k) ?: k + body.velocities[3 * k] = fromMorph.velocities[3 * i] + body.velocities[3 * k + 1] = fromMorph.velocities[3 * i + 1] + body.velocities[3 * k + 2] = fromMorph.velocities[3 * i + 2] } } // A burst keeps its own clock, so moving it to the new body carries it on where it was. The // pointer's repel moves with it, and the next build aims it at the new body. if (fromMorph != null) body.forces.addAll(fromMorph.forces) - if (toCount > fromCount) spawnLeftovers(nextPermutation, assignment, origins, toSample.positions, body) + if (toCount > fromCount) { + spawnLeftovers(nextPermutation, assignment, origins, toSample.positions, body, mixFromIndex) + } // Not through the public setter, which would reset the identity just built. adoptForm(target) permutation = nextPermutation if (durationSeconds == 0f) { morph = null + morphMixFrom = null return } morphFramingFrom = framingFrom + morphMixFrom = MixFrom(body, fromSample, mixFromIndex) body.retarget( targets = toSample.positions, assignment = nextPermutation, @@ -691,6 +729,7 @@ class VoxelFrameBuilder( durationSeconds = durationSeconds, ) morphFramingFrom = framing(sample) + morphMixFrom = null morph = body return body } @@ -706,6 +745,7 @@ class VoxelFrameBuilder( origins: List, targets: List, body: FormMorph, + mixFromIndex: IntArray, ) { val taken = BooleanArray(targets.size) for (j in assignment) taken[j] = true @@ -716,13 +756,16 @@ class VoxelFrameBuilder( val target = targets[j] var nearest = Vector3.ZERO var nearestDistance = Float.POSITIVE_INFINITY - for (origin in origins) { - val d = (origin - target).lengthSquared() + var parent = -1 + for (k in origins.indices) { + val d = (origins[k] - target).lengthSquared() if (d < nearestDistance) { nearestDistance = d - nearest = origin + nearest = origins[k] + parent = k } } + if (parent >= 0) mixFromIndex[cell] = mixFromIndex[parent] body.positions[3 * cell] = nearest.x body.positions[3 * cell + 1] = nearest.y body.positions[3 * cell + 2] = nearest.z @@ -1050,6 +1093,7 @@ class VoxelFrameBuilder( permutation = permutation, morphPositions = body?.positions, framing = if (body == null) framing(sample) else effectiveFraming(sample), + mixFrom = morphMixFrom?.takeIf { it.body === body && it.body.isSettling }, modulator = modulator, outgoing = outgoing, outgoingTime = outgoingTime, @@ -1101,6 +1145,7 @@ class VoxelFrameBuilder( val body = restingBody?.takeIf { it.count == sample.count } ?: FormMorph(sample.count) body.snapTo(sample.positions, permutation) restingBody = body + morphMixFrom = null morph = body return body } @@ -1299,6 +1344,7 @@ class VoxelFrameBuilder( permutation: IntArray?, morphPositions: FloatArray?, framing: Framing, + mixFrom: MixFrom? = null, modulator: LookModulator?, outgoing: LookModulator?, outgoingTime: Float, @@ -1359,7 +1405,16 @@ class VoxelFrameBuilder( val cells = ArrayList(sample.count) for (cell in 0 until sample.count) { val index = permutation?.get(cell) ?: cell - val mix = computeMix(atmosphere, transition, sample, index, phases.patternPhase) + var mix = computeMix(atmosphere, transition, sample, index, phases.patternPhase) + if (mixFrom != null) { + // Mid-morph a cell's pattern turns from the form it left to the one it is heading for, + // with the spring, so its colour travels with it rather than cutting on the first frame. + val fromIndex = mixFrom.indices[cell] + if (fromIndex >= 0) { + val left = computeMix(atmosphere, transition, mixFrom.sample, fromIndex, phases.patternPhase) + mix = left + (mix - left) * mixFrom.body.progress + } + } val boundaryShrink = computeBoundaryShrink(atmosphere.bipolarStrength, mix) val baseColor = computeVoxelColor(atmosphere, transition, mix) val direction = directions[index] @@ -1592,6 +1647,16 @@ class VoxelFrameBuilder( ) } + /** + * Where a morph's colours start: the sample the form being left was drawn from, and the index + * each of [body]'s cells read in it, or -1. Applies only while [body] is the morph in flight. + */ + private class MixFrom( + val body: FormMorph, + val sample: FormSample, + val indices: IntArray, + ) + /** * A [FramedForm]'s framing resolved against the lattice: [formScale] * multiplies every position, [cellScale] every cell's scale, and @@ -1599,6 +1664,7 @@ class VoxelFrameBuilder( * `1` for a [FramedForm.rigid] form at rest. [NONE] is the lattice's own, * and leaves every frame as it was before forms were framed. */ + private class Framing(val formScale: Float, val cellScale: Float, val rigidity: Float = 0f) { companion object { val NONE = Framing(1f, 1f) diff --git a/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/PixelFormTest.kt b/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/PixelFormTest.kt index 80ab724..1a00e46 100644 --- a/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/PixelFormTest.kt +++ b/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/PixelFormTest.kt @@ -181,6 +181,43 @@ class PixelFormTest { assertEquals(0.5f * spacingPx / viewport.radiusPx, form.cellRadius(count), 1e-6f) } + @Test + fun `spacing on Socket's 128 by 40 button at the hero and inline counts`() { + val turnOn = RectPx(left = 0f, top = 0f, width = 128f, height = 40f, cornerRadius = 8f) + assertEquals(1.13f, PixelForm.fillSpacingPx(turnOn, 4801), 0.01f) + assertEquals(2.33f, PixelForm.fillSpacingPx(turnOn, 1141), 0.01f) + assertEquals(8.76f, PixelForm.fillSpacingPx(turnOn, 80), 0.01f) + assertEquals(23.0f, PixelForm.outlineSpacingPx(turnOn, 80), 0.1f) + // Every cell on the outline: the fill's spacing is the outline's. + assertEquals(PixelForm.outlineSpacingPx(turnOn, 40, 1f), PixelForm.fillSpacingPx(turnOn, 40, 1f)) + assertEquals(Float.POSITIVE_INFINITY, PixelForm.outlineSpacingPx(turnOn, 40, 0f)) + // The spacing a form lays out is the one its cells are sized by. + val viewport = OrbViewport(centerXPx = 64f, centerYPx = 20f, radiusPx = 80f) + assertEquals( + 0.5f * PixelForm.fillSpacingPx(turnOn, 1141) / 80f, + PixelForm.roundedRect(turnOn, viewport).cellRadius(1141), + 1e-6f, + ) + } + + @Test + fun `outlineFraction is Dots' share at its counts and more as the count falls`() { + val turnOn = RectPx(left = 0f, top = 0f, width = 128f, height = 40f, cornerRadius = 8f) + assertEquals(PixelForm.PERIMETER_FRACTION, PixelForm.outlineFraction(turnOn, 4801)) + // Dots' share at the count it was tuned on, give or take the rounding of its ratio to 1.5. + assertEquals(PixelForm.PERIMETER_FRACTION, PixelForm.outlineFraction(turnOn, 1141), 0.005f) + val inline = PixelForm.outlineFraction(turnOn, 80) + assertEquals(0.52f, inline, 0.01f) + // Below Dots' counts the outline's cells sit OUTLINE_DENSITY times as close as the fill's. + assertEquals( + PixelForm.OUTLINE_DENSITY, + PixelForm.fillSpacingPx(turnOn, 80, inline) / PixelForm.outlineSpacingPx(turnOn, 80, inline), + 0.15f, + ) + assertTrue(PixelForm.outlineFraction(turnOn, 8) > inline) + assertTrue(PixelForm.outlineFraction(turnOn, 1) <= 1f) + } + @Test fun `counted keeps a view form a rigid view form`() { val counted = assertIs(PixelForm.roundedRect(button, viewport).counted(90)) diff --git a/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/VoxelFrameBuilderMorphTest.kt b/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/VoxelFrameBuilderMorphTest.kt index f937759..3a2b8c8 100644 --- a/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/VoxelFrameBuilderMorphTest.kt +++ b/phosphor-lumos/src/commonTest/kotlin/link/socket/phosphor/lumos/VoxelFrameBuilderMorphTest.kt @@ -222,6 +222,65 @@ class VoxelFrameBuilderMorphTest { } } + @Test + fun `a cell keeps its colour on the first frame of a morph rather than taking the new form's`() { + val pattern = AtmospherePresets.THINKING.copy(resolution = resolution, noise = 0f, surfaceBump = 0f) + val cut = VoxelFrameBuilder(initialResolution = resolution) + val builder = VoxelFrameBuilder(initialResolution = resolution) + val before = builder.build(snapshot(pattern, 0f), dt = 0f) + cut.build(snapshot(pattern, 0f), dt = 0f) + + builder.morphTo(Forms.Cube, choreography = Choreography.DIRECT, durationSeconds = 1f) + val first = builder.build(snapshot(pattern, 0f), dt = 0f) + cut.form = Forms.Cube + val recoloured = cut.build(snapshot(pattern, 0f), dt = 0f) + + fun shift( + a: VoxelCell, + b: VoxelCell, + ) = abs(a.red - b.red) + abs(a.green - b.green) + abs(a.blue - b.blue) + // The premise: the cube's pattern colours the orb differently from the lattice's. + val cutShift = before.cells.indices.sumOf { shift(before.cells[it], recoloured.cells[it]).toDouble() } + assertTrue(cutShift > 0.5, "the cube recolours too little to test against: $cutShift") + for (i in before.cells.indices) { + assertTrue(shift(before.cells[i], first.cells[i]) < 1e-3f, "cell $i changed colour on the first frame") + } + } + + @Test + fun `survivors name the cells a smaller count keeps — survivor i becomes cell i`() { + val builder = VoxelFrameBuilder(initialResolution = resolution) + val before = builder.build(snapshot(still, 0f), dt = 0f) + val count = before.cells.size + val survivors = IntArray(count / 3) { it * 3 } + + builder.morphTo(Forms.Fibonacci, count = survivors.size, durationSeconds = 1f, survivors = survivors) + val after = builder.build(snapshot(still, 0f), dt = 0f) + + assertEquals(survivors.size, after.cells.size) + for (k in survivors.indices) { + val was = before.cells[survivors[k]] + val now = after.cells[k] + val moved = abs(was.x - now.x) + abs(was.y - now.y) + abs(was.z - now.z) + assertTrue(moved < 1e-3f, "survivor $k is not where cell ${survivors[k]} was: moved $moved") + } + } + + @Test + fun `survivors must be as many ascending indices as the new form has`() { + val builder = VoxelFrameBuilder(initialResolution = resolution) + val count = builder.build(snapshot(still, 0f), dt = 0f).cells.size + assertFailsWith { + builder.morphTo(Forms.Fibonacci, count = 3, survivors = intArrayOf(0, 1)) + } + assertFailsWith { + builder.morphTo(Forms.Fibonacci, count = 3, survivors = intArrayOf(0, 2, 1)) + } + assertFailsWith { + builder.morphTo(Forms.Fibonacci, count = 3, survivors = intArrayOf(0, 1, count)) + } + } + @Test fun `morphing to the current form at the current count is a no-op`() { val builder = VoxelFrameBuilder(initialResolution = resolution) diff --git a/phosphor-trace/build.gradle.kts b/phosphor-trace/build.gradle.kts index 9f844a5..7d8a4a0 100644 --- a/phosphor-trace/build.gradle.kts +++ b/phosphor-trace/build.gradle.kts @@ -38,7 +38,8 @@ val isPublishingToMavenLocal = it == "publishToMavenLocal" || it.endsWith(":publishToMavenLocal") } -// Per-test timeout for the browser runners; mocha's default is 2 s. +// Per-test timeout for the JS browser runner; mocha's default is 2 s. The wasmJs runner ignores +// useMocha and takes the same 60 s from karma.config.d/mocha-timeout.js. val browserTestTimeout = "60s" kotlin { @@ -62,11 +63,8 @@ kotlin { @OptIn(ExperimentalWasmDsl::class) wasmJs { - browser { - testTask { - useMocha { timeout = browserTestTimeout } - } - } + // No useMocha here: KGP skips it on a wasm target. The timeout is in karma.config.d. + browser() } val xcf = XCFramework() diff --git a/phosphor-trace/karma.config.d/mocha-timeout.js b/phosphor-trace/karma.config.d/mocha-timeout.js new file mode 100644 index 0000000..94e457a --- /dev/null +++ b/phosphor-trace/karma.config.d/mocha-timeout.js @@ -0,0 +1,6 @@ +// The wasmJs browser tests' per-test timeout. KGP ignores `useMocha { timeout }` on a wasm target +// (it logs that Mocha is unsupported for Wasm and skips the block), so without this they run at +// karma-mocha's 2 s default and an overrun fails as a bare `Error`. Merged into `client.mocha`, not +// over `client`, which carries KGP's own arguments. The JS target's useMocha sets the same 60 s. +config.client = config.client || {}; +config.client.mocha = Object.assign({}, config.client.mocha, { timeout: 60000 });