FPS pacer work (#2086)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2026-09-08 23:01:21 -07:00
1 parent 6f054a09a9
commit 2845c9e078
44 files changed
+3304 -491

No files matched your search

@@ -1,152 +1,252 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.glsm.backend.RenderBackend.GateSample;
import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import com.gtnewhorizons.angelica.glsm.testutil.Reflect;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.function.LongConsumer;
import java.util.function.LongSupplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class FramePacerTest {
@Test
void vsyncStillHonoursTheCap() {
assertEquals(60, FramePacer.pacingCeilingHz(VSyncMode.ON, 60, 144, true));
assertEquals(30, FramePacer.pacingCeilingHz(VSyncMode.ON, 30, 144, false));
}
private static final long CLOCK_TICK_NANOS = 1_000L;
@Test
void anActiveGateGetsTheHeadroomBackstop() {
assertEquals(151, FramePacer.pacingCeilingHz(VSyncMode.ON, 0, 144, true));
assertEquals(151, FramePacer.pacingCeilingHz(VSyncMode.ON, 260, 144, true));
}
private static final class FakeBackend implements FramePacer.Backend {
VSyncMode mode = VSyncMode.ON;
long refreshPeriodNanos;
boolean vsyncHonored = true;
int displayGeneration;
long gpuWaitNanos;
long gateDurationNanos;
long gateEndNanos;
long now;
@Test
void aQuietGateGetsThePlainRefreshBackstopToAvoidQueueSaturation() {
assertEquals(144, FramePacer.pacingCeilingHz(VSyncMode.ON, 0, 144, false));
assertEquals(144, FramePacer.pacingCeilingHz(VSyncMode.ON, 260, 144, false));
}
int awaitPresentCalls;
int readGateSampleCalls;
int parkCalls;
int pumpCalls;
boolean awaitedBeforeRead;
boolean readBeforePump;
boolean parkedBeforePump;
@Test
void mailboxGetsThePlainRefreshBackstopRegardlessOfTheGate() {
assertEquals(60, FramePacer.pacingCeilingHz(VSyncMode.MAILBOX, 0, 60, false));
assertEquals(60, FramePacer.pacingCeilingHz(VSyncMode.MAILBOX, 0, 60, true));
assertEquals(45, FramePacer.pacingCeilingHz(VSyncMode.MAILBOX, 45, 60, false));
}
@Test
void vsyncOffIsBoundedOnlyByTheCap() {
assertEquals(0, FramePacer.pacingCeilingHz(VSyncMode.OFF, 0, 144, false));
assertEquals(215, FramePacer.pacingCeilingHz(VSyncMode.OFF, 215, 144, false));
assertEquals(0, FramePacer.pacingCeilingHz(VSyncMode.OFF, -1, 144, false));
}
@Test
void anUnknownRefreshRateLeavesTearFreeModesUnbounded() {
assertEquals(0, FramePacer.pacingCeilingHz(VSyncMode.ON, 0, 0, true));
assertEquals(0, FramePacer.pacingCeilingHz(VSyncMode.ON, 0, 19, false));
assertEquals(0, FramePacer.pacingCeilingHz(VSyncMode.ON, 0, 1001, true));
assertEquals(215, FramePacer.pacingCeilingHz(VSyncMode.ON, 215, 1001, true));
}
@Test
void gateThresholdScalesWithThePeriodAboveAFloor() {
assertEquals(100_000L, FramePacer.gateBlockThresholdNanos(1_000_000L));
assertEquals(173_611L, FramePacer.gateBlockThresholdNanos(5_555_555L));
assertEquals(520_833L, FramePacer.gateBlockThresholdNanos(16_666_666L));
}
@Test
void implausibleRefreshIsIgnored() {
assertEquals(0, FramePacer.plausibleRefreshHz(0));
assertEquals(0, FramePacer.plausibleRefreshHz(-1));
assertEquals(0, FramePacer.plausibleRefreshHz(19));
assertEquals(0, FramePacer.plausibleRefreshHz(1001));
assertEquals(20, FramePacer.plausibleRefreshHz(20));
assertEquals(1000, FramePacer.plausibleRefreshHz(1000));
}
@Test
void headroomRoundsToTheNearestHz() {
assertEquals(21, FramePacer.withHeadroom(20, FramePacer.PACING_HEADROOM_PERCENT));
assertEquals(62, FramePacer.withHeadroom(59, FramePacer.PACING_HEADROOM_PERCENT));
assertEquals(63, FramePacer.withHeadroom(60, FramePacer.PACING_HEADROOM_PERCENT));
assertEquals(151, FramePacer.withHeadroom(144, FramePacer.PACING_HEADROOM_PERCENT));
assertEquals(252, FramePacer.withHeadroom(240, FramePacer.PACING_HEADROOM_PERCENT));
assertEquals(1050, FramePacer.withHeadroom(1000, FramePacer.PACING_HEADROOM_PERCENT));
}
@Test
void headroomAlwaysClearsTheRefreshRate() {
for (int hz = 20; hz <= 1000; hz++) {
assertTrue(FramePacer.withHeadroom(hz, FramePacer.PACING_HEADROOM_PERCENT) > hz, "headroom must exceed " + hz + "Hz");
assertTrue(FramePacer.withHeadroom(hz, 0) > hz, "a zero-percent headroom must still exceed " + hz + "Hz");
@Override
public VSyncMode effectiveVSyncMode() {
return mode;
}
assertEquals(0, FramePacer.withHeadroom(0, FramePacer.PACING_HEADROOM_PERCENT));
}
@Test
void theDeadlineAdvancesByExactlyOnePeriodDespiteJitter() {
final long target = 16_666_666L;
long deadline = FramePacer.nextDeadline(0L, 1_000L, target);
assertEquals(1_000L + target, deadline);
@Override
public long refreshPeriodNanos() {
return refreshPeriodNanos;
}
final long first = deadline;
final long[] wakeJitter = { -400_000L, 900_000L, -120_000L, 250_000L };
for (int i = 0; i < wakeJitter.length; i++) {
deadline = FramePacer.nextDeadline(deadline, deadline + wakeJitter[i], target);
assertEquals(first + target * (i + 1), deadline, "jitter must not accumulate into the deadline");
@Override
public boolean vsyncHonored() {
return vsyncHonored;
}
@Override
public int displayGeneration() {
return displayGeneration;
}
@Override
public void awaitPresent() {
awaitPresentCalls++;
}
@Override
public void readGateSample(GateSample out) {
readGateSampleCalls++;
awaitedBeforeRead = awaitPresentCalls > 0;
out.durationNanos = gateDurationNanos;
out.endNanos = gateEndNanos;
out.gpuWaitNanos = gpuWaitNanos;
}
@Override
public void pumpDisplayMessages() {
pumpCalls++;
readBeforePump = readGateSampleCalls > 0;
parkedBeforePump = parkCalls > 0;
}
@Override
public void parkNanos(long nanos) {
parkCalls++;
now += nanos;
}
@Override
public long nanoTime() {
final long t = now;
now += CLOCK_TICK_NANOS;
return t;
}
}
@Test
void aPeriodChangeKeepsThePhaseInsteadOfRestartingIt() {
final long previousDeadline = 1_000_000_000L;
final long newTarget = 1_000_000_000L / 76;
final long now = previousDeadline + 200_000L;
assertEquals(previousDeadline + newTarget, FramePacer.nextDeadline(previousDeadline, now, newTarget));
@BeforeEach
void freshPacerState() {
final PacerSleeper previous = Reflect.getStatic(FramePacer.class, "sleeper");
final LongSupplier clock = Reflect.get(previous, "clock");
final LongConsumer parker = Reflect.get(previous, "parker");
final PacerSleeper sleeper = new PacerSleeper(clock, parker, true);
Reflect.setStatic(FramePacer.class, "sleeper", sleeper);
Reflect.setStatic(FramePacer.class, "core", new PacerCore(clock, sleeper));
Reflect.setStatic(FramePacer.class, "lastDisplayGeneration", 0);
Reflect.setStatic(FramePacer.class, "warnedUncapped", false);
Reflect.setStatic(FramePacer.class, "loggedMode", null);
Reflect.setStatic(FramePacer.class, "loggedRefreshHz", 0);
Reflect.setStatic(FramePacer.class, "loggedCapHz", 0);
Reflect.setStatic(FramePacer.class, "loggedEffectiveCapHz", 0);
Reflect.setStatic(FramePacer.class, "loggedLocked", false);
Reflect.setStatic(FramePacer.class, "loggedProbing", false);
}
private static void withBackend(FramePacer.Backend fake, Runnable body) {
final FramePacer.Backend original = Reflect.getStatic(FramePacer.class, "BACKEND");
Reflect.setStatic(FramePacer.class, "BACKEND", fake);
try {
body.run();
} finally {
Reflect.setStatic(FramePacer.class, "BACKEND", original);
}
}
@ParameterizedTest(name = "{0} refresh={1} cap={2}->{3} locked={4} probing={5}")
@CsvSource(nullValues = "null", value = {
"ON, 60, 0, 0, true, false, ' [vsync 60]'",
"ON, 60, 30, 30, true, false, ' [vsync 60, cap 30 -> 30]'",
"ON, 144, 50, 48, true, false, ' [vsync 144, cap 50 -> 48]'",
"MAILBOX, 144, 0, 0, false, false, ' [mailbox 144]'",
"OFF, 144, 100, 100, false, false, ' [cap 100]'",
"ON, 60, 0, 0, false, true, ' [vsync 60, probing]'",
"ON, 60, 0, 0, false, false, ' [vsync 60, wall clock]'",
"OFF, 144, 0, 0, false, false, null",
})
void theIndicatorNamesEveryPacingState(VSyncMode mode, int refreshHz, int capHz, int effectiveCapHz, boolean locked, boolean probing, String expected) {
assertEquals(expected, FramePacer.debugIndicator(mode, refreshHz, capHz, effectiveCapHz, locked, probing));
}
@ParameterizedTest(name = "{0} refresh={1} cap={2}->{3} locked={4} probing={5}")
@CsvSource({
"ON, 60, 0, 0, true, false, 'Frame pacing: vsync 60Hz, hardware paced'",
"ON, 60, 0, 0, false, true, 'Frame pacing: vsync 60Hz, probing'",
"ON, 60, 0, 0, false, false, 'Frame pacing: vsync 60Hz, driver not blocking, paced by wall clock'",
"MAILBOX, 144, 0, 0, true, false, 'Frame pacing: mailbox 144Hz'",
"OFF, 144, 100, 100, false, false, 'Frame pacing: vsync off, cap 100'",
"ON, 60, 30, 30, true, false, 'Frame pacing: vsync 60Hz, hardware paced, cap 30'",
"ON, 144, 50, 48, true, false, 'Frame pacing: vsync 144Hz, hardware paced, cap 50 -> 48'",
})
void thePacingLineNamesEveryPacingState(VSyncMode mode, int refreshHz, int capHz, int effectiveCapHz, boolean locked, boolean probing, String expected) {
assertEquals(expected, FramePacer.pacingLine(mode, refreshHz, capHz, effectiveCapHz, locked, probing));
}
@Test
void fallingMoreThanTwoPeriodsBehindResynchronises() {
final long target = 16_666_666L;
final long deadline = 1_000_000_000L;
final long lateNow = deadline + target * 3;
assertEquals(lateNow + target, FramePacer.nextDeadline(deadline, lateNow, target));
void settersAreAppliedBeforeBeginFrame() {
final FakeBackend backend = new FakeBackend();
backend.mode = VSyncMode.OFF;
backend.vsyncHonored = false;
withBackend(backend, () -> {
FramePacer.endFrame(60, null);
assertTrue(FramePacer.pacedLastFrame(), "a nonzero cap must pace even under vsync off");
});
}
@Test
void indicatorNamesWhatIsHoldingTheRateDown() {
assertEquals(" [vsync 144]", FramePacer.debugIndicator(VSyncMode.ON, 144, 0, false));
assertEquals(" [vsync 144, cap 60]", FramePacer.debugIndicator(VSyncMode.ON, 144, 60, false));
assertEquals(" [cap 215]", FramePacer.debugIndicator(VSyncMode.OFF, 144, 215, false));
assertEquals(" [mailbox 144]", FramePacer.debugIndicator(VSyncMode.MAILBOX, 144, 0, false));
void awaitPresentPrecedesReadGateSampleOnlyWhenVsyncOnAndHonored() {
final FakeBackend honored = new FakeBackend();
honored.mode = VSyncMode.ON;
honored.vsyncHonored = true;
withBackend(honored, () -> {
FramePacer.endFrame(0, null);
assertEquals(1, honored.awaitPresentCalls);
assertTrue(honored.awaitedBeforeRead);
});
final FakeBackend notHonored = new FakeBackend();
notHonored.mode = VSyncMode.ON;
notHonored.vsyncHonored = false;
withBackend(notHonored, () -> {
FramePacer.endFrame(60, null);
assertEquals(0, notHonored.awaitPresentCalls);
assertEquals(1, notHonored.readGateSampleCalls);
});
final FakeBackend off = new FakeBackend();
off.mode = VSyncMode.OFF;
withBackend(off, () -> {
FramePacer.endFrame(60, null);
assertEquals(0, off.awaitPresentCalls);
assertEquals(1, off.readGateSampleCalls);
});
}
@Test
void indicatorOmitsACapTheBackstopAlreadyBeats() {
assertEquals(" [vsync 144]", FramePacer.debugIndicator(VSyncMode.ON, 144, 260, false));
void endFramePumpsExactlyOnceAfterTheGateReadAndThePacingSleep() {
final FakeBackend backend = new FakeBackend();
backend.mode = VSyncMode.OFF;
withBackend(backend, () -> {
FramePacer.endFrame(60, null);
assertEquals(1, backend.pumpCalls);
assertTrue(backend.readBeforePump, "the gate sample must be read before the window is pumped");
FramePacer.endFrame(60, null);
assertEquals(2, backend.pumpCalls);
assertTrue(backend.parkedBeforePump, "the pump must follow the pacing sleep, not precede it");
});
}
@Test
void indicatorStillReportsVsyncWithoutARefreshRate() {
assertEquals(" [vsync]", FramePacer.debugIndicator(VSyncMode.ON, 0, 0, false));
assertEquals(" [vsync, cap 60]", FramePacer.debugIndicator(VSyncMode.ON, 0, 60, false));
void gpuWaitFedToTheCoreEqualsBackendGpuWaitPlusTheFenceWait() {
final FakeBackend backend = new FakeBackend();
backend.mode = VSyncMode.OFF;
backend.gpuWaitNanos = 500_000L;
final long fenceNanos = 5_000_000L;
withBackend(backend, () -> {
FramePacer.endFrame(0, () -> backend.now += fenceNanos);
final long fed = FramePacer.core.lastGpuWaitNanos();
assertEquals(backend.gpuWaitNanos + fenceNanos + CLOCK_TICK_NANOS, fed);
});
}
@Test
void indicatorIsAbsentWhenNothingLimits() {
assertNull(FramePacer.debugIndicator(VSyncMode.OFF, 144, 0, false));
assertNull(FramePacer.debugIndicator(VSyncMode.OFF, 0, 0, false));
void endFrameReturnsThePresentInterval() {
final FakeBackend backend = new FakeBackend();
backend.mode = VSyncMode.OFF;
withBackend(backend, () -> {
FramePacer.endFrame(0, null);
final long firstPresent = backend.nanoTime();
FramePacer.core.beforePresent(firstPresent, 0L);
FramePacer.endFrame(0, null);
backend.now += 7_000_000L;
final long secondPresent = backend.nanoTime();
FramePacer.core.beforePresent(secondPresent, 0L);
final long returned = FramePacer.endFrame(0, null);
assertEquals(secondPresent - firstPresent, returned);
});
}
@Test
void endingTheStatsPutsThemBackToSleep() {
FramePacer.beginStats();
assertTrue(FramePacer.statsActive());
void aDisplayGenerationChangeReArmsTheProbe() {
final FakeBackend backend = new FakeBackend();
backend.mode = VSyncMode.ON;
backend.vsyncHonored = true;
backend.refreshPeriodNanos = 16_666_666L;
withBackend(backend, () -> {
for (int i = 0; i < 60; i++) FramePacer.endFrame(0, null);
assertFalse(FramePacer.core.probing(), "the probe must exhaust its lead without ever locking");
FramePacer.endStats();
assertFalse(FramePacer.statsActive(), "a cancelled run must not leave the bookkeeping running forever");
backend.displayGeneration++;
FramePacer.endFrame(0, null);
assertTrue(FramePacer.core.probing(), "a display change must re-arm the probe");
});
}
}
@@ -0,0 +1,614 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.glsm.testutil.Reflect;
import org.junit.jupiter.api.Test;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.function.LongConsumer;
import java.util.function.LongSupplier;
import java.util.function.ObjIntConsumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PacerCoreSimTest {
private static final long US = 1_000L;
private static final long MS = 1_000_000L;
private static final int FRAMES = 3000;
private static final int WARMUP = 300;
private static final long LAG_MEAN = 30 * US;
private static final long JITTER = 10 * US;
private static final long SEED = 987654321L;
private static final int MAILBOX_IMAGES = 2;
private static final long P60 = 1_000_000_000L / 60;
private static final long P5994 = 1_000_000_000L * 1001 / 60_000;
private static final long P144 = 1_000_000_000L / 144;
private enum Mode {
FIFO, MAILBOX, IMMEDIATE
}
private enum Gate {
SWAP, FIRST_CLEAR, NONE
}
private static final class FakeClock implements LongSupplier {
long now;
@Override
public long getAsLong() {
return now;
}
}
private static final class FakeSleeper implements LongConsumer {
private final FakeClock clock;
private final Random rng = new Random(SEED);
private final long granularity;
int parks;
FakeSleeper(FakeClock clock, long granularity) {
this.clock = clock;
this.granularity = granularity;
}
@Override
public void accept(long request) {
parks++;
long actual = request + LAG_MEAN + rng.nextInt(2 * (int) JITTER + 1) - JITTER;
if (actual < 0L) actual = 0L;
if (granularity > 0L) actual = Math.max(granularity, (actual + granularity - 1) / granularity * granularity);
clock.now += actual;
}
}
private static final class Frame {
final int index;
final long frameStart;
final long ready;
long entry;
long showTime = -1L;
Frame(int index, long frameStart, long ready) {
this.index = index;
this.frameStart = frameStart;
this.ready = ready;
}
}
private static final class FakeDisplay {
long period;
private final long gpuTail;
private final int queue;
private final Gate gate;
private final Mode mode;
private final int outageFrom;
private final int outageTo;
private final ArrayDeque<Long> scheduled = new ArrayDeque<>();
final List<Frame> frames = new ArrayList<>();
private long lastFlip = Long.MIN_VALUE;
private long deferredGate = Long.MIN_VALUE;
FakeDisplay(Sim sim) {
this.period = sim.displayPeriod > 0L ? sim.displayPeriod
: sim.refreshPeriod + sim.refreshPeriod * sim.driftPpm / 1_000_000L;
this.gpuTail = sim.gpuTail;
this.queue = sim.queue;
this.gate = sim.gate;
this.mode = sim.mode;
this.outageFrom = sim.gateOutageFrom;
this.outageTo = sim.gateOutageTo;
}
long present(int index, long frameStart, long entry) {
final boolean outage = index >= outageFrom && index < outageTo;
long accepted = entry;
final int depth = mode == Mode.FIFO ? queue : MAILBOX_IMAGES;
if (mode != Mode.IMMEDIATE && !outage) {
purge(accepted);
while (scheduled.size() >= depth) {
accepted = Math.max(accepted, scheduled.peek());
purge(accepted);
}
}
final long ready = accepted + gpuTail;
final Frame frame = new Frame(index, frameStart, ready);
frame.entry = entry;
if (mode == Mode.FIFO) {
final long floor = lastFlip == Long.MIN_VALUE ? ready : Math.max(ready, lastFlip + period);
final long flip = ceilVblank(floor);
lastFlip = flip;
scheduled.add(flip);
frame.showTime = flip;
} else if (mode == Mode.IMMEDIATE) {
frame.showTime = ready;
} else {
scheduled.add(ceilVblank(ready));
}
if (outage) {
scheduled.clear();
lastFlip = Long.MIN_VALUE;
}
frames.add(frame);
if (gate == Gate.FIRST_CLEAR) {
deferredGate = accepted;
return entry;
}
return accepted;
}
long firstDraw(long now) {
if (gate != Gate.FIRST_CLEAR || deferredGate == Long.MIN_VALUE) return now;
final long blocked = Math.max(now, deferredGate);
deferredGate = Long.MIN_VALUE;
return blocked;
}
private void purge(long now) {
while (!scheduled.isEmpty() && scheduled.peek() <= now) scheduled.poll();
}
private long ceilVblank(long time) {
return Math.floorDiv(time + period - 1, period) * period;
}
void resolve(Result result) {
final long warmupTime = frames.get(WARMUP).frameStart;
if (mode == Mode.MAILBOX) resolveMailbox(result, warmupTime);
if (mode == Mode.FIFO) countVblanks(result, warmupTime);
}
private void resolveMailbox(Result result, long warmupTime) {
int i = 0;
long vblank = ceilVblank(frames.get(0).ready);
while (i < frames.size()) {
Frame latest = null;
while (i < frames.size() && frames.get(i).ready <= vblank) {
if (latest != null && latest.index >= WARMUP) result.dropped++;
latest = frames.get(i);
i++;
}
if (latest != null) latest.showTime = vblank;
else if (vblank >= warmupTime) result.repeats++;
vblank += period;
}
}
private void countVblanks(Result result, long warmupTime) {
final long last = frames.get(frames.size() - 1).showTime;
int next = 0;
for (long vblank = ceilVblank(warmupTime); vblank <= last; vblank += period) {
while (next < frames.size() && frames.get(next).showTime < vblank) next++;
if (next < frames.size() && frames.get(next).showTime == vblank) continue;
result.repeats++;
for (final Frame frame : frames) {
if (frame.ready <= vblank && frame.showTime > vblank) {
result.dups++;
break;
}
}
}
}
}
private static final class Sim {
long refreshPeriod = P60;
long displayPeriod;
boolean tearFree = true;
boolean vsyncOn = true;
int cap;
Mode mode = Mode.FIFO;
Gate gate = Gate.SWAP;
int queue = 1;
int gateOutageFrom = Integer.MAX_VALUE;
int gateOutageTo = Integer.MAX_VALUE;
long gpuTail = 500 * US;
long work = 4 * MS;
long stallWork;
int stallEvery;
int refreshChangeFrame = Integer.MAX_VALUE;
long refreshChangeTo;
long granularity;
long driftPpm;
ObjIntConsumer<PacerCore> schedule;
String name = "";
Sim named(String value) {
name = value;
return this;
}
}
private static final class Result {
String name;
int dups;
int repeats;
int dropped;
int startParks;
int lockedStartParks;
int probeFrames;
int lockFrame = -1;
int unlockFrame = -1;
int relockFrame = -1;
long cadence;
long displayPeriod;
long minInterval;
long maxInterval;
long meanInterval;
long intervalSd;
long maxStartSleep;
long latencyP50;
long latencyP99;
long margin;
boolean driverPaced;
long[] entries;
long[] cadences;
long[] margins;
boolean[] probed;
boolean[] driven;
@Override
public String toString() {
return name + " [C=" + cadence / 1000 + "us driverPaced=" + driverPaced
+ " dups=" + dups + " repeats=" + repeats + " dropped=" + dropped
+ " startParks=" + startParks + " lockedStartParks=" + lockedStartParks
+ " lockFrame=" + lockFrame + " unlockFrame=" + unlockFrame + " relockFrame=" + relockFrame
+ " probeFrames=" + probeFrames
+ " intervalUs mean=" + meanInterval / 1000 + " sd=" + intervalSd / 1000 + "." + intervalSd % 1000
+ " min=" + minInterval / 1000 + " max=" + maxInterval / 1000
+ " latencyUs p50=" + latencyP50 / 1000 + " p99=" + latencyP99 / 1000
+ " marginUs=" + margin / 1000 + "]";
}
}
private static Result run(Sim sim) {
final FakeClock clock = new FakeClock();
final FakeSleeper parker = new FakeSleeper(clock, sim.granularity);
final PacerSleeper sleeper = new PacerSleeper(clock, parker, false);
final PacerCore core = new PacerCore(clock, sleeper);
core.setRefreshPeriodNanos(sim.refreshPeriod);
core.setTearFree(sim.tearFree);
core.setVsyncOn(sim.vsyncOn);
core.setCap(sim.cap);
final FakeDisplay display = new FakeDisplay(sim);
final Result result = new Result();
result.name = sim.name;
result.displayPeriod = display.period;
result.entries = new long[FRAMES];
result.cadences = new long[FRAMES];
result.margins = new long[FRAMES];
result.probed = new boolean[FRAMES];
result.driven = new boolean[FRAMES];
boolean wasLocked = false;
for (int f = 0; f < FRAMES; f++) {
if (sim.schedule != null) sim.schedule.accept(core, f);
if (f == sim.refreshChangeFrame) {
core.setRefreshPeriodNanos(sim.refreshChangeTo);
display.period = sim.refreshChangeTo + sim.refreshChangeTo * sim.driftPpm / 1_000_000L;
}
final int parksBefore = parker.parks;
clock.now = core.beginFrame(clock.now);
final int startParks = parker.parks - parksBefore;
if (f >= WARMUP) result.startParks += startParks;
result.probed[f] = core.probing();
result.driven[f] = Reflect.<Boolean>invoke(core, "driverPaced", new Class<?>[0]);
if (core.probing()) result.probeFrames++;
if (core.locked()) {
if (result.lockFrame < 0) result.lockFrame = f;
if (wasLocked == false && result.unlockFrame >= 0 && result.relockFrame < 0) result.relockFrame = f;
result.lockedStartParks += startParks;
wasLocked = true;
} else if (wasLocked) {
result.unlockFrame = f;
wasLocked = false;
}
if (core.slackNanos() > result.maxStartSleep) result.maxStartSleep = core.slackNanos();
result.cadences[f] = Reflect.<Long>get(core, "cadenceNanos");
result.margins[f] = core.marginNanos();
final long start = clock.now;
core.markFrameStart(start);
long firstClearBlockNanos = 0L;
if (sim.gate == Gate.FIRST_CLEAR) {
final long blocked = display.firstDraw(clock.now);
if (blocked > clock.now) {
firstClearBlockNanos = blocked - clock.now;
core.onGateSample(firstClearBlockNanos, blocked);
clock.now = blocked;
}
}
clock.now += sim.stallEvery > 0 && f > 0 && f % sim.stallEvery == 0 ? sim.stallWork : sim.work;
final long entry = core.beforePresent(clock.now, firstClearBlockNanos);
clock.now = entry;
result.entries[f] = entry;
final long accepted = display.present(f, start, entry);
if (sim.gate == Gate.SWAP && accepted > entry) {
core.onGateSample(accepted - entry, accepted);
}
clock.now = accepted;
}
result.driverPaced = Reflect.<Boolean>invoke(core, "driverPaced", new Class<?>[0]);
result.cadence = Reflect.<Long>get(core, "cadenceNanos");
result.margin = core.marginNanos();
display.resolve(result);
measure(display.frames, result);
return result;
}
private static void measure(List<Frame> frames, Result result) {
final List<Long> intervals = new ArrayList<>();
final List<Long> latencies = new ArrayList<>();
for (int i = WARMUP; i < frames.size(); i++) {
final Frame frame = frames.get(i);
intervals.add(frame.entry - frames.get(i - 1).entry);
if (frame.showTime >= 0L) latencies.add(frame.showTime - frame.frameStart);
}
long sum = 0L;
result.minInterval = Long.MAX_VALUE;
for (final long interval : intervals) {
sum += interval;
result.minInterval = Math.min(result.minInterval, interval);
result.maxInterval = Math.max(result.maxInterval, interval);
}
result.meanInterval = sum / intervals.size();
double variance = 0.0;
for (final long interval : intervals) {
final double d = interval - (double) result.meanInterval;
variance += d * d;
}
result.intervalSd = (long) Math.sqrt(variance / intervals.size());
Collections.sort(latencies);
result.latencyP50 = latencies.get(latencies.size() / 2);
result.latencyP99 = latencies.get(Math.min(latencies.size() - 1, latencies.size() * 99 / 100));
}
private static Sim fifo60(long work, int queue, Gate gate) {
final Sim sim = new Sim();
sim.work = work;
sim.queue = queue;
sim.gate = gate;
return sim;
}
private static void assertNeverBunches(Result r, long slopNanos) {
for (int f = WARMUP; f < FRAMES; f++) {
if (r.driven[f] || r.driven[f - 1]) continue;
final long interval = r.entries[f] - r.entries[f - 1];
final long c = r.cadences[f];
final long unpinned = r.probed[f] ? r.margins[f] : 0L;
final long floor = c - c / PacerCore.CATCHUP_DIVISOR - slopNanos - unpinned;
assertTrue(interval >= floor, r + " interval " + interval + "ns at frame " + f + ", floor is " + floor);
assertTrue(r.maxStartSleep <= 2 * c, r + " start sleep " + r.maxStartSleep + "ns exceeds two periods");
}
}
@Test
void anHonoredVsyncGateIsLeftToPaceItself() {
for (final long drift : new long[] { 0L, 1000L }) {
for (final long work : new long[] { 4 * MS, 10 * MS }) {
for (final int queue : new int[] { 1, 2 }) {
for (final Gate gate : new Gate[] { Gate.SWAP, Gate.FIRST_CLEAR }) {
final Sim sim = fifo60(work, queue, gate)
.named("fifo60 R=" + work / MS + "ms Q=" + queue + " " + gate + " drift=" + drift);
sim.driftPpm = drift;
final Result r = run(sim);
assertTrue(r.driverPaced, r + " must hand pacing to the driver");
assertTrue(r.lockFrame >= 0 && r.lockFrame <= 150, r + " must lock inside the probe window");
assertEquals(0, r.dups, r.toString());
assertEquals(0, r.repeats, r + " must fill every vblank");
assertEquals(0, r.lockedStartParks, r + " must not sleep at frame start once locked");
}
}
}
}
}
@Test
void aPanelFasterThanItsReportedRateIsStillFoundByTheProbe() {
final Sim sim = fifo60(4 * MS, 2, Gate.SWAP).named("lateDrift60 Q=2");
sim.refreshPeriod = P5994;
sim.displayPeriod = P60;
final Result r = run(sim);
assertTrue(r.lockFrame >= 0 && r.lockFrame <= 150, r + " must lock inside the probe window");
assertTrue(r.driverPaced, r.toString());
assertEquals(0, r.repeats, r + " must fill every vblank once locked");
assertEquals(0, r.lockedStartParks, r.toString());
final Sim single = fifo60(4 * MS, 1, Gate.SWAP).named("lateDrift60 Q=1");
single.driftPpm = -1000L;
final Result rs = run(single);
assertTrue(rs.displayPeriod < P60, rs + " the panel must run faster than its reported rate");
assertTrue(rs.lockFrame >= 0 && rs.lockFrame <= 150, rs + " must lock inside the probe window");
assertTrue(rs.driverPaced, rs.toString());
assertEquals(0, rs.repeats, rs.toString());
assertEquals(0, rs.lockedStartParks, rs.toString());
}
@Test
void aDriverThatNeverBlocksFallsBackToTheExactCadenceAfterTheProbe() {
final Sim sim = fifo60(4 * MS, Integer.MAX_VALUE, Gate.NONE).named("freeRunFifo60");
final Result r = run(sim);
assertEquals(-1, r.lockFrame, r + " has no gate to lock onto");
for (int f = WARMUP; f < FRAMES; f++) {
final long interval = r.entries[f] - r.entries[f - 1];
assertTrue(Math.abs(interval - P60) <= 200 * US, r + " interval " + interval + "ns at frame " + f);
}
final double vblanks = (r.entries[FRAMES - 1] - r.entries[WARMUP]) / (double) r.displayPeriod;
final double ratio = (FRAMES - 1 - WARMUP) / vblanks;
assertTrue(Math.abs(ratio - 1.0) <= 0.01, r + " presented " + ratio + " frames per vblank");
assertTrue(r.repeats <= 2, r + " repeats");
}
@Test
void aGateOutageReleasesTheLockAndTheProbeFindsItAgain() {
final Sim sim = fifo60(4 * MS, 1, Gate.SWAP).named("gateOutage60");
sim.gateOutageFrom = 100;
sim.gateOutageTo = 100 + PacerCore.LOCK_FRAMES;
final Result r = run(sim);
assertTrue(r.lockFrame >= 0 && r.lockFrame < sim.gateOutageFrom, r + " must lock before the outage");
assertTrue(r.unlockFrame >= sim.gateOutageTo - 1, r + " must hold the lock for the whole lapse window");
assertTrue(r.relockFrame > r.unlockFrame && r.relockFrame - r.unlockFrame <= 150,
r + " the re-armed probe must find the gate again");
assertTrue(r.driverPaced, r.toString());
}
@Test
void aFractionalRefreshRateSwallowsAnIntegerCapOfTheSameRate() {
final Sim sim = fifo60(4 * MS, 1, Gate.SWAP).named("fifo59.94 cap60");
sim.refreshPeriod = P5994;
sim.cap = 60;
sim.driftPpm = 1000L;
final Result r = run(sim);
assertTrue(r.lockFrame >= 0 && r.lockFrame <= 150, r + " must lock inside the probe window");
assertEquals(P5994, r.cadence, r.toString());
assertTrue(r.driverPaced, r.toString());
assertEquals(0, r.dups, r.toString());
assertEquals(0, r.repeats, r.toString());
}
@Test
void aCapBetweenVblanksSnapsDownToTheNearestMultiple() {
final Sim sim = fifo60(4 * MS, 1, Gate.SWAP).named("fifo144 cap50");
sim.refreshPeriod = P144;
sim.cap = 50;
sim.gpuTail = 200 * US;
final Result r = run(sim);
assertTrue(r.intervalSd < 300 * US, r.toString());
assertTrue(Math.abs(r.meanInterval - 3 * P144) < 300 * US, r.toString());
}
@Test
void mailboxIsPacedToTheRefreshRateInsteadOfBeatingAgainstIt() {
final Sim sim = new Sim().named("mailbox144");
sim.refreshPeriod = P144;
sim.mode = Mode.MAILBOX;
sim.gate = Gate.SWAP;
sim.vsyncOn = false;
sim.work = 3 * MS;
sim.gpuTail = MS;
final Result r = run(sim);
assertTrue(r.dropped <= 1, r + " must not drop presents it paid to render");
assertTrue(r.intervalSd < 200 * US, r.toString());
}
@Test
void aTearingCapHoldsItsPeriodAndKeepsLatencyToOneFrameOfWork() {
final Sim sim = new Sim().named("vsyncOff cap100");
sim.tearFree = false;
sim.vsyncOn = false;
sim.mode = Mode.IMMEDIATE;
sim.gate = Gate.NONE;
sim.cap = 100;
sim.work = 4 * MS;
sim.gpuTail = 200 * US;
final Result r = run(sim);
assertTrue(Math.abs(r.minInterval - 10 * MS) < 200 * US, r.toString());
assertTrue(Math.abs(r.maxInterval - 10 * MS) < 200 * US, r.toString());
assertTrue(r.latencyP50 <= sim.work + r.margin + MS, r.toString());
assertTrue(r.latencyP99 <= sim.work + r.margin + MS, r.toString());
}
@Test
void aFrameSlowerThanTheCadenceIsNeverSleptOn() {
final Sim sim = new Sim().named("cpuBound R=20ms cap60");
sim.tearFree = false;
sim.vsyncOn = false;
sim.mode = Mode.IMMEDIATE;
sim.gate = Gate.NONE;
sim.cap = 60;
sim.work = 20 * MS;
sim.gpuTail = 200 * US;
final Result r = run(sim);
assertEquals(0, r.startParks, r.toString());
assertEquals(20 * MS, r.minInterval, r.toString());
assertEquals(20 * MS, r.maxInterval, r.toString());
}
@Test
void aCoarseSleepTimerWidensTheMarginWithoutSaturatingIt() {
final Sim sim = new Sim().named("coarseTimer cap60");
sim.tearFree = false;
sim.vsyncOn = false;
sim.mode = Mode.IMMEDIATE;
sim.gate = Gate.NONE;
sim.cap = 60;
sim.granularity = 4 * MS;
sim.gpuTail = 200 * US;
final Result r = run(sim);
assertTrue(r.margin > PacerCore.MARGIN_MIN_NANOS, r + " a coarse timer must buy extra lead");
assertTrue(r.margin < PacerCore.MARGIN_CEILING_NANOS, r + " but not saturate the margin");
}
@Test
void aPeriodicStallIsWalkedOffWithoutBunchingPresents() {
final Sim sim = fifo60(8 * MS, 1, Gate.SWAP).named("fifo60 cap30 stall");
sim.cap = 30;
sim.stallWork = 200 * MS;
sim.stallEvery = 300;
final Result r = run(sim);
final int stalls = (FRAMES - WARMUP) / sim.stallEvery;
final long floor = r.cadence - r.cadence / PacerCore.CATCHUP_DIVISOR - PacerSleeper.MIN_SPIN_FLOOR_NANOS - JITTER;
assertTrue(r.dups <= stalls, r + " allowed " + stalls + " duplicated flips");
assertTrue(r.minInterval >= floor, r + " floor is " + floor);
}
@Test
void aMidRunCapChangeNeverBunchesPresents() {
final Sim sim = fifo60(4 * MS, 1, Gate.SWAP).named("capChange 0-30-0");
sim.schedule = (core, frame) -> {
if (frame == 1000) core.setCap(30);
if (frame == 2000) core.setCap(0);
};
final Result r = run(sim);
assertEquals(P60, r.cadences[999], r.toString());
assertEquals(2 * P60, r.cadences[1500], r.toString());
assertEquals(P60, r.cadences[2500], r.toString());
assertNeverBunches(r, PacerSleeper.MIN_SPIN_FLOOR_NANOS + JITTER);
}
@Test
void aMidRunRefreshChangeNeverBunchesPresents() {
final Sim sim = fifo60(4 * MS, 1, Gate.SWAP).named("refreshChange 60-144");
sim.refreshChangeFrame = 1500;
sim.refreshChangeTo = P144;
final Result r = run(sim);
assertEquals(P60, r.cadences[1499], r.toString());
assertEquals(P144, r.cadences[2500], r.toString());
assertTrue(r.relockFrame > 1500 && r.relockFrame - 1500 <= 150, r + " must find the new panel's gate");
assertTrue(r.driverPaced, r.toString());
assertNeverBunches(r, PacerSleeper.MIN_SPIN_FLOOR_NANOS + JITTER);
}
}
@@ -0,0 +1,420 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.glsm.backend.RenderBackend;
import com.gtnewhorizons.angelica.glsm.testutil.Reflect;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PacerCoreTest {
private static final long MS = 1_000_000L;
private static final long P60 = 1_000_000_000L / 60;
private static final long P5994 = 1_000_000_000L * 1001 / 60_000;
private static final long P144 = 1_000_000_000L / 144;
private static final class Rig {
final long[] now = { 0L };
final PacerCore core;
final List<Long> presents = new ArrayList<>();
int parks;
Rig(long refreshPeriodNanos, boolean tearFree, int capHz) {
this(refreshPeriodNanos, tearFree, tearFree, capHz);
}
Rig(long refreshPeriodNanos, boolean tearFree, boolean vsyncOn, int capHz) {
final PacerSleeper sleeper = new PacerSleeper(() -> now[0], nanos -> {
parks++;
now[0] += nanos;
}, false);
core = new PacerCore(() -> now[0], sleeper);
core.setRefreshPeriodNanos(refreshPeriodNanos);
core.setTearFree(tearFree);
core.setVsyncOn(vsyncOn);
core.setCap(capHz);
}
long frameWithFirstClear(long blockNanos, long workNanos) {
if (blockNanos > 0L) {
core.onGateSample(blockNanos, now[0]);
}
now[0] = core.beginFrame(now[0]);
core.markFrameStart(now[0]);
now[0] += blockNanos + workNanos;
final long present = core.beforePresent(now[0], blockNanos);
now[0] = present;
presents.add(present);
return present;
}
long frame(long workNanos) {
now[0] = core.beginFrame(now[0]);
core.markFrameStart(now[0]);
now[0] += workNanos;
final long present = core.beforePresent(now[0], 0L);
now[0] = present;
presents.add(present);
return present;
}
void feed(long gateEndNanos, long durationNanos, long atNanos) {
if (durationNanos > 0L) core.onGateSample(durationNanos, gateEndNanos);
now[0] = Math.max(now[0], atNanos);
now[0] = core.beginFrame(now[0]);
}
void feedRun(int count, long firstEndNanos, long durationNanos, long strideNanos) {
long end = firstEndNanos;
for (int i = 0; i < count; i++) {
feed(end, durationNanos, end);
end += strideNanos;
}
}
void idleFrames(int count, long atNanos) {
for (int i = 0; i < count; i++) {
now[0] = Math.max(now[0], atNanos + i);
core.beginFrame(now[0]);
}
}
}
@Test
void aCapAtOrAboveTheRefreshRateCollapsesOntoTheRefreshPeriod() {
assertEquals(P5994, PacerCore.cadencePeriodNanos(60, P5994, true));
assertEquals(P60, PacerCore.cadencePeriodNanos(58, P60, true));
assertEquals(P60, PacerCore.cadencePeriodNanos(0, P60, true));
assertEquals(P60, PacerCore.cadencePeriodNanos(240, P60, true));
}
@Test
void aCapNearAVblankMultipleSnapsToThatMultiple() {
assertEquals(2 * P60, PacerCore.cadencePeriodNanos(30, P60, true));
assertEquals(3 * P144, PacerCore.cadencePeriodNanos(50, P144, true));
assertEquals(48, RenderBackend.hzFromPeriod(3 * P144));
}
@Test
void aCapFarFromEveryMultipleKeepsItsLiteralPeriod() {
assertEquals(1_000_000_000L / 45, PacerCore.cadencePeriodNanos(45, P60, true));
assertEquals(1_000_000_000L / 100, PacerCore.cadencePeriodNanos(100, P144, true));
}
@Test
void aTearingModeIgnoresTheRefreshPeriodEntirely() {
assertEquals(10 * MS, PacerCore.cadencePeriodNanos(100, P60, false));
assertEquals(0L, PacerCore.cadencePeriodNanos(0, P60, false));
assertEquals(0L, PacerCore.cadencePeriodNanos(0, 0L, true));
assertEquals(10 * MS, PacerCore.cadencePeriodNanos(100, 0L, true));
}
@Test
void threeConsistentPairsOnTheRefreshGridLockThePhase() {
final Rig rig = new Rig(P60, true, 0);
rig.feedRun(PacerCore.LOCK_PAIRS, 20 * MS, 5 * MS, P60);
assertFalse(rig.core.locked(), "the last pair of the run has not arrived yet");
assertTrue(rig.core.probing());
rig.feed(20 * MS + PacerCore.LOCK_PAIRS * P60, 5 * MS, 20 * MS + PacerCore.LOCK_PAIRS * P60);
assertTrue(rig.core.locked());
assertTrue(Reflect.<Boolean>invoke(rig.core, "driverPaced", new Class<?>[0]));
assertFalse(rig.core.probing());
}
@Test
void pairsSpanningSeveralRefreshPeriodsAlsoLock() {
final Rig rig = new Rig(P60, true, 0);
rig.feedRun(PacerCore.LOCK_PAIRS + 1, 20 * MS, 5 * MS, 2 * P60);
assertTrue(rig.core.locked());
}
@Test
void oneBadPairRestartsTheRunOfConsistentPairs() {
final Rig rig = new Rig(P60, true, 0);
rig.feedRun(PacerCore.LOCK_PAIRS, 20 * MS, 5 * MS, P60);
long end = 20 * MS + PacerCore.LOCK_PAIRS * P60;
end += P60 / 2;
rig.feed(end, 5 * MS, end);
assertFalse(rig.core.locked());
for (int i = 0; i < PacerCore.LOCK_PAIRS; i++) {
end += P60;
rig.feed(end, 5 * MS, end);
}
assertTrue(rig.core.locked(), "a fresh run of consistent pairs must still lock");
}
@Test
void aRunOfInconsistentPairsGivesUpOnTheGateEntirely() {
final Rig rig = new Rig(P60, true, 0);
rig.feedRun(PacerCore.LOCK_PAIRS + 1, 20 * MS, 5 * MS, P60);
assertTrue(rig.core.locked());
long end = 20 * MS + (PacerCore.LOCK_PAIRS + 1) * P60;
for (int i = 0; i < PacerCore.LOCK_WINDOW + 1; i++) {
end += P60 / 2;
rig.feed(end, 5 * MS, end);
}
assertFalse(rig.core.locked(), "a gate that stops landing on the grid must be released");
assertFalse(rig.core.probing(), "a gate proven off the grid must not be probed again");
}
@Test
void samplesFurtherApartThanTheLockWindowNeverPairUp() {
final Rig rig = new Rig(P60, true, 0);
long end = 20 * MS;
for (int i = 0; i < 5; i++) {
rig.feed(end, 5 * MS, end);
rig.idleFrames(PacerCore.LOCK_WINDOW + 1, end + 1);
end += (PacerCore.LOCK_WINDOW + 2) * P60;
}
assertFalse(rig.core.locked());
}
@Test
void aSampleShorterThanTheGateThresholdIsNotAPhaseCandidate() {
final Rig rig = new Rig(P60, true, 0);
rig.feedRun(PacerCore.LOCK_PAIRS + 2, 20 * MS, PacerCore.gateThresholdNanos(P60), P60);
assertFalse(rig.core.locked());
}
@Test
void theLockLapsesAfterSixHundredSampleFreeFrames() {
final Rig rig = new Rig(P60, true, 0);
rig.feedRun(PacerCore.LOCK_PAIRS + 1, 20 * MS, 5 * MS, P60);
assertTrue(rig.core.locked());
rig.idleFrames(PacerCore.LOCK_FRAMES - 1, 100 * MS);
assertTrue(rig.core.locked(), "the lock must survive one frame short of the timeout");
rig.idleFrames(1, 200 * MS);
assertFalse(rig.core.locked());
}
@Test
void aLockedGateStillLeavesADividedCadencePacedByTheWallClock() {
final Rig rig = new Rig(P60, true, 30);
rig.feedRun(PacerCore.LOCK_PAIRS + 1, 20 * MS, 5 * MS, P60);
assertTrue(rig.core.locked());
assertEquals(2 * P60, Reflect.<Long>get(rig.core, "cadenceNanos"));
assertFalse(Reflect.<Boolean>invoke(rig.core, "driverPaced", new Class<?>[0]));
}
@Test
void aTearingModeNeverLocksHoweverRegularTheGateIs() {
final Rig rig = new Rig(P60, false, true, 60);
rig.feedRun(20, 20 * MS, 5 * MS, P60);
assertFalse(rig.core.locked());
assertFalse(rig.core.probing());
}
@Test
void aFirstClearBlockIsChargedToTheDriverNotToTheFrame() {
final Rig blocked = new Rig(P60, false, 60);
blocked.frameWithFirstClear(5 * MS, 7 * MS);
blocked.frame(4 * MS);
assertEquals(7 * MS, Reflect.<Long>get(blocked.core, "cpuHighNanos"));
final Rig plain = new Rig(P60, false, 60);
plain.frame(12 * MS);
plain.frame(4 * MS);
assertEquals(12 * MS, Reflect.<Long>get(plain.core, "cpuHighNanos"));
}
@Test
void aStallIsWalkedOffAtOneEighthOfAPeriodPerFrameInsteadOfBunching() {
final Rig rig = new Rig(P60, false, 60);
final long cadence = 1_000_000_000L / 60;
for (int i = 0; i < 200; i++) rig.frame(4 * MS);
final int stallIndex = rig.presents.size();
rig.frame(208 * MS);
for (int i = 0; i < 200; i++) rig.frame(4 * MS);
long min = Long.MAX_VALUE;
for (int i = stallIndex + 1; i < rig.presents.size(); i++) {
min = Math.min(min, rig.presents.get(i) - rig.presents.get(i - 1));
}
final long floor = cadence - cadence / 8 - PacerSleeper.MIN_SPIN_FLOOR_NANOS;
assertTrue(min >= floor, "shortest post-stall interval was " + min + "ns, floor is " + floor);
assertTrue(min < cadence, "the pacer must actually claw back the stall, min interval was " + min);
}
@Test
void aStallFrameIsKeptOutOfTheMarginWindows() {
final Rig rig = new Rig(P60, false, 60);
for (int i = 0; i < 200; i++) rig.frame(4 * MS);
final long before = rig.core.marginNanos();
final long cpuBefore = Reflect.<Long>get(rig.core, "cpuHighNanos");
assertEquals(4 * MS, cpuBefore);
rig.frame(208 * MS);
rig.frame(4 * MS);
assertEquals(before, rig.core.marginNanos());
assertEquals(cpuBefore, Reflect.<Long>get(rig.core, "cpuHighNanos"));
rig.frame(4 * MS);
assertEquals(before, rig.core.marginNanos());
assertEquals(cpuBefore, Reflect.<Long>get(rig.core, "cpuHighNanos"));
}
@Test
void aFrameThatStartsLateWidensTheMargin() {
final Rig rig = new Rig(P60, false, 60);
for (int i = 0; i < 300; i++) rig.frame(4 * MS);
final long before = rig.core.marginNanos();
assertEquals(PacerCore.MARGIN_MIN_NANOS, before);
for (int i = 0; i < PacerCore.LOCK_PAIRS + 1; i++) {
rig.frame(6 * MS);
for (int j = 0; j < 20; j++) rig.frame(4 * MS);
}
final long after = rig.core.marginNanos();
assertTrue(after > before, "an overrunning frame must buy more lead, margin is " + after);
assertTrue(after < PacerCore.MARGIN_CEILING_NANOS, "a 2ms overrun must not saturate the margin, margin is " + after);
}
@Test
void idleWorkStillRunsWhenTheDriverPaces() {
final Rig rig = new Rig(P60, true, 0);
rig.feedRun(PacerCore.LOCK_PAIRS + 1, 20 * MS, 5 * MS, P60);
assertTrue(Reflect.<Boolean>invoke(rig.core, "driverPaced", new Class<?>[0]));
final int[] runs = { 0 };
rig.core.setIdleWork(deadline -> {
runs[0]++;
rig.now[0] += MS;
});
final int parksBefore = rig.parks;
for (int i = 0; i < 10; i++) rig.frame(2 * MS);
assertEquals(10, runs[0], "a driver-paced frame still has idle time before the present target");
assertEquals(parksBefore, rig.parks, "but it must never sleep");
}
@Test
void theFirstPacedFrameAfterAnUnpacedStretchIsAnchoredWithoutSleeping() {
final Rig rig = new Rig(P60, false, 0);
for (int i = 0; i < 5; i++) rig.frame(4 * MS);
assertEquals(0, rig.parks);
rig.core.setCap(60);
rig.frame(4 * MS);
assertEquals(0, rig.parks, "the anchor frame must not stall the loop");
assertEquals(0L, rig.core.slackNanos());
rig.frame(4 * MS);
assertTrue(rig.parks > 0, "the cadence resumes on the frame after the anchor");
}
@Test
void aTargetMoreThanTwoPeriodsAheadIsPulledBack() {
final Rig rig = new Rig(P60, false, 60);
for (int i = 0; i < 20; i++) rig.frame(4 * MS);
rig.now[0] -= 500 * MS;
rig.core.beginFrame(rig.now[0]);
assertTrue(rig.core.slackNanos() <= P60, "a backward clock step must not park for half a second: " + rig.core.slackNanos());
}
@Test
void theEffectiveCapReportsTheCadenceThePacerActuallyRuns() {
final Rig unpaced = new Rig(0L, false, 0);
unpaced.frame(4 * MS);
assertEquals(0, unpaced.core.effectiveCapHz());
assertFalse(unpaced.core.paced());
final Rig snapped = new Rig(P144, true, 50);
snapped.frame(4 * MS);
assertEquals(48, snapped.core.effectiveCapHz());
assertTrue(snapped.core.paced());
}
@Test
void anUnpacedFrameNeverSleeps() {
final Rig rig = new Rig(P60, false, 0);
for (int i = 0; i < 50; i++) rig.frame(4 * MS);
assertEquals(0, rig.parks);
assertEquals(0L, rig.core.slackNanos());
}
@Test
void theMarginIsClampedIntoItsBandByTheCadence() {
assertEquals(PacerCore.MARGIN_MIN_NANOS, PacerCore.clampMargin(0L, 16_666_666L));
assertEquals(PacerCore.MARGIN_CEILING_NANOS, PacerCore.clampMargin(50 * MS, 100 * MS));
assertEquals(2 * MS, PacerCore.clampMargin(2 * MS, 16_666_666L));
assertEquals(P144 / 4, PacerCore.clampMargin(3 * MS, P144), "a short cadence caps the margin below its own minimum");
}
@Test
void theProbeRunsAheadOfThePanelOnlyUntilItHasGainedTwoPeriods() {
final Rig rig = new Rig(P60, true, 0);
for (int i = 0; i < 400; i++) rig.frame(4 * MS);
final long lead = P60 / PacerCore.PROBE_LEAD_DIVISOR;
assertEquals(P60 - lead, rig.presents.get(10) - rig.presents.get(9), "the probe must present ahead of the panel");
assertEquals(P60, rig.presents.get(300) - rig.presents.get(299), "an expired probe must fall back to the exact cadence");
}
@Test
void mailboxIsNeverProbedAndNeverLocks() {
final Rig rig = new Rig(P60, true, false, 0);
for (int i = 0; i < 40; i++) {
final long end = 20 * MS + i * P60;
rig.feed(end, 5 * MS, end);
assertFalse(rig.core.probing());
}
assertFalse(rig.core.locked());
assertEquals(P60, Reflect.<Long>get(rig.core, "cadenceNanos"));
}
@Test
void aCapChangeRearmsTheProbe() {
final Rig rig = new Rig(P60, true, 0);
for (int i = 0; i < 200; i++) rig.frame(4 * MS);
assertFalse(rig.core.probing());
rig.core.setCap(45);
rig.frame(4 * MS);
assertFalse(rig.core.probing(), "a cadence off the refresh period is never probed");
rig.core.setCap(0);
rig.frame(4 * MS);
assertTrue(rig.core.probing());
}
@Test
void aRefreshChangeRearmsTheProbe() {
final Rig rig = new Rig(P60, true, 0);
for (int i = 0; i < 200; i++) rig.frame(4 * MS);
assertFalse(rig.core.probing());
rig.core.setRefreshPeriodNanos(P144);
rig.frame(4 * MS);
assertTrue(rig.core.probing());
}
@Test
void aFirstClearBlockIsKeptOutOfTheStartResidualToo() {
final Rig plain = new Rig(P60, false, 60);
final Rig blocked = new Rig(P60, false, 60);
for (int i = 0; i < 300; i++) {
plain.frame(4 * MS);
blocked.frameWithFirstClear(5 * MS, 4 * MS);
}
assertEquals(Reflect.<Long>get(plain.core, "cpuHighNanos"), Reflect.<Long>get(blocked.core, "cpuHighNanos"));
assertEquals(plain.core.marginNanos(), blocked.core.marginNanos());
assertTrue(blocked.core.marginNanos() < PacerCore.MARGIN_CEILING_NANOS, "the driver block must not saturate the margin");
}
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.glsm.testutil.Reflect;
import org.junit.jupiter.api.Test;
import java.util.function.LongConsumer;
@@ -64,7 +65,7 @@ class PacerSleeperTest {
for (int i = 0; i < 20; i++) {
final long deadline = time.now + 13 * MS;
final long floor = s.spinFloorNanos();
final long floor = Reflect.<Long>get(s, "spinFloorNanos");
final long woke = s.sleepUntil(deadline, time.now);
assertTrue(deadline - woke <= floor, "left " + (deadline - woke) + "ns to spin, floor is " + floor);
}
@@ -95,7 +96,7 @@ class PacerSleeperTest {
final long woke = s.sleepUntil(10 * MS, 0L);
assertEquals(2, time.parks, "a short park must be followed by another, not by a spin");
assertTrue(10 * MS - woke <= s.spinFloorNanos(), "the second park should still land inside the floor");
assertTrue(10 * MS - woke <= Reflect.<Long>get(s, "spinFloorNanos"), "the second park should still land inside the floor");
}
@Test
@@ -111,13 +112,6 @@ class PacerSleeperTest {
assertEquals(i + 1, time.parks, "every frame must still park exactly once");
assertTrue(woke >= deadline, "frame " + i + " left " + (deadline - woke) + "ns to busy-wait; a coarse timer must never hand the frame to the spin loop");
}
}
@Test
void aPeriodShorterThanTheWakeUpLagStillParksRatherThanSpinning() {
final FakeTime time = new FakeTime();
time.granularity = 15_600_000L;
final PacerSleeper s = sleeper(time);
for (int i = 0; i < 30; i++) {
final int before = time.parks;
@@ -175,13 +169,18 @@ class PacerSleeperTest {
void theSpinLoopFinishesTheFrameAndIsCounted() {
final long step = 10_000L;
final long[] clock = { 0L };
final PacerSleeper s = new PacerSleeper(() -> clock[0] += step, nanos -> clock[0] += nanos, true);
final int[] parks = { 0 };
final PacerSleeper s = new PacerSleeper(() -> clock[0] += step, nanos -> {
parks[0]++;
clock[0] += nanos;
}, true);
final long woke = s.sleepUntil(5 * MS, 0L);
s.noteFrame(0L, 0L);
assertEquals(5 * MS, woke, "the spin must carry the frame to the deadline");
assertEquals(1, s.lastParks);
assertEquals(10_000L, s.lastSpinNanos, "the spin covers what the park left short");
assertEquals(1, parks[0]);
assertEquals(10_000L, s.lastFrameSpinNanos, "the spin covers what the park left short");
}
@Test
@@ -189,18 +188,25 @@ class PacerSleeperTest {
final long step = 10_000L;
final long overshoot = 2 * MS;
final long[] clock = { 0L };
final PacerSleeper s = new PacerSleeper(() -> clock[0] += step, nanos -> clock[0] += nanos + overshoot, true);
final int[] parks = { 0 };
final PacerSleeper s = new PacerSleeper(() -> clock[0] += step, nanos -> {
parks[0]++;
clock[0] += nanos + overshoot;
}, true);
for (int i = 0; i < PacerSleeper.SLOTS; i++) {
s.sleepUntil(clock[0] + 13 * MS, clock[0]);
}
s.noteFrame(0L, 0L);
assertTrue(s.avgOvershootNanos() > MS, "the park estimate must exceed the remaining gap for this branch to be reached");
final long deadline = clock[0] + MS;
final int before = parks[0];
final long woke = s.sleepUntil(deadline, clock[0]);
s.noteFrame(0L, 0L);
assertEquals(0, s.lastParks, "a gap under one park quantum must not park again");
assertTrue(s.lastSpinNanos > 0L, "the spin loop has to close a gap far wider than the floor");
assertEquals(before, parks[0], "a gap under one park quantum must not park again");
assertTrue(s.lastFrameSpinNanos > 0L, "the spin loop has to close a gap far wider than the floor");
assertTrue(woke >= deadline, "woke " + woke + "ns short of deadline " + deadline);
}
@@ -214,7 +220,7 @@ class PacerSleeperTest {
s.sleepUntil(time.now + 13 * MS, time.now);
}
assertEquals(PacerSleeper.MIN_SPIN_FLOOR_NANOS, s.spinFloorNanos(), "identical overshoots are pure bias, not jitter, so the floor stays at its minimum");
assertEquals(PacerSleeper.MIN_SPIN_FLOOR_NANOS, Reflect.<Long>get(s, "spinFloorNanos"), "identical overshoots are pure bias, not jitter, so the floor stays at its minimum");
}
@Test
@@ -230,7 +236,7 @@ class PacerSleeperTest {
s.sleepUntil(time.now + 13 * MS, time.now);
assertEquals(140_000L, s.avgOvershootNanos());
assertEquals(500_000L - 140_000L, s.spinFloorNanos(), "the floor must cover the spread between the worst park and the mean, not the mean itself");
assertEquals(500_000L - 140_000L, Reflect.<Long>get(s, "spinFloorNanos"), "the floor must cover the spread between the worst park and the mean, not the mean itself");
}
@Test
@@ -243,4 +249,46 @@ class PacerSleeperTest {
assertEquals(0, time.parks);
assertEquals(0L, woke);
}
@Test
void everyWaitInAFrameLandsOnTheOneFrameOfBookkeeping() {
final FakeTime time = new FakeTime();
final PacerSleeper s = sleeper(time);
s.sleepUntil(10 * MS, 0L);
s.sleepUntil(time.now + 10 * MS, time.now);
s.noteFrame(0L, 0L);
s.sleepUntil(time.now + 10 * MS, time.now);
s.noteFrame(0L, 0L);
assertEquals(3, time.parks);
assertEquals(2L, Reflect.<Long>get(s, "frames"));
assertEquals(3L, Reflect.<Long>get(s, "parkTotal"));
s.sleepUntil(time.now + 10 * MS, time.now);
s.resetStats();
s.noteFrame(0L, 0L);
assertEquals(1L, Reflect.<Long>get(s, "frames"));
assertEquals(0L, Reflect.<Long>get(s, "parkTotal"));
}
@Test
void aWakeInsideTheToleranceIsNotLate() {
final FakeTime time = new FakeTime();
final PacerSleeper s = sleeper(time);
s.noteFrame(0L, PacerSleeper.LATE_TOL_NANOS);
s.noteFrame(-5 * MS, 0L);
assertEquals(0L, Reflect.<Long>get(s, "lateFrames"));
assertEquals(0L, Reflect.<Long>get(s, "lateMax"));
s.noteFrame(0L, PacerSleeper.LATE_TOL_NANOS + 1);
s.noteFrame(0L, 3 * MS);
s.noteFrame(0L, MS);
assertEquals(3L, Reflect.<Long>get(s, "lateFrames"));
assertEquals(3 * MS, Reflect.<Long>get(s, "lateMax"));
}
}
@@ -0,0 +1,179 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.rendering.ReducerStateMachine.State;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ReducerStateMachineTest {
private static final float DELTA = 1e-6f;
private long time = 1_000_000_000L;
private final ReducerStateMachine machine = new ReducerStateMachine(() -> time);
@Test
void configOffWinsOverEverything() {
machine.toggleForced();
assertTrue(machine.evaluate(false, false, false, 1_000_000_000L));
assertEquals(State.DISABLED, machine.state());
}
@Test
void keybindDisabledWinsOverForced() {
machine.toggleForced();
machine.toggleKeybindDisabled();
machine.evaluate(true, true, true, 0);
assertEquals(State.DISABLED, machine.state());
}
@Test
void forcedWinsOverMinimized() {
machine.toggleForced();
machine.evaluate(true, false, true, 0);
assertEquals(State.FORCED, machine.state());
}
@Test
void minimizedWinsOverUnfocused() {
machine.evaluate(true, false, false, 0);
assertEquals(State.MINIMIZED, machine.state());
}
@Test
void unfocusedWhenNotActiveButVisible() {
machine.evaluate(true, true, false, 0);
assertEquals(State.UNFOCUSED, machine.state());
time += 10_000_000_000L;
machine.evaluate(true, true, false, 1_000_000_000L);
assertEquals(State.UNFOCUSED, machine.state());
}
@Test
void idleAfterTimeoutWhileFocused() {
time += 999_999_999L;
assertFalse(machine.evaluate(true, true, true, 1_000_000_000L));
assertEquals(State.FOCUSED, machine.state());
time += 1L;
assertTrue(machine.evaluate(true, true, true, 1_000_000_000L));
assertEquals(State.IDLE, machine.state());
}
@Test
void idleTimeoutZeroNeverIdles() {
time += 10_000_000_000L;
machine.evaluate(true, true, true, 0);
assertEquals(State.FOCUSED, machine.state());
}
@Test
void inputReturnsFromIdle() {
time += 1_000_000_000L;
machine.evaluate(true, true, true, 1_000_000_000L);
assertEquals(State.IDLE, machine.state());
machine.onInput();
machine.evaluate(true, true, true, 1_000_000_000L);
assertEquals(State.FOCUSED, machine.state());
}
@Test
void toggleForcedCountsAsInput() {
time += 10_000_000_000L;
machine.evaluate(true, true, true, 1_000_000_000L);
assertEquals(State.IDLE, machine.state());
machine.toggleForced();
machine.evaluate(true, true, true, 1_000_000_000L);
assertEquals(State.FORCED, machine.state());
machine.toggleForced();
machine.evaluate(true, true, true, 1_000_000_000L);
assertEquals(State.FOCUSED, machine.state());
}
@Test
void toggleKeybindDisabledCountsAsInput() {
time += 10_000_000_000L;
machine.evaluate(true, true, true, 1_000_000_000L);
assertEquals(State.IDLE, machine.state());
machine.toggleKeybindDisabled();
machine.evaluate(true, true, true, 1_000_000_000L);
assertEquals(State.DISABLED, machine.state());
machine.toggleKeybindDisabled();
machine.evaluate(true, true, true, 1_000_000_000L);
assertEquals(State.FOCUSED, machine.state());
}
@Test
void evaluateReportsTransitionOnce() {
assertFalse(machine.evaluate(true, true, true, 0));
machine.toggleForced();
assertTrue(machine.evaluate(true, true, true, 0));
assertFalse(machine.evaluate(true, true, true, 0));
}
@Test
void unlimitedUserAndNoStateCapIsUncapped() {
assertEquals(0, ReducerStateMachine.mergeCap(0, 0, false, true));
assertEquals(0, ReducerStateMachine.mergeCap(260, 0, false, true));
}
@Test
void theLowerOfTheUserAndStateCapWins() {
assertEquals(10, ReducerStateMachine.mergeCap(120, 10, false, true));
assertEquals(30, ReducerStateMachine.mergeCap(30, 60, false, true));
}
@Test
void menuCapAppliesOnlyWhenOptionOn() {
assertEquals(30, ReducerStateMachine.mergeCap(0, 0, true, true));
assertEquals(0, ReducerStateMachine.mergeCap(0, 0, true, false));
}
@Test
void menuCapNeverRaisesUserCap() {
assertEquals(20, ReducerStateMachine.mergeCap(20, 0, true, true));
assertEquals(30, ReducerStateMachine.mergeCap(260, 0, true, true));
assertEquals(10, ReducerStateMachine.mergeCap(260, 10, true, true));
}
@Test
void stateCapSelectsProfile() {
assertEquals(10, ReducerStateMachine.stateCap(State.FORCED, 10, 30));
assertEquals(10, ReducerStateMachine.stateCap(State.UNFOCUSED, 10, 30));
assertEquals(20, ReducerStateMachine.stateCap(State.MINIMIZED, 5, 5));
assertEquals(20, ReducerStateMachine.stateCap(State.MINIMIZED, 260, 260));
assertEquals(30, ReducerStateMachine.stateCap(State.IDLE, 10, 30));
assertEquals(0, ReducerStateMachine.stateCap(State.FOCUSED, 10, 10));
assertEquals(0, ReducerStateMachine.stateCap(State.DISABLED, 10, 10));
assertEquals(0, ReducerStateMachine.stateCap(State.UNFOCUSED, 260, 30));
assertEquals(0, ReducerStateMachine.stateCap(State.IDLE, 10, 260));
assertEquals(120, ReducerStateMachine.mergeCap(120, ReducerStateMachine.stateCap(State.UNFOCUSED, 260, 30), false, true));
}
@Test
void masterVolumeScalesByPercent() {
assertEquals(0.73f, ReducerStateMachine.masterVolume(0.73f, 100), DELTA);
assertEquals(0.5f, ReducerStateMachine.masterVolume(1.0f, 50), DELTA);
assertEquals(0.01f, ReducerStateMachine.masterVolume(1.0f, 0), DELTA);
}
@Test
void stateVolumeSelectsProfile() {
assertEquals(10, ReducerStateMachine.stateVolume(State.FORCED, 10, 20, 30));
assertEquals(10, ReducerStateMachine.stateVolume(State.UNFOCUSED, 10, 20, 30));
assertEquals(20, ReducerStateMachine.stateVolume(State.MINIMIZED, 10, 20, 30));
assertEquals(30, ReducerStateMachine.stateVolume(State.IDLE, 10, 20, 30));
assertEquals(100, ReducerStateMachine.stateVolume(State.FOCUSED, 10, 20, 30));
assertEquals(100, ReducerStateMachine.stateVolume(State.DISABLED, 10, 20, 30));
}
}