measure: fix AR tracking pipeline and add synthetic VIO harness
- Commit
aeddf412e677f3971428ee41501a30623d31e3ff- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 16:09 UTC (18 days ago)
- Parents
9618ea5
Why AR measurement never tracked on device, in pipeline order: 1. Keyframes never fired during a normal scan: the parallax gate compared one frame's flow against 24px, so no second keyframe ever opened. It now accumulates keyframe->current flow per feature. 2. Keyframe triangulation paired list indices, which name different scene points as soon as LK/FB/RANSAC drops a point or top-up adds one: every triangulation failed its reprojection gate and no landmark was ever created. Rust now gives each feature a stable id (JNI pairs are id+4 coords) and triangulation matches by id. 3. IMU samples were treated as camera-frame, but SensorEvent values are Android device axes while the visual pose lives in raw camera-image axes. VioEngine now rotates accel/gyro by the frame-rotation-derived device->camera matrix. 4. The IMU integrator re-integrated each scale window with zero initial velocity and one orientation per window, leaking gravity into phantom displacement (~0.5m/window on a still phone; scale confidence pinned at 0.0 in live logcat). It now integrates continuously: gyro orientation per sample, carried velocity and position, and accel bias estimated from the initial still period. 5. Chained essential poses carry unit translations, so the visual trajectory encoded frame count, not distance. Once a landmark map exists the camera centre is solved against it (solveCameraCentre in VioMath, with outlier rejection), keyframes are refined by a two-view triangulate/re-solve iteration, pre-solve landmarks are purged once solving is established, and the scale estimator uses projected (direction-aware) ratios over recent windows. 6. Intrinsics were resolved for the requested 640x480, not the delivered frame: the engine is now created on the first frame with the actual size+rotation, and hit/projection paths use it. Also: MeasureCv structured logging at every stage boundary (frames/corners/LK/FB/RANSAC/pose/keyframes/landmarks/scale/flow state), and a synthetic ground-truth harness (SyntheticVioHarnessTest) rendering a textured scene from known trajectories with synthesized IMU. Harness: sideways and low-texture scenarios now lock scale and reach Good with ~170 landmarks (previously scale never locked anywhere); forward/fast and <3% scale accuracy still need full bundle adjustment against the unit-translation bootstrap warp (metrics printed in-test). Verified: cargo test (measure_cv, 21 tests incl. stable-id test), :measure:testDevUnitTest full suite, and live Pixel 9 Pro XL logcat showing corners 220 -> LK/FB ~120-180 -> RANSAC pose=true, landmarks 0 -> 400 and plane fit on the instrumented build.
Diff
measure/src/main/java/com/vayunmathur/measure/domain/VioMath.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/VioMath.kt b/measure/src/main/java/com/vayunmathur/measure/domain/VioMath.ktindex 8645c37545..b29475ae63 100644--- a/measure/src/main/java/com/vayunmathur/measure/domain/VioMath.kt+++ b/measure/src/main/java/com/vayunmathur/measure/domain/VioMath.kt@@ -205,6 +205,94 @@ private fun jacobiRotate(a: DoubleArray, v: DoubleArray, n: Int, p: Int, q: Int) } } +/**+ * Camera centre from bearing observations of known landmarks: each+ * observation says the centre lies on the ray `X - mu * d` (world ray+ * direction [d] through landmark [X]), i.e. `(I - d d^T)(C - X) = 0`.+ * Least squares over all observations (3x3 normal equations).+ *+ * This is what makes the visual trajectory metrically *consistent* (one+ * global scale): pairwise essential poses only give unit translations,+ * so a chained trajectory encodes frame count, not distance, and no+ * IMU/visual window ratio can ever converge on it. Solving the centre+ * against the triangulated map puts every frame in map units instead.+ */+fun solveCameraCentre(+ observations: List<Pair<Vec3, Vec3>>,+): Vec3? {+ if (observations.size < 4) return null+ val first = solveCentreLeastSquares(observations) ?: return null+ // Two-pass outlier rejection: landmarks triangulated from early,+ // pre-map poses can be badly placed; one inconsistent subset must+ // not drag the centre. Residual = point-to-ray distance at the solve.+ val residuals = observations.map { (x, d) ->+ val rel = centreResidual(first, x, d)+ rel+ }+ val median = residuals.sorted()[residuals.size / 2]+ val keep = observations.filterIndexed { i, _ -> residuals[i] <= maxOf(3 * median, 0.02) }+ if (keep.size >= 4 && keep.size < observations.size) {+ return solveCentreLeastSquares(keep) ?: first+ }+ return first+}++/** Perpendicular distance from landmark [x] to the ray centre->landmark direction [dRaw]. */+private fun centreResidual(centre: Vec3, x: Vec3, dRaw: Vec3): Double {+ val len = sqrt(dRaw.x * dRaw.x + dRaw.y * dRaw.y + dRaw.z * dRaw.z)+ if (len < 1e-12) return Double.MAX_VALUE+ val rel = x - centre+ val along = (rel.x * dRaw.x + rel.y * dRaw.y + rel.z * dRaw.z) / len+ val perp = Vec3(rel.x - dRaw.x / len * along, rel.y - dRaw.y / len * along, rel.z - dRaw.z / len * along)+ return sqrt(perp.x * perp.x + perp.y * perp.y + perp.z * perp.z)+}++private fun solveCentreLeastSquares(+ observations: List<Pair<Vec3, Vec3>>,+): Vec3? {+ if (observations.size < 4) return null+ val ata = DoubleArray(9)+ val atb = DoubleArray(3)+ for ((x, dRaw) in observations) {+ val len = sqrt(dRaw.x * dRaw.x + dRaw.y * dRaw.y + dRaw.z * dRaw.z)+ if (len < 1e-12) continue+ val d = doubleArrayOf(dRaw.x / len, dRaw.y / len, dRaw.z / len)+ // A = I - d d^T; accumulate A^T A (=A, symmetric idempotent-ish) and A^T (A X) = A X.+ val a = DoubleArray(9) { i ->+ val rc = i / 3+ val cc = i % 3+ (if (rc == cc) 1.0 else 0.0) - d[rc] * d[cc]+ }+ val ax = Vec3(+ a[0] * x.x + a[1] * x.y + a[2] * x.z,+ a[3] * x.x + a[4] * x.y + a[5] * x.z,+ a[6] * x.x + a[7] * x.y + a[8] * x.z,+ )+ for (i in 0..8) ata[i] += a[i]+ atb[0] += ax.x; atb[1] += ax.y; atb[2] += ax.z+ }+ // Solve ata * C = atb by Gaussian elimination with partial pivoting.+ val m = Array(3) { r -> doubleArrayOf(ata[r * 3], ata[r * 3 + 1], ata[r * 3 + 2], atb[r]) }+ for (col in 0..2) {+ var pivot = col+ for (r in col + 1..2) if (abs(m[r][col]) > abs(m[pivot][col])) pivot = r+ if (abs(m[pivot][col]) < 1e-12) return null+ val tmp = m[col]; m[col] = m[pivot]; m[pivot] = tmp+ for (r in col + 1..2) {+ val f = m[r][col] / m[col][col]+ for (c in col..3) m[r][c] -= f * m[col][c]+ }+ }+ val out = DoubleArray(3)+ for (r in 2 downTo 0) {+ var s = m[r][3]+ for (c in r + 1..2) s -= m[r][c] * out[c]+ out[r] = s / m[r][r]+ }+ val centre = Vec3(out[0], out[1], out[2])+ return centre.takeIf { it.isFinite() }+}+ /** A fitted plane: a point on it plus a unit normal. */ data class FittedPlane(val point: Vec3, val normal: Vec3) { fun distanceTo(p: Vec3): Double {@@ -310,7 +398,16 @@ fun estimateScale(visual: List<Vec3>, imu: List<Vec3>): ScaleEstimate? { val m = imu[i] val im = sqrt(m.x * m.x + m.y * m.y + m.z * m.z) if (im < 0.005) continue- ratios += im / vm+ // Projected ratio: scale along the visual displacement direction.+ // A magnitude ratio |imu|/|visual| counts perpendicular drift+ // (visual centre wander, IMU residue) as if it were motion along+ // the window, which scattered ratios ~2x in the synthetic harness+ // even with centimetre-accurate IMU windows. Windows whose IMU+ // displacement points against the visual one are not scale+ // evidence at all and are dropped.+ val dot = m.x * v.x + m.y * v.y + m.z * v.z+ if (dot <= 0.0) continue+ ratios += dot / (vm * vm) } if (ratios.size < 3) return null val sorted = ratios.sorted()
measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt b/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.ktindex 146f0b598a..a73a860d52 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt@@ -27,7 +27,11 @@ class VioArHitProvider( ) : ArHitProvider { override fun centreHit(sessionHandle: Long): HitCandidate? { val eng = engine() ?: return null- return HitSelector.select(eng.centreCandidates(analysisWidth, analysisHeight))+ // Prefer the size the engine was actually calibrated for (the+ // delivered analysis size), falling back to the requested size.+ val w = eng.frameWidth.takeIf { it > 0 } ?: analysisWidth+ val h = eng.frameHeight.takeIf { it > 0 } ?: analysisHeight+ return HitSelector.select(eng.centreCandidates(w, h)) } }
measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.ktindex a57f6de219..1ae2288471 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt@@ -202,7 +202,13 @@ internal fun MeasureViewModel.refreshFlowImpl(nowMs: Long = System.currentTimeMi lostSinceMs = lostSinceMs, nowMs = nowMs, )- if (flow != s.flowState) arState.value = s.copy(flowState = flow)+ if (flow != s.flowState) {+ com.vayunmathur.library.log.Log.dev(+ "MeasureCv",+ "flow ${s.flowState} -> $flow quality=${s.quality} hasSession=${vioEngine != null}",+ )+ arState.value = s.copy(flowState = flow)+ } } internal fun MeasureViewModel.onReticleHit(
measure/src/main/java/com/vayunmathur/measure/platform/vio/ImuIntegrator.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/vio/ImuIntegrator.kt b/measure/src/main/java/com/vayunmathur/measure/platform/vio/ImuIntegrator.ktindex 2049b6897f..ad1d9ebee5 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/vio/ImuIntegrator.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/vio/ImuIntegrator.kt@@ -1,44 +1,152 @@ package com.vayunmathur.measure.platform.vio import com.vayunmathur.measure.domain.Vec3+import com.vayunmathur.measure.domain.multiply3 import com.vayunmathur.measure.domain.rotate3+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt -/** One IMU sample: accel in camera coordinates (m/s^2), timestamp in ns. */-private data class ImuSample(val tNs: Long, val ax: Double, val ay: Double, val az: Double)+/** One IMU sample: accel+gyro in camera coordinates (m/s^2, rad/s), timestamp in ns. */+private data class ImuSample(+ val tNs: Long,+ val ax: Double,+ val ay: Double,+ val az: Double,+ val gx: Double,+ val gy: Double,+ val gz: Double,+)++/** Rotation matrix for a small rotation vector (Rodrigues' formula). */+private fun rodrigues(rx: Double, ry: Double, rz: Double): DoubleArray {+ val theta = sqrt(rx * rx + ry * ry + rz * rz)+ if (theta < 1e-12) {+ return doubleArrayOf(1.0, -rz, ry, rz, 1.0, -rx, -ry, rx, 1.0)+ }+ val (kx, ky, kz) = Triple(rx / theta, ry / theta, rz / theta)+ val c = cos(theta)+ val s = sin(theta)+ val v = 1.0 - c+ return doubleArrayOf(+ c + kx * kx * v, kx * ky * v - kz * s, kx * kz * v + ky * s,+ ky * kx * v + kz * s, c + ky * ky * v, ky * kz * v - kx * s,+ kz * kx * v - ky * s, kz * ky * v + kx * s, c + kz * kz * v,+ )+} /**- * Short-window IMU displacement for visual-inertial scale alignment.+ * Continuous short-horizon IMU integration for visual-inertial scale. *- * This is deliberately not a full inertial navigator: gravity is- * removed with the tracker's current world-up and orientation, accel- * is rotated into the world frame, and displacement comes from double- * integration over one keyframe window assuming near-zero velocity at- * the window edges (the user is moving the phone by hand, pausing at- * each keyframe beat). Windows are seconds at most, so drift stays- * bounded; the scale estimator's confidence gate rejects windows where- * the assumption breaks. Honest accuracy note: this is the pipeline's- * weakest link, and the confidence threshold exists because of it.+ * Samples are integrated once, on arrival: orientation by gyro+ * integration (world frame = first camera frame, matching the visual+ * tracker's fiat), gravity removed with that orientation, velocity and+ * position carried continuously. A scale window's displacement is then+ * just the difference of integrated positions at its endpoints.+ *+ * The previous design re-integrated each window from scratch with two+ * fatal assumptions: zero velocity at the window start (false during a+ * continuous walk โ it throws away `v0 * T`, the same order as the+ * window's own displacement) and one orientation for the whole window+ * (gravity leaks whenever the phone turns mid-window). Both scattered+ * the visual/IMU displacement ratios so the scale confidence never+ * converged, on device or in the synthetic harness.+ *+ * This is still not a full inertial navigator: gyro bias and accel bias+ * are not estimated, so integrated positions are only trusted over a+ * few seconds โ which is all a scale window spans. */ internal class ImuIntegrator { private val samples = ArrayList<ImuSample>() private var firstAccel: Vec3? = null + // Continuous integration state, advanced as samples arrive.+ private var processed = 0+ private var orientR = doubleArrayOf(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)+ private var vel = Vec3(0.0, 0.0, 0.0)+ private var pos = Vec3(0.0, 0.0, 0.0)+ private var lastTNs = 0L+ private var upWorld: Vec3? = null+ /** Accel bias in camera axes, estimated from the initial still period. */+ private var accelBias: Vec3? = null+ /** Integrated position at each processed sample, parallel to sample times. */+ private val track = ArrayList<Pair<Long, Vec3>>()+ /** Consume a packed batch: `[tNs, gx, gy, gz, ax, ay, az]` per sample. */ fun push(packed: DoubleArray) { var i = 0 while (i + STRIDE <= packed.size) { val t = packed[i].toLong()- val ax = packed[i + AX_OFFSET]- val ay = packed[i + AY_OFFSET]- val az = packed[i + AZ_OFFSET]- samples += ImuSample(t, ax, ay, az)- if (firstAccel == null) firstAccel = Vec3(ax, ay, az)+ samples += ImuSample(+ t,+ packed[i + AX_OFFSET], packed[i + AY_OFFSET], packed[i + AZ_OFFSET],+ packed[i + 1], packed[i + 2], packed[i + 3],+ )+ if (firstAccel == null) {+ firstAccel = Vec3(packed[i + AX_OFFSET], packed[i + AY_OFFSET], packed[i + AZ_OFFSET])+ } i += STRIDE }- // Windows only ever look back a few seconds; cap the buffer.+ integrateNewSamples()+ // Windows only ever look back a few seconds; cap the buffers. if (samples.size > MAX_SAMPLES) {- samples.subList(0, samples.size - MAX_SAMPLES).clear()+ val drop = samples.size - MAX_SAMPLES+ samples.subList(0, drop).clear()+ track.subList(0, minOf(drop, track.size)).clear()+ processed = maxOf(0, processed - drop)+ }+ }++ private fun integrateNewSamples() {+ // Calibration from the initial still period (the user has just+ // opened the AR screen): gravity-up from the mean accel direction,+ // and accel bias as the mean's deviation from exactly g along up.+ // Uncalibrated accel bias (~0.02 m/s^2) otherwise double-integrates+ // into centimetres of phantom displacement within seconds.+ if (accelBias == null) {+ if (samples.size < CALIBRATION_SAMPLES) return+ val head = samples.subList(0, CALIBRATION_SAMPLES)+ val mean = Vec3(+ head.sumOf { it.ax } / head.size,+ head.sumOf { it.ay } / head.size,+ head.sumOf { it.az } / head.size,+ )+ val len = sqrt(mean.x * mean.x + mean.y * mean.y + mean.z * mean.z)+ if (len <= 1.0) return+ val up = Vec3(mean.x / len, mean.y / len, mean.z / len)+ upWorld = up+ accelBias = Vec3(+ mean.x - up.x * GRAVITY,+ mean.y - up.y * GRAVITY,+ mean.z - up.z * GRAVITY,+ )+ }+ val up = upWorld ?: return+ val bias = accelBias ?: return+ while (processed < samples.size) {+ val s = samples[processed]+ if (processed == 0 || lastTNs == 0L) {+ lastTNs = s.tNs+ track += s.tNs to pos+ processed+++ continue+ }+ val dt = (s.tNs - lastTNs) / NS_PER_SECOND+ lastTNs = s.tNs+ processed+++ if (dt <= 0.0 || dt > MAX_STEP_S) {+ track += s.tNs to pos+ continue+ }+ val worldAccel = rotate3(orientR, Vec3(s.ax - bias.x, s.ay - bias.y, s.az - bias.z))+ val ax = worldAccel.x - up.x * GRAVITY+ val ay = worldAccel.y - up.y * GRAVITY+ val az = worldAccel.z - up.z * GRAVITY+ vel = Vec3(vel.x + ax * dt, vel.y + ay * dt, vel.z + az * dt)+ pos = Vec3(pos.x + vel.x * dt, pos.y + vel.y * dt, pos.z + vel.z * dt)+ orientR = multiply3(orientR, rodrigues(s.gx * dt, s.gy * dt, s.gz * dt))+ track += s.tNs to pos } } @@ -54,46 +162,38 @@ internal class ImuIntegrator { } /**- * Double-integrated displacement between [fromNs] and [toNs], in- * world coordinates, or null when the window has too few samples.- * [worldFromCamR] orients camera-frame accel into the world.+ * Integrated displacement between [fromNs] and [toNs] in world+ * coordinates, or null when the track does not cover the window. */- fun displacementBetween(- fromNs: Long,- toNs: Long,- worldFromCamR: DoubleArray,- worldUp: Vec3,- ): Vec3? {- if (toNs <= fromNs) return null- val window = samples.filter { it.tNs in fromNs..toNs }- if (window.size < MIN_WINDOW_SAMPLES) return null- var vx = 0.0- var vy = 0.0- var vz = 0.0- var px = 0.0- var py = 0.0- var pz = 0.0- var prevT = window.first().tNs- for (s in window) {- val dt = (s.tNs - prevT) / NS_PER_SECOND- prevT = s.tNs- if (dt <= 0.0 || dt > MAX_STEP_S) continue- val cam = Vec3(s.ax, s.ay, s.az)- val world = rotate3(worldFromCamR, cam)- // Remove gravity: accelerometer measures specific force, so- // world accel already includes +g along up; subtract it.- val ax = world.x - worldUp.x * GRAVITY- val ay = world.y - worldUp.y * GRAVITY- val az = world.z - worldUp.z * GRAVITY- vx += ax * dt; vy += ay * dt; vz += az * dt- px += vx * dt; py += vy * dt; pz += vz * dt+ fun displacementBetween(fromNs: Long, toNs: Long): Vec3? {+ if (toNs <= fromNs || track.size < MIN_WINDOW_SAMPLES) return null+ val a = positionAt(fromNs) ?: return null+ val b = positionAt(toNs) ?: return null+ return b - a+ }++ private fun positionAt(tNs: Long): Vec3? {+ // Latest integrated position at or before tNs (windows end on a+ // frame timestamp, which always follows the newest IMU sample).+ var found: Vec3? = null+ for ((t, p) in track) {+ if (t > tNs) break+ found = p }- return Vec3(px, py, pz)+ return found } fun reset() { samples.clear()+ track.clear() firstAccel = null+ processed = 0+ orientR = doubleArrayOf(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)+ vel = Vec3(0.0, 0.0, 0.0)+ pos = Vec3(0.0, 0.0, 0.0)+ lastTNs = 0L+ upWorld = null+ accelBias = null } private companion object {@@ -103,6 +203,14 @@ internal class ImuIntegrator { const val AY_OFFSET = 5 const val AZ_OFFSET = 6 const val MAX_SAMPLES = 4000+ /**+ * ~0.2 s at 200 Hz: the initial-still calibration window. Kept+ * short on purpose: a longer window risks overlapping the user's+ * first motion, and the motion's mean accel then lands in the+ * "bias" estimate and cancels real signal (harness: a 0.5 s+ * window ate ~0.19 m/s^2 and halved integrated displacement).+ */+ const val CALIBRATION_SAMPLES = 40 const val MIN_WINDOW_SAMPLES = 4 const val NS_PER_SECOND = 1e9 const val MAX_STEP_S = 0.1
measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt b/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.ktindex 83c064ed72..627c6cd917 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt@@ -3,8 +3,9 @@ package com.vayunmathur.measure.platform.vio import com.vayunmathur.measure.domain.Pose3 import com.vayunmathur.measure.domain.Vec3 -/** One tracked correspondence, in pixels: previous -> current. */+/** One tracked correspondence, in pixels: previous -> current. [id] is stable for the feature's life. */ data class CvPair(+ val id: Long, val prevX: Double, val prevY: Double, val currX: Double,@@ -19,6 +20,11 @@ data class CvFrameFlow( val pose: Pose3?, /** Feature points seeded for the next frame, after top-up. */ val pointCount: Int,+ val seeded: Int = 0,+ val forwardOk: Int = 0,+ val fbSurvivors: Int = 0,+ /** RANSAC inliers; -1 = did not run, -2 = ran but no pose. */+ val ransacInliers: Int = -1, ) /**@@ -73,21 +79,30 @@ object MeasureCvNative { } val pairs = ArrayList<CvPair>(pairCount) for (i in 0 until pairCount) {- val base = HEADER_SIZE + i * 4+ val base = HEADER_SIZE + i * VALUES_PER_PAIR if (base + LAST_PAIR_OFFSET >= raw.size) break- pairs += CvPair(raw[base], raw[base + 1], raw[base + 2], raw[base + LAST_PAIR_OFFSET])+ pairs += CvPair(+ raw[base].toLong(),+ raw[base + 1], raw[base + 2], raw[base + 3], raw[base + LAST_PAIR_OFFSET],+ ) } return CvFrameFlow( firstFrame = raw[2] != 0.0, pairs = pairs, pose = pose, pointCount = raw[3].toInt(),+ seeded = if (raw.size > 16) raw[16].toInt() else 0,+ forwardOk = if (raw.size > 17) raw[17].toInt() else 0,+ fbSurvivors = if (raw.size > 18) raw[18].toInt() else 0,+ ransacInliers = if (raw.size > 19) raw[19].toInt() else -1, ) } - private const val HEADER_SIZE = 16+ private const val HEADER_SIZE = 20+ /** Values per tracked pair in the native array: id, prevX, prevY, currX, currY. */+ private const val VALUES_PER_PAIR = 5 /** Offset of the last (current-y) value within one tracked pair. */- private const val LAST_PAIR_OFFSET = 3+ private const val LAST_PAIR_OFFSET = 4 private external fun nativeCreateSession( fx: Double,
measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt b/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.ktindex 3bce2a2f97..c1ceb564fc 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt@@ -15,8 +15,10 @@ import com.vayunmathur.measure.domain.project import com.vayunmathur.measure.domain.ransacPlane import com.vayunmathur.measure.domain.reprojectionErrorPx import com.vayunmathur.measure.domain.rotate3+import com.vayunmathur.measure.domain.solveCameraCentre import com.vayunmathur.measure.domain.triangulate import com.vayunmathur.measure.platform.Intrinsics+import com.vayunmathur.library.log.Log import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.sqrt@@ -31,7 +33,12 @@ data class VioFrameResult( ) /** One triangulated landmark, in visual (scale-free) world units. */-private data class Landmark(val position: Vec3, var observations: Int)+private data class Landmark(+ val id: Long,+ val position: Vec3,+ var observations: Int,+ val birthFrame: Int = 0,+) /** * Visual-inertial tracker behind the AR measurement flow.@@ -54,7 +61,14 @@ private data class Landmark(val position: Vec3, var observations: Int) * to false and the UI falls back to the manual tools instead of * crashing. */-class VioEngine(private val intrinsics: Intrinsics) {+class VioEngine(+ private val intrinsics: Intrinsics,+ /** Actual analysis-frame size the intrinsics were resolved for (0 = unknown). */+ val frameWidth: Int = 0,+ val frameHeight: Int = 0,+ /** Clockwise rotation of the analysis frames vs the display (from ImageProxy). */+ private val rotationDegrees: Int = 0,+) { /** Native-engine availability and per-frame tuning constants for [VioEngine]. */ companion object {@@ -66,19 +80,26 @@ class VioEngine(private val intrinsics: Intrinsics) { private const val MIN_TRACKED_FOR_POSE = 15 private const val GOOD_TRACKED = 40 private const val GOOD_LANDMARKS = 20- private const val KEYFRAME_PARALLAX_PX = 24.0+ private const val KEYFRAME_PARALLAX_PX = 14.0 private const val MAX_REPROJECTION_PX = 2.0 private const val SCALE_CONFIDENCE_MIN = 0.6 private const val SCALE_WINDOWS_MIN = 4 private const val MAX_LANDMARKS = 400+ private const val MIN_LANDMARKS_FOR_CENTRE = 12 private const val LOST_AFTER_FAILURES = 3 private const val PLANE_EXTENT_MARGIN_M = 0.5 /** Landmarks closer than this (visual units) are the same point. */ private const val MIN_LANDMARK_SEPARATION = 0.01- /** Scale-estimate windows kept for the visual/IMU alignment. */- private const val MAX_SCALE_WINDOWS = 12+ /**+ * Scale-estimate windows kept for the visual/IMU alignment. Only+ * recent windows price the scale: the landmark map's gauge drifts+ * slowly as cohorts are re-triangulated, and a long memory+ * averages stale gauges into the estimate.+ */+ private const val MAX_SCALE_WINDOWS = 6 /** Landmarks needed before a dominant plane is worth fitting. */ private const val MIN_LANDMARKS_FOR_PLANE = 12+ const val TAG = "MeasureCv" } private val cameraMatrix = doubleArrayOf(@@ -97,10 +118,12 @@ class VioEngine(private val intrinsics: Intrinsics) { private var worldFromCam: Pose3 = Pose3.identity() private var keyframePose: Pose3? = null- private var keyframePoints: List<Pair<Double, Double>> = emptyList()+ /** Keyframe points by stable feature id (see CvPair.id). */+ private var keyframePoints: Map<Long, Pair<Double, Double>> = emptyMap() private var keyframeTimeNs: Long = 0L private val landmarks = ArrayList<Landmark>()+ private val landmarkById = HashMap<Long, Landmark>() private var plane: FittedPlane? = null private var planeExtentM: Double = 0.0 @@ -120,8 +143,46 @@ class VioEngine(private val intrinsics: Intrinsics) { @Volatile private var lastQuality: TrackingQuality = TrackingQuality.Initialising + /**+ * Device->camera rotation for the accel/gyro axes, as a row-major 3x3.+ *+ * SensorEvent values are in Android device axes (x right, y up, z out+ * of the screen); the visual pose lives in raw camera-image axes+ * (x = image right, y = image down, z into the scene). The fixed part+ * maps device->image axes at zero rotation, `(ax, -ay, -az)`; the+ * in-plane part then rotates by the frame rotation. Without this the+ * integrator's gravity subtraction uses a "camera frame" the camera+ * never had: on a still phone it double-integrated metres of phantom+ * displacement from un-cancelled gravity, the visual/IMU ratios+ * scattered, and scale confidence stayed at 0 forever (device logs,+ * 2026-11-17).+ */+ private val deviceToCameraR: DoubleArray = run {+ val theta = Math.toRadians(-rotationDegrees.toDouble())+ val c = kotlin.math.cos(theta)+ val s = kotlin.math.sin(theta)+ // Rz(-rotation) * diag(1, -1, -1), expanded.+ doubleArrayOf(c, s, 0.0, s, -c, 0.0, 0.0, 0.0, -1.0)+ }+ /** Feed the packed IMU batch (`[tNs, gx, gy, gz, ax, ay, az]` per sample). */ fun pushImu(packed: DoubleArray) {+ // Re-express gyro+accel in camera axes before integration.+ val r = deviceToCameraR+ run {+ var i = 0+ while (i + 7 <= packed.size) {+ for (base in intArrayOf(i + 1, i + 4)) {+ val x = packed[base]+ val y = packed[base + 1]+ val z = packed[base + 2]+ packed[base] = r[0] * x + r[1] * y + r[2] * z+ packed[base + 1] = r[3] * x + r[4] * y + r[5] * z+ packed[base + 2] = r[6] * x + r[7] * y + r[8] * z+ }+ i += 7+ }+ } imu.push(packed) if (!upSeeded) { imu.meanAccelCam()?.let { a ->@@ -145,7 +206,19 @@ class VioEngine(private val intrinsics: Intrinsics) { ): VioFrameResult { framesSeen++ val flow = MeasureCvNative.processFrame(nativeHandle, yPlane, width, height, rowStride)- ?: return trackingFailure(0)+ ?: run {+ if (framesSeen % 30 == 1) Log.dev(TAG, "frame=$framesSeen native=null handle=$nativeHandle avail=$available")+ return trackingFailure(0)+ }+ if (framesSeen % 30 == 1 || flow.firstFrame) {+ Log.dev(+ TAG,+ "frame=$framesSeen ${width}x$height stride=$rowStride first=${flow.firstFrame} " ++ "seeded=${flow.seeded} cornersNext=${flow.pointCount} fwdOk=${flow.forwardOk} " ++ "fb=${flow.fbSurvivors} pairs=${flow.pairs.size} ransac=${flow.ransacInliers} " ++ "pose=${flow.pose != null} landmarks=${landmarks.size} scaleConf=$scaleConfidence scale=$scale",+ )+ } if (flow.firstFrame) { return result(TrackingQuality.Initialising, flow.pointCount) }@@ -155,9 +228,68 @@ class VioEngine(private val intrinsics: Intrinsics) { val rel = flow.pose ?: return poseFailure(flow.pairs) consecutiveFailures = 0 worldFromCam = chainPose(worldFromCam, rel)- val prevPts = flow.pairs.map { it.prevX to it.prevY }+ // Once a landmark map exists, replace the chained centre with a+ // centre solved against the map: chained centres accumulate one+ // *unit* translation per frame (essential poses have no scale),+ // which encodes frame count rather than distance and made every+ // IMU/visual scale ratio depend on walking speed. Rotation from+ // the chain is unaffected and is kept.+ if (landmarks.size >= MIN_LANDMARKS_FOR_CENTRE) {+ val matched = ArrayList<Pair<Landmark, CvPair>>()+ for (pair in flow.pairs) {+ val lm = landmarkById[pair.id] ?: continue+ matched += lm to pair+ lm.observations+++ }+ // Prefer well-observed landmarks: young ones were triangulated+ // from early poses and can sit in a distorted part of the map.+ val mature = matched.filter { it.first.observations >= 4 }+ val use = if (mature.size >= MIN_LANDMARKS_FOR_CENTRE) mature else matched+ val observations = use.map { (lm, pair) ->+ val bearingCam = Vec3(+ (pair.currX - intrinsics.cx) / intrinsics.fx,+ (pair.currY - intrinsics.cy) / intrinsics.fy,+ 1.0,+ )+ lm.position to rotate3(worldFromCam.r, bearingCam)+ }+ debugCentreAttempts+++ val solved = solveCameraCentre(observations)+ if (solved != null) {+ debugCentreSolves+++ if (centreSolveBirthFrame < 0) centreSolveBirthFrame = framesSeen+ // One-time map heal: landmarks triangulated before centre+ // solving existed were placed from unit-chained (time-+ // warped) poses, so each early cohort is a differently+ // warped copy of the scene and the solved centre jumps as+ // cohorts rotate. Once solving is established, drop the+ // pre-solve map; it rebuilds from solved poses only.+ if (!preSolveMapPurged && framesSeen - centreSolveBirthFrame > 20) {+ preSolveMapPurged = true+ val before = landmarks.size+ landmarks.removeAll { it.birthFrame < centreSolveBirthFrame }+ landmarkById.clear()+ landmarks.forEach { landmarkById[it.id] = it }+ // Scale windows spanning the warp are meaningless.+ visualWindows.clear()+ imuWindows.clear()+ scale = null+ scaleConfidence = 0.0+ Log.dev(TAG, "map heal: purged ${before - landmarks.size} pre-solve landmarks")+ }+ if (framesSeen % 30 == 1) {+ Log.dev(TAG, "centre solve obs=${observations.size} chained=${worldFromCam.t} solved=$solved")+ }+ worldFromCam = Pose3(worldFromCam.r, solved)+ // Keep the last few solved centres: their average poses+ // keyframes and scale windows. A single frame's solve+ // wanders by more than a window's real motion (cohort-+ // correlated landmark depth errors), and triangulating+ // from such a pose poisons the next cohort's depths.+ }+ } val currPts = flow.pairs.map { it.currX to it.currY }- updateKeyframes(prevPts, currPts, timestampNs)+ updateKeyframes(flow.pairs, timestampNs) val q = when { scale == null -> TrackingQuality.Initialising currPts.size >= GOOD_TRACKED && landmarks.size >= GOOD_LANDMARKS ->@@ -189,18 +321,37 @@ class VioEngine(private val intrinsics: Intrinsics) { ) } - private fun updateKeyframes(- prevPts: List<Pair<Double, Double>>,- currPts: List<Pair<Double, Double>>,- timestampNs: Long,- ) {+ private fun updateKeyframes(pairs: List<CvPair>, timestampNs: Long) { val kf = keyframePose if (kf == null) {- setKeyframe(currPts, timestampNs)- } else if (meanFlow(prevPts, currPts) >= KEYFRAME_PARALLAX_PX) {- onKeyframe(kf, currPts, timestampNs)- setKeyframe(currPts, timestampNs)+ setKeyframe(pairs, timestampNs)+ return }+ // Parallax is accumulated keyframe->current flow for the *same*+ // features (matched by stable id), not one frame's flow: a slow+ // scanning pan moves only a few px/frame, so the old per-frame+ // 24px gate never fired and no keyframe after the first existed.+ val matched = pairs.filter { keyframePoints.containsKey(it.id) }+ if (matched.size < MIN_TRACKED_FOR_POSE) {+ // Keyframe features are gone; re-anchor on the current set.+ debugReanchors+++ Log.dev(TAG, "keyframe re-anchor: only ${matched.size} kf features survive")+ setKeyframe(pairs, timestampNs)+ } else if (meanKfFlow(matched) >= KEYFRAME_PARALLAX_PX) {+ debugKeyframes+++ onKeyframe(kf, matched, timestampNs)+ setKeyframe(pairs, timestampNs)+ }+ }++ private fun meanKfFlow(matched: List<CvPair>): Double {+ if (matched.isEmpty()) return 0.0+ var sum = 0.0+ for (p in matched) {+ val kfPt = keyframePoints[p.id] ?: continue+ sum += kfPt.distanceTo(p.currX to p.currY)+ }+ return sum / matched.size } private fun result(quality: TrackingQuality, tracked: Int): VioFrameResult {@@ -279,12 +430,36 @@ class VioEngine(private val intrinsics: Intrinsics) { return out } + /** Harness/diagnostics accessors: current world pose and locked scale. */+ internal fun debugPose(): Pose3 = worldFromCam+ internal fun debugScale(): Double? = scale++ internal var debugCentreSolves = 0+ internal var debugCentreAttempts = 0+ internal var debugKeyframes = 0+ internal var debugTriangulated = 0+ internal var debugReprojRejected = 0+ internal var debugReanchors = 0++ /** Frame of the first successful centre solve; -1 until then. */+ private var centreSolveBirthFrame = -1+ private var preSolveMapPurged = false++ /** Per-window (visualMag, imuMag) pairs feeding the scale estimator. */+ internal fun debugScaleWindows(): List<Pair<Double, Double>> =+ visualWindows.zip(imuWindows) { v, m ->+ val vm = sqrt(v.x * v.x + v.y * v.y + v.z * v.z)+ val im = sqrt(m.x * m.x + m.y * m.y + m.z * m.z)+ vm to im+ }+ fun reset() { MeasureCvNative.reset(nativeHandle) worldFromCam = Pose3.identity() keyframePose = null- keyframePoints = emptyList()+ keyframePoints = emptyMap() landmarks.clear()+ landmarkById.clear() plane = null planeExtentM = 0.0 scale = null@@ -295,6 +470,14 @@ class VioEngine(private val intrinsics: Intrinsics) { imu.reset() consecutiveFailures = 0 framesSeen = 0+ centreSolveBirthFrame = -1+ preSolveMapPurged = false+ debugCentreSolves = 0+ debugCentreAttempts = 0+ debugKeyframes = 0+ debugTriangulated = 0+ debugReprojRejected = 0+ debugReanchors = 0 lastQuality = TrackingQuality.Initialising } @@ -302,43 +485,105 @@ class VioEngine(private val intrinsics: Intrinsics) { MeasureCvNative.destroySession(nativeHandle) } - private fun onKeyframe(prevKfPose: Pose3, currPts: List<Pair<Double, Double>>, timestampNs: Long) {+ private fun onKeyframe(prevKfPose: Pose3, matched: List<CvPair>, timestampNs: Long) { val kfPoints = keyframePoints- if (kfPoints.size >= MIN_TRACKED_FOR_POSE && currPts.size >= MIN_TRACKED_FOR_POSE) {- // Correspondences survived from the keyframe are the pairs LK- // has carried; indices align because keyframe points were the- // previous frame's tracked set when the baseline opened.- val pa = projectionMatrix(cameraMatrix, prevKfPose)- val pb = projectionMatrix(cameraMatrix, worldFromCam)- val pairs = minOf(kfPoints.size, currPts.size)+ if (kfPoints.size >= MIN_TRACKED_FOR_POSE && matched.size >= MIN_TRACKED_FOR_POSE) {+ // Correspondences are matched by stable feature id: the same+ // scene point in the keyframe and in the current frame. (The+ // old code paired list indices, which name different points+ // as soon as LK/FB/RANSAC filtering drops or top-up inserts+ // any point, so every triangulation failed its reprojection+ // gate and no landmark was ever created.)+ // Keyframe-local refinement (a two-view bundle adjustment):+ // triangulate the matched bearings, re-solve both keyframe+ // centres against those points, and repeat. Poses and+ // landmarks become mutually consistent within the window+ // instead of each cohort inheriting the single-frame centre+ // noise (or smoothing lag) of the poses that created it โ+ // the inconsistency that scattered scale ratios ~3x.+ var poseA = prevKfPose+ var poseB = worldFromCam+ var refinedWorld: List<Pair<CvPair, Vec3>> = emptyList()+ repeat(3) {+ val paR = projectionMatrix(cameraMatrix, poseA)+ val pbR = projectionMatrix(cameraMatrix, poseB)+ val tri = ArrayList<Pair<CvPair, Vec3>>()+ for (pair in matched) {+ val a = kfPoints[pair.id] ?: continue+ val b = pair.currX to pair.currY+ val world = triangulate(paR, a, pbR, b) ?: continue+ val errA = reprojectionErrorPx(paR, world, a)+ val errB = reprojectionErrorPx(pbR, world, b)+ if (errA > MAX_REPROJECTION_PX || errB > MAX_REPROJECTION_PX) continue+ tri += pair to world+ }+ refinedWorld = tri+ if (tri.size < MIN_TRACKED_FOR_POSE) return@repeat+ val obsA = tri.map { (pair, world) ->+ val a = kfPoints[pair.id]!!+ val bearing = Vec3(+ (a.first - intrinsics.cx) / intrinsics.fx,+ (a.second - intrinsics.cy) / intrinsics.fy,+ 1.0,+ )+ world to rotate3(poseA.r, bearing)+ }+ val obsB = tri.map { (pair, world) ->+ val bearing = Vec3(+ (pair.currX - intrinsics.cx) / intrinsics.fx,+ (pair.currY - intrinsics.cy) / intrinsics.fy,+ 1.0,+ )+ world to rotate3(poseB.r, bearing)+ }+ solveCameraCentre(obsA)?.let { poseA = Pose3(poseA.r, it) }+ solveCameraCentre(obsB)?.let { poseB = Pose3(poseB.r, it) }+ }+ worldFromCam = poseB var added = 0- for (i in 0 until pairs) {- val a = kfPoints[i]- val b = currPts[i]- val world = triangulate(pa, a, pb, b)- if (world != null) {- val errA = reprojectionErrorPx(pa, world, a)- val errB = reprojectionErrorPx(pb, world, b)- val isNewLandmark = landmarks.none {- it.position.distanceTo(world) < MIN_LANDMARK_SEPARATION- }- if (errA <= MAX_REPROJECTION_PX && errB <= MAX_REPROJECTION_PX && isNewLandmark) {- landmarks += Landmark(world, observations = 2)- added++- }+ val reprojRejected = matched.size - refinedWorld.size+ debugReprojRejected += reprojRejected+ for ((pair, world) in refinedWorld) {+ val existing = landmarkById[pair.id]+ if (existing != null) {+ // Re-triangulate with the current (map-solved) poses:+ // landmarks born from early unit-chained poses carry+ // that distortion until refreshed like this.+ landmarks.remove(existing)+ val refreshed = Landmark(pair.id, world, existing.observations + 1, framesSeen)+ landmarks += refreshed+ landmarkById[pair.id] = refreshed+ continue }+ if (landmarks.any { it.position.distanceTo(world) < MIN_LANDMARK_SEPARATION }) continue+ val lm = Landmark(pair.id, world, observations = 2, birthFrame = framesSeen)+ landmarks += lm+ debugTriangulated+++ landmarkById[lm.id] = lm+ added++ } if (landmarks.size > MAX_LANDMARKS) {+ // Evict the least-observed landmarks first: early,+ // pre-map triangulations are exactly the ones with few+ // confirming observations.+ landmarks.sortBy { it.observations } landmarks.subList(0, landmarks.size - MAX_LANDMARKS).clear()+ landmarkById.clear()+ landmarks.forEach { landmarkById[it.id] = it } }+ Log.dev(+ TAG,+ "keyframe kfPts=${kfPoints.size} matched=${matched.size} triangulated=$added " ++ "reprojRejected=$reprojRejected landmarks=${landmarks.size} plane=${plane != null}",+ ) if (added > 0) refitPlane() updateScaleWindows(timestampNs) } } - private fun setKeyframe(points: List<Pair<Double, Double>>, timestampNs: Long) {+ private fun setKeyframe(points: List<CvPair>, timestampNs: Long) { keyframePose = worldFromCam- keyframePoints = points+ keyframePoints = points.associate { it.id to (it.currX to it.currY) } keyframeTimeNs = timestampNs lastKeyframeCentre = worldFromCam.t }@@ -347,9 +592,7 @@ class VioEngine(private val intrinsics: Intrinsics) { val centre = worldFromCam.t val last = lastKeyframeCentre ?: return val visual = centre - last- val imuDisp = imu.displacementBetween(- keyframeTimeNs, timestampNs, worldFromCam.r, worldUp,- )+ val imuDisp = imu.displacementBetween(keyframeTimeNs, timestampNs) if (imuDisp != null) { visualWindows += visual imuWindows += imuDisp@@ -362,7 +605,14 @@ class VioEngine(private val intrinsics: Intrinsics) { if (est.pairs >= SCALE_WINDOWS_MIN && est.confidence >= SCALE_CONFIDENCE_MIN) { scale = est.scale }- }+ Log.dev(+ TAG,+ "scale windows=${visualWindows.size} pairs=${est.pairs} conf=${est.confidence} " ++ "scale=${est.scale} locked=${scale != null} visual=$visual imu=$imuDisp",+ )+ } ?: Log.dev(TAG, "scale windows=${visualWindows.size} estimate=null imuDisp=$imuDisp")+ } else {+ Log.dev(TAG, "scale imuDisp=null window ${keyframeTimeNs}..$timestampNs (too few IMU samples?)") } lastKeyframeCentre = centre }@@ -391,13 +641,6 @@ class VioEngine(private val intrinsics: Intrinsics) { return Vec3(worldDir.x / len, worldDir.y / len, worldDir.z / len) } - private fun meanFlow(a: List<Pair<Double, Double>>, b: List<Pair<Double, Double>>): Double {- if (a.isEmpty()) return 0.0- val n = minOf(a.size, b.size)- var sum = 0.0- for (i in 0 until n) sum += a[i].distanceTo(b[i])- return sum / n- } } private operator fun Vec3.times(s: Double): Vec3 = Vec3(x * s, y * s, z * s)
measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.ktindex 7e6cd5620e..66cec2c776 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt@@ -91,8 +91,8 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { // analysis size, not the canvas size. val projected = eng.projectPoints( flat,- ANALYSIS_SIZE.width.toDouble(),- ANALYSIS_SIZE.height.toDouble(),+ eng.frameWidth.takeIf { it > 0 }?.toDouble() ?: ANALYSIS_SIZE.width.toDouble(),+ eng.frameHeight.takeIf { it > 0 }?.toDouble() ?: ANALYSIS_SIZE.height.toDouble(), ) // Third component is the visibility flag: points behind the // camera must not be drawn in the top-left corner.
measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt b/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.ktindex 1e3ae3f517..70eaa53d50 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt@@ -26,6 +26,7 @@ import androidx.lifecycle.repeatOnLifecycle import com.vayunmathur.measure.data.model.TrackingQuality import com.vayunmathur.measure.platform.CameraIntrinsicsResolver import com.vayunmathur.measure.platform.vio.VioEngine+import com.vayunmathur.library.log.Log import com.vayunmathur.measure.platform.sensor.ImuRecorder import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow@@ -65,8 +66,12 @@ fun MeasureCamera( lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { val executor = Executors.newSingleThreadExecutor() var provider: ProcessCameraProvider? = null- val engine = createEngine(context)- onEngineReady(engine)+ // The engine is created lazily on the first frame, with+ // intrinsics resolved for the size CameraX actually delivers+ // (see VioFrameAnalyzer): resolving for the requested size up+ // front silently miscalibrates every bearing when the delivered+ // size differs (different aspect = cropped principal point).+ var engine: VioEngine? = null try { provider = ProcessCameraProvider.awaitInstance(context) provider.unbindAll()@@ -93,7 +98,19 @@ fun MeasureCamera( .also { it.setAnalyzer( executor,- VioFrameAnalyzer(engine, imuRecorder, onTrackingUpdate, onDiagnostics),+ VioFrameAnalyzer(+ null,+ imuRecorder,+ onTrackingUpdate,+ onDiagnostics,+ engineFactory = { size, rotation ->+ createEngine(context, size, rotation)+ },+ onEngineCreated = { created ->+ engine = created+ onEngineReady(created)+ },+ ), ) } @@ -126,25 +143,59 @@ fun MeasureCamera( } } -private fun createEngine(context: Context): VioEngine? {- if (!VioEngine.available) return null- val intr = CameraIntrinsicsResolver.resolve(context, ANALYSIS_SIZE) ?: return null- return VioEngine(intr)+private fun createEngine(context: Context, actualSize: Size, rotationDegrees: Int): VioEngine? {+ if (!VioEngine.available) {+ Log.dev("MeasureCv", "engine NOT created: native unavailable")+ return null+ }+ val intr = CameraIntrinsicsResolver.resolve(context, actualSize)+ Log.dev(+ "MeasureCv",+ "engine create: actual=${actualSize.width}x${actualSize.height} " ++ "(requested ${ANALYSIS_SIZE.width}x${ANALYSIS_SIZE.height}) intrinsics=$intr " ++ "tsAlign=${CameraIntrinsicsResolver.timestampsAlignWithSensors(context)}",+ )+ if (intr == null) return null+ return VioEngine(intr, actualSize.width, actualSize.height, rotationDegrees) } internal class VioFrameAnalyzer(- private val engine: VioEngine?,+ engine: VioEngine?, private val imuRecorder: ImuRecorder, private val onTrackingUpdate: (TrackingQuality, Boolean) -> Unit, private val onDiagnostics: Diagnostics,+ private val engineFactory: ((Size, Int) -> VioEngine?)? = null,+ private val onEngineCreated: (VioEngine?) -> Unit = {}, ) : ImageAnalysis.Analyzer { + private var engine: VioEngine? = engine+ private var engineCreationTried = false+ private var buffer: ByteArray? = null private var lastFrameNs = 0L private var frameIntervalNs = 0L+ private var frameCount = 0L override fun analyze(image: ImageProxy) { try {+ frameCount+++ if (frameCount % 60L == 1L) {+ Log.dev(+ "MeasureCv",+ "analyzer frame=$frameCount ${image.width}x${image.height} format=${image.format} " ++ "rotation=${image.imageInfo.rotationDegrees} ts=${image.imageInfo.timestamp} " ++ "rowStride=${image.planes[0].rowStride} pixelStride=${image.planes[0].pixelStride} " ++ "engine=${engine != null} imuActive=${imuRecorder.isActive} imuHz=${imuRecorder.rateHz()}",+ )+ }+ if (engine == null && !engineCreationTried && engineFactory != null) {+ engineCreationTried = true+ engine = engineFactory(+ Size(image.width, image.height),+ image.imageInfo.rotationDegrees,+ )+ onEngineCreated(engine)+ } val eng = engine ?: return // Drain IMU first so every sample older than this frame is already queued,
measure/src/main/rust/src/lib.rs
diff --git a/measure/src/main/rust/src/lib.rs b/measure/src/main/rust/src/lib.rsindex dce66617a3..80016c9ffe 100644--- a/measure/src/main/rust/src/lib.rs+++ b/measure/src/main/rust/src/lib.rs@@ -32,8 +32,12 @@ const ESSENTIAL_ITERS: usize = 200; const ESSENTIAL_THRESH_PX: f64 = 1.0; /// One tracked correspondence, in pixels: previous -> current.+/// `id` is stable for a feature's whole life in the session, so callers+/// can match a point seen now against the same point in an older frame+/// (keyframe triangulation) instead of assuming list indices line up. #[derive(Clone, Copy, Debug, PartialEq)] pub struct TrackPair {+ pub id: u64, pub prev: (f64, f64), pub curr: (f64, f64), }@@ -48,6 +52,14 @@ pub struct FrameFlow { pub pose: Option<RelPose>, /// Feature points seeded for the next frame, after top-up. pub point_count: usize,+ /// Diagnostics: points carried into this frame.+ pub seeded: usize,+ /// Diagnostics: forward LK tracks that succeeded.+ pub forward_ok: usize,+ /// Diagnostics: pairs surviving the forward-backward check (pre-RANSAC).+ pub fb_survivors: usize,+ /// Diagnostics: RANSAC inlier count, or -1 when RANSAC did not run.+ pub ransac_inliers: i32, } struct Intrinsics {@@ -62,7 +74,8 @@ struct Intrinsics { pub struct CvSession { intr: Intrinsics, prev_gray: Option<Gray>,- prev_points: Vec<(f32, f32)>,+ prev_points: Vec<(u64, f32, f32)>,+ next_id: u64, } impl CvSession {@@ -71,12 +84,20 @@ impl CvSession { intr: Intrinsics { fx, fy, cx, cy }, prev_gray: None, prev_points: Vec::new(),+ next_id: 1, } } pub fn reset(&mut self) { self.prev_gray = None; self.prev_points = Vec::new();+ self.next_id = 1;+ }++ fn fresh_id(&mut self) -> u64 {+ let id = self.next_id;+ self.next_id += 1;+ id } pub fn process_frame(&mut self, gray: &Gray) -> FrameFlow {@@ -85,20 +106,33 @@ impl CvSession { _ => { let pts = corners::detect(gray); let count = pts.len();- self.prev_points = pts;+ self.prev_points = pts+ .into_iter()+ .map(|(x, y)| {+ let id = self.next_id;+ self.next_id += 1;+ (id, x, y)+ })+ .collect(); self.prev_gray = Some(gray.clone()); return FrameFlow { first_frame: true, pairs: Vec::new(), pose: None, point_count: count,+ seeded: count,+ forward_ok: 0,+ fb_survivors: 0,+ ransac_inliers: -1, }; } }; let prev_pyr = Pyramid::build(&prev_gray, PYRAMID_LEVELS); let curr_pyr = Pyramid::build(gray, PYRAMID_LEVELS);- let forward = klt::track(&prev_pyr, &curr_pyr, &self.prev_points);+ let prev_xy: Vec<(f32, f32)> =+ self.prev_points.iter().map(|&(_, x, y)| (x, y)).collect();+ let forward = klt::track(&prev_pyr, &curr_pyr, &prev_xy); let candidates: Vec<(f32, f32)> = forward .iter() .filter(|r| r.ok)@@ -119,44 +153,55 @@ impl CvSession { if !b.ok { continue; }- let (ox, oy) = self.prev_points[i];+ let (id, ox, oy) = self.prev_points[i]; let dx = b.x - ox; let dy = b.y - oy; if dx * dx + dy * dy > FB_MAX_ERROR_PX * FB_MAX_ERROR_PX { continue; } pairs.push(TrackPair {+ id, prev: (ox as f64, oy as f64), curr: (f.x as f64, f.y as f64), }); } + let seeded = self.prev_points.len();+ let forward_ok = forward.iter().filter(|r| r.ok).count();+ let fb_survivors = pairs.len(); // Essential pose on calibrated bearings; keep only RANSAC inliers // as correspondences when a pose was recovered. let mut pose = None;+ let mut ransac_inliers: i32 = -1; if pairs.len() >= 8 { let a: Vec<(f64, f64)> = pairs.iter().map(|p| self.calibrated(p.prev)).collect(); let b: Vec<(f64, f64)> = pairs.iter().map(|p| self.calibrated(p.curr)).collect(); let thresh = ESSENTIAL_THRESH_PX / ((self.intr.fx + self.intr.fy) * 0.5); if let Some((rel, inliers)) = recover_pose(&a, &b, ESSENTIAL_ITERS, thresh) {+ ransac_inliers = inliers.len() as i32; if inliers.len() >= 8 { pairs = inliers.iter().map(|&i| pairs[i]).collect(); pose = Some(rel); }+ } else {+ ransac_inliers = -2; } } // Seed the next frame: tracked points, topped up with fresh corners // so slow attrition never starves the tracker.- let mut next_points: Vec<(f32, f32)> =- pairs.iter().map(|p| (p.curr.0 as f32, p.curr.1 as f32)).collect();+ let mut next_points: Vec<(u64, f32, f32)> = pairs+ .iter()+ .map(|p| (p.id, p.curr.0 as f32, p.curr.1 as f32))+ .collect(); if next_points.len() < corners::MAX_CORNERS / 2 { for pt in corners::detect(gray) { if next_points .iter()- .all(|&(x, y)| (x - pt.0).powi(2) + (y - pt.1).powi(2) >= 100.0)+ .all(|&(_, x, y)| (x - pt.0).powi(2) + (y - pt.1).powi(2) >= 100.0) {- next_points.push(pt);+ let id = self.fresh_id();+ next_points.push((id, pt.0, pt.1)); if next_points.len() >= corners::MAX_CORNERS { break; }@@ -171,6 +216,10 @@ impl CvSession { pairs, pose, point_count,+ seeded,+ forward_ok,+ fb_survivors,+ ransac_inliers, } } @@ -307,7 +356,12 @@ mod jni_bindings { } None => v.extend(std::iter::repeat_n(0.0, 12)), }+ v.push(flow.seeded as f64);+ v.push(flow.forward_ok as f64);+ v.push(flow.fb_survivors as f64);+ v.push(flow.ransac_inliers as f64); for pair in &flow.pairs {+ v.push(pair.id as f64); v.push(pair.prev.0); v.push(pair.prev.1); v.push(pair.curr.0);
measure/src/main/rust/tests/cv_core.rs
diff --git a/measure/src/main/rust/tests/cv_core.rs b/measure/src/main/rust/tests/cv_core.rsindex 1acf3175de..73918cc545 100644--- a/measure/src/main/rust/tests/cv_core.rs+++ b/measure/src/main/rust/tests/cv_core.rs@@ -81,6 +81,33 @@ fn flat_frames_never_track() { assert!(second.pose.is_none()); } +#[test]+fn pair_ids_are_stable_across_frames() {+ // Keyframe triangulation matches keyframe<->current points by id, so+ // an id must name the same feature for its whole tracked life and+ // must not repeat within one frame.+ let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);+ s.process_frame(&frame(320, 240, 0, 0));+ let f2 = s.process_frame(&frame(320, 240, 3, 1));+ let f3 = s.process_frame(&frame(320, 240, 6, 2));+ assert!(f2.pairs.len() >= 15 && f3.pairs.len() >= 15);+ for flow in [&f2, &f3] {+ let mut ids: Vec<u64> = flow.pairs.iter().map(|p| p.id).collect();+ ids.sort_unstable();+ ids.dedup();+ assert_eq!(ids.len(), flow.pairs.len(), "duplicate id in one frame");+ }+ let persisted = f3+ .pairs+ .iter()+ .filter(|p| f2.pairs.iter().any(|q| q.id == p.id))+ .count();+ assert!(+ persisted >= 10,+ "expected most features to persist with stable ids, got {persisted}"+ );+}+ #[test] fn reset_returns_to_first_frame() { let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);
measure/src/test/java/com/vayunmathur/measure/platform/SyntheticVioHarnessTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/platform/SyntheticVioHarnessTest.kt b/measure/src/test/java/com/vayunmathur/measure/platform/SyntheticVioHarnessTest.ktnew file mode 100644index 0000000000..a6839a9a3b--- /dev/null+++ b/measure/src/test/java/com/vayunmathur/measure/platform/SyntheticVioHarnessTest.kt@@ -0,0 +1,362 @@+package com.vayunmathur.measure.platform++import com.vayunmathur.measure.domain.HitSelector+import com.vayunmathur.measure.domain.Vec3+import com.vayunmathur.measure.platform.vio.VioEngine+import org.junit.Test+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt+import kotlin.random.Random++/**+ * Synthetic ground-truth validation of the whole VIO pipeline.+ *+ * A textured two-plane scene is rendered from a defined camera trajectory+ * at the analyzer's resolution; accel/gyro samples are synthesized from+ * the same trajectory (in Android device axes, so the engine's+ * device->camera rotation is exercised too) and the real [VioEngine]+ * (Rust corners/LK/essential + Kotlin chaining/triangulation/IMU scale)+ * consumes both. Metrics are printed as a table and the walk scenarios+ * assert sane bars. Deterministic seeds throughout.+ */+class SyntheticVioHarnessTest {++ private val w = 640+ private val h = 480+ private val fx = 450.0+ private val fy = 450.0+ private val cx = 320.0+ private val cy = 240.0++ // ---- scene texture (wrapped, sampled bilinearly) ----+ private val texSize = 1024+ private val texture = FloatArray(texSize * texSize).also { t ->+ val rnd = Random(42)+ val block = FloatArray((texSize / 8) * (texSize / 8)) { (rnd.nextFloat() - 0.5f) * 110f }+ for (y in 0 until texSize) {+ for (x in 0 until texSize) {+ var v = 128f ++ 55f * sin(x * 0.11f) * cos(y * 0.13f) ++ 35f * sin((x + y) * 0.045f) ++ block[(y / 8) * (texSize / 8) + (x / 8)]+ v += (rnd.nextFloat() - 0.5f) * 18f+ t[y * texSize + x] = v.coerceIn(0f, 255f)+ }+ }+ }++ private fun sampleTex(u: Double, v: Double, contrast: Double): Double {+ val x = ((u % texSize) + texSize) % texSize+ val y = ((v % texSize) + texSize) % texSize+ val x0 = x.toInt()+ val y0 = y.toInt()+ val x1 = (x0 + 1) % texSize+ val y1 = (y0 + 1) % texSize+ val ax = x - x0+ val ay = y - y0+ val top = texture[y0 * texSize + x0] * (1 - ax) + texture[y0 * texSize + x1] * ax+ val bot = texture[y1 * texSize + x0] * (1 - ax) + texture[y1 * texSize + x1] * ax+ val value = top * (1 - ay) + bot * ay+ return 128.0 + (value - 128.0) * contrast+ }++ // Rays in camera coords per pixel, precomputed once.+ private val rayX = DoubleArray(w * h)+ private val rayY = DoubleArray(w * h)++ init {+ for (y in 0 until h) {+ for (x in 0 until w) {+ rayX[y * w + x] = (x - cx) / fx+ rayY[y * w + x] = (y - cy) / fy+ }+ }+ }++ /** World frame = first camera frame: X right, Y down, Z into the scene. */+ private data class Traj(val pos: (Double) -> Vec3, val euler: (Double) -> Triple<Double, Double, Double>)++ private fun smooth01(x: Double): Double {+ val t = x.coerceIn(0.0, 1.0)+ return t * t * (3 - 2 * t)+ }++ private fun scenarios(): List<Triple<String, Traj, Double>> {+ val still = Traj({ Vec3(0.0, 0.0, 0.0) }, { t -> Triple(0.002 * sin(2 * t), 0.0, 0.0) })+ val pan = Traj({ Vec3(0.0, 0.0, 0.0) }, { t -> Triple(0.0, 0.30 * sin(0.5 * t), 0.0) })+ val sideways = Traj(+ { t -> Vec3(0.85 * smooth01((t - 0.5) / 3.2), 0.01 * sin(3 * t), 0.0) },+ { t -> Triple(0.01 * sin(2 * t), 0.03 * sin(0.7 * t), 0.0) },+ )+ val forward = Traj(+ { t -> Vec3(0.01 * sin(2.5 * t), 0.008 * sin(3 * t), 0.85 * smooth01((t - 0.5) / 3.2)) },+ { t -> Triple(0.01 * sin(2 * t), 0.02 * sin(0.6 * t), 0.0) },+ )+ val fast = Traj(+ { t -> Vec3(1.3 * smooth01((t - 0.3) / 1.1), 0.02 * sin(5 * t), 0.0) },+ { t -> Triple(0.02 * sin(4 * t), 0.06 * sin(1.5 * t), 0.0) },+ )+ return listOf(+ Triple("static", still, 1.0),+ Triple("slow-pan", pan, 1.0),+ Triple("sideways", sideways, 1.0),+ Triple("forward", forward, 1.0),+ Triple("low-texture", sideways, 0.12),+ Triple("fast", fast, 1.0),+ )+ }++ private fun rotAt(traj: Traj, t: Double): DoubleArray {+ val (pitch, yaw, roll) = traj.euler(t)+ val cy = cos(yaw); val sy = sin(yaw)+ val cp = cos(pitch); val sp = sin(pitch)+ val cr = cos(roll); val sr = sin(roll)+ val ry = doubleArrayOf(cy, 0.0, sy, 0.0, 1.0, 0.0, -sy, 0.0, cy)+ val rx = doubleArrayOf(1.0, 0.0, 0.0, 0.0, cp, -sp, 0.0, sp, cp)+ val rz = doubleArrayOf(cr, -sr, 0.0, sr, cr, 0.0, 0.0, 0.0, 1.0)+ return mul(mul(ry, rx), rz)+ }++ private fun mul(a: DoubleArray, b: DoubleArray): DoubleArray {+ val out = DoubleArray(9)+ for (r in 0..2) for (c in 0..2) {+ out[r * 3 + c] = a[r * 3] * b[c] + a[r * 3 + 1] * b[3 + c] + a[r * 3 + 2] * b[6 + c]+ }+ return out+ }++ private fun transpose(r: DoubleArray) = doubleArrayOf(+ r[0], r[3], r[6], r[1], r[4], r[7], r[2], r[5], r[8],+ )++ private fun rotVec(r: DoubleArray, v: Vec3): Vec3 = Vec3(+ r[0] * v.x + r[1] * v.y + r[2] * v.z,+ r[3] * v.x + r[4] * v.y + r[5] * v.z,+ r[6] * v.x + r[7] * v.y + r[8] * v.z,+ )++ private fun rotVecT(r: DoubleArray, v: Vec3): Vec3 = Vec3(+ r[0] * v.x + r[3] * v.y + r[6] * v.z,+ r[1] * v.x + r[4] * v.y + r[7] * v.z,+ r[2] * v.x + r[5] * v.y + r[8] * v.z,+ )++ private fun render(r: DoubleArray, c: Vec3, contrast: Double, rnd: Random, gain: Double): ByteArray {+ val out = ByteArray(w * h)+ for (i in 0 until w * h) {+ val dir = rotVec(r, Vec3(rayX[i], rayY[i], 1.0))+ var bestT = Double.MAX_VALUE+ var value = 40.0+ // Front plane z = 3.+ if (dir.z > 1e-6) {+ val t = (3.0 - c.z) / dir.z+ if (t > 0.05 && t < bestT) {+ val px = c.x + dir.x * t+ val py = c.y + dir.y * t+ if (px in -6.0..6.0 && py in -4.5..4.5) {+ bestT = t+ value = sampleTex((px + 6) * 170.0, (py + 4.5) * 170.0, contrast)+ }+ }+ }+ // Floor plane y = 1.1 (below camera; Y is down).+ if (dir.y > 1e-6) {+ val t = (1.1 - c.y) / dir.y+ if (t > 0.05 && t < bestT) {+ val px = c.x + dir.x * t+ val pz = c.z + dir.z * t+ if (px in -6.0..6.0 && pz in -1.0..8.0) {+ bestT = t+ value = sampleTex((px + 6) * 170.0, pz * 170.0, contrast) * 0.85+ }+ }+ }+ val noisy = value * gain + (rnd.nextDouble() - 0.5) * 5.0+ out[i] = noisy.coerceIn(0.0, 255.0).toInt().toByte()+ }+ return out+ }++ /** Synthesize one IMU sample in Android device axes at time [t]. */+ private fun imuSample(traj: Traj, t: Double, rnd: Random): DoubleArray {+ val dt = 0.002+ val aWorld = Vec3(+ (traj.pos(t + dt).x - 2 * traj.pos(t).x + traj.pos(t - dt).x) / (dt * dt),+ (traj.pos(t + dt).y - 2 * traj.pos(t).y + traj.pos(t - dt).y) / (dt * dt),+ (traj.pos(t + dt).z - 2 * traj.pos(t).z + traj.pos(t - dt).z) / (dt * dt),+ )+ val r = rotAt(traj, t)+ // Specific force in world = a - g, g = (0, +9.81, 0) in Y-down world.+ val fWorld = Vec3(aWorld.x, aWorld.y - 9.81, aWorld.z)+ val fCam = rotVecT(r, fWorld)+ // Angular velocity in camera frame: skew part of R^T R(t+dt) ~ angle.+ val rel = mul(transpose(r), rotAt(traj, t + dt))+ val ang = Vec3((rel[7] - rel[5]) / 2, (rel[2] - rel[6]) / 2, (rel[3] - rel[1]) / 2)+ val gyro = Vec3(ang.x / dt, ang.y / dt, ang.z / dt)+ // Camera -> device axes: inverse of the engine's device->camera map+ // for rotation=90, M = [[0,-1,0],[-1,0,0],[0,0,-1]] (symmetric).+ fun camToDev(v: Vec3) = Vec3(-v.y, -v.x, -v.z)+ val fDev = camToDev(+ Vec3(+ fCam.x + 0.02 + (rnd.nextDouble() - 0.5) * 0.08,+ fCam.y - 0.015 + (rnd.nextDouble() - 0.5) * 0.08,+ fCam.z + 0.01 + (rnd.nextDouble() - 0.5) * 0.08,+ ),+ )+ val gDev = camToDev(+ Vec3(+ gyro.x + (rnd.nextDouble() - 0.5) * 0.002,+ gyro.y + (rnd.nextDouble() - 0.5) * 0.002,+ gyro.z + (rnd.nextDouble() - 0.5) * 0.002,+ ),+ )+ val tNs = (t * 1e9).toLong()+ return doubleArrayOf(+ tNs.toDouble(), gDev.x, gDev.y, gDev.z, fDev.x, fDev.y, fDev.z,+ )+ }++ @Test+ fun imuIntegratorMatchesGroundTruth() {+ val (_, traj, _) = scenarios()[2] // sideways+ val integrator = com.vayunmathur.measure.platform.vio.ImuIntegrator()+ val rnd = Random(7)+ // Feed samples in the *camera* frame here: the integrator sits+ // below the engine's device->camera rotation, so undo that map by+ // feeding cam-frame samples packed directly.+ var t = 0.0+ val batch = ArrayList<Double>()+ while (t <= 2.8) {+ val s = imuSample(traj, t, rnd)+ // imuSample returns device axes; rotate back to camera axes+ // (M is symmetric): cam = (-devY, -devX, -devZ) per axis group.+ val gx = -s[2]; val gy = -s[1]; val gz = -s[3]+ val ax = -s[5]; val ay = -s[4]; val az = -s[6]+ batch.addAll(listOf(s[0], gx, gy, gz, ax, ay, az))+ t += 0.005+ }+ integrator.push(batch.toDoubleArray())+ for ((a, b) in listOf(0.0 to 0.4, 0.0 to 0.9, 0.0 to 1.8, 0.0 to 2.8, 0.4 to 1.3, 1.3 to 2.2, 0.9 to 1.8)) {+ val est = integrator.displacementBetween((a * 1e9).toLong(), (b * 1e9).toLong())+ val gt = traj.pos(b) - traj.pos(a)+ println("imu window $a..$b est=$est gt=$gt")+ // Scale estimation consumes displacement magnitude along the+ // motion axis; perpendicular drift over a multi-second open+ // integration is expected without bias estimation. Assert+ // those two, not full-vector agreement.+ check(+ est != null && kotlin.math.abs(est.x - gt.x) < 0.03 &&+ kotlin.math.abs(+ sqrt(est.x * est.x + est.y * est.y + est.z * est.z) -+ sqrt(gt.x * gt.x + gt.y * gt.y + gt.z * gt.z),+ ) < 0.03,+ ) {+ "IMU displacement off: est=$est gt=$gt"+ }+ }+ }++ @Test+ fun syntheticPipelineMetrics() {+ val fps = 30.0+ val frames = 150+ val rows = mutableListOf<String>()+ var sidewaysScaleErr: Double? = null+ var forwardScaleErr: Double? = null+ var sidewaysLocked = false+ var forwardLocked = false++ for ((name, traj, contrast) in scenarios()) {+ val engine = VioEngine(Intrinsics(fx, fy, cx, cy, true), w, h, rotationDegrees = 90)+ val rnd = Random(7)+ var trackedSum = 0+ var lastResult: com.vayunmathur.measure.platform.vio.VioFrameResult? = null+ var imuCursor = 0.0+ for (f in 0 until frames) {+ val t = f / fps+ val batch = ArrayList<Double>()+ while (imuCursor <= t) {+ batch.addAll(imuSample(traj, imuCursor, rnd).toList())+ imuCursor += 0.005+ }+ if (batch.isNotEmpty()) {+ engine.pushImu(batch.toDoubleArray())+ }+ val frame = render(rotAt(traj, t), traj.pos(t), contrast, rnd, 1.0 + 0.03 * sin(t * 1.7))+ val result = engine.processFrame(frame, w, h, w, (t * 1e9).toLong())+ trackedSum += result.trackedFeatures+ lastResult = result+ }+ val res = lastResult!!+ val scale = engine.debugScale()+ val estPose = engine.debugPose()+ val gtC = traj.pos((frames - 1) / fps)+ val posErr = if (scale != null) {+ Vec3(estPose.t.x * scale, estPose.t.y * scale, estPose.t.z * scale).distanceTo(gtC)+ } else {+ Double.NaN+ }+ val hit = HitSelector.select(engine.centreCandidates(w, h))+ val rEnd = rotAt(traj, (frames - 1) / fps)+ val centreDir = rotVec(rEnd, Vec3(0.0, 0.0, 1.0))+ val gtDist = if (centreDir.z > 0.05) (3.0 - gtC.z) / centreDir.z else Double.NaN+ val scaleErr = if (hit != null && gtDist.isFinite()) hit.distanceM / gtDist - 1.0 else Double.NaN+ rows += String.format(+ "%-12s tracked=%5.1f landmarks=%3d quality=%-12s scaleConf=%.2f scale=%s " ++ "posErrM=%s hit=%s scaleErr=%s kf=%d tri=%d rej=%d reanchor=%d solves=%d",+ name,+ trackedSum.toDouble() / frames,+ res.landmarkCount,+ res.quality,+ res.scaleConfidence,+ scale?.let { String.format("%.3f", it) } ?: "null",+ if (posErr.isNaN()) " - " else String.format("%.3f", posErr),+ hit?.let { String.format("%.2fm", it.distanceM) } ?: "none",+ if (scaleErr.isNaN()) " - " else String.format("%+.1f%%", scaleErr * 100),+ engine.debugKeyframes,+ engine.debugTriangulated,+ engine.debugReprojRejected,+ engine.debugReanchors,+ engine.debugCentreSolves,+ )+ if (name == "sideways" || name == "forward") {+ println(+ "$name windows: " + engine.debugScaleWindows().joinToString(" ") {+ String.format("(v=%.3f,i=%.3f,r=%.3f)", it.first, it.second, it.second / it.first)+ } ++ " centreSolves=${engine.debugCentreSolves}/${engine.debugCentreAttempts}" ++ " estT=${engine.debugPose().t} gtT=$gtC",+ )+ }+ when (name) {+ "sideways" -> {+ sidewaysScaleErr = scaleErr+ sidewaysLocked = scale != null && res.landmarkCount >= 20+ }+ "forward" -> {+ forwardScaleErr = scaleErr+ forwardLocked = scale != null && res.landmarkCount >= 20+ }+ }+ engine.close()+ }++ println("=== Synthetic VIO harness (640x480, 150 frames @30fps, IMU 200Hz) ===")+ rows.forEach { println(it) }++ // Demonstrated bars (2026-11-17): the sideways-class scenarios lock+ // metric scale with a full landmark map. Forward/fast still do not+ // lock reliably, and locked-scale accuracy is ~10-50%, not the <3%+ // a measuring app ultimately needs: the remaining error is the+ // unit-translation bootstrap warp in the landmark map, which only+ // a real bundle adjustment (joint pose+landmark refinement) can+ // remove. Those numbers stay printed above as the follow-up's+ // baseline; do not weaken the printouts to hide them.+ check(sidewaysLocked) { "sideways: scale not locked or too few landmarks\n" + rows.joinToString("\n") }+ println(+ "scaleErr sideways=$sidewaysScaleErr forward=$forwardScaleErr " ++ "forwardLocked=$forwardLocked (target <3%: NOT yet met)",+ )+ }+}