measure: replace Rust VIO internals with an OpenCV tracker
- Commit
0008b7fc8c745c812421432e3aa989c6c800a003- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 03:47 UTC (19 days ago)
- Parents
2d20ff4
total redesign of the AR measurement engine. The owner tested the Rust monocular VIO build on device: it does not work. Rather than patch it again, its internals are replaced with OpenCV behind the Kotlin seams the previous redesign added, so the live AR UX (centre reticle, place/undo/close, per-segment + total + area readouts, typed ArFlow gating, ruler fallback) is unchanged. Pipeline (CameraX 640x480 Y-plane + IMU, single executor thread): - goodFeaturesToTrack (Shi-Tomasi, 220 corners) with cornerSubPix refinement (the Java binding quantises corners to integers), calcOpticalFlowPyrLK with a forward-backward check (1.5 px), findEssentialMat (RANSAC) + recoverPose for frame-to-frame motion, chained into a world pose via domain chainPose. - Keyframes on 24 px mean parallax; landmarks by DLT triangulation between keyframes (VioMath), filtered on 2 px reprojection error and de-duplicated; dominant plane by seeded RANSAC over landmarks, rejected unless horizontal/vertical against IMU gravity-up. - Metric scale from visual-inertial alignment: ImuIntegrator double-integrates gravity-removed accel over each keyframe window (near-zero edge velocity assumed — the hand-held case); the median IMU/visual displacement ratio with IQR confidence must reach 0.6 over 4+ windows before any distance is quoted. Everything visual stays scale-free until the lock; projection is scale-invariant, so only quoted numbers wait. Measurement layer survives intact: centre-reticle candidates are the triangulated landmarks (angle from image centre, metric distance) plus the plane intersection with an observed-extent check (inlier spread + 0.5 m), all selected by the existing HitSelector thresholds; anchors, MeasureMath segments/polyline/area, ArFlow states and the manual-tools fallback card are untouched concepts. Rust wiring is removed (measure_vio rustNativeLib + MeasureNative JNI bridge deleted; the crate source stays in the tree unreferenced — its only consumers were this flow). MeasureViewModel now holds the engine plus an injectable engineAvailable seam so flow tests can simulate a capable device; ArHitProvider gains OpenCvArHitProvider with the Fake provider unchanged for tests. Tests: ArFlow/HitSelector suites unchanged; ArFlowViewModelTest drives the real state machine against a stand-in engine; MainActivityAndAnalyzerTest covers the no-engine analyzer path; native-bridge tests replaced by VioMath ground-truth tests. Verified: :measure:compileDevKotlin, :measure:testDevUnitTest (141 tests) and :measure:lintDev all green. Device verification of tracking quality, scale-lock time and keyframe triangulation behaviour on the owner's Pixel 9 Pro remains — see the final report for parameters and honest accuracy limits.
Diff
measure/build.gradle.kts
diff --git a/measure/build.gradle.kts b/measure/build.gradle.ktsindex d663dc4c00..813896971d 100644--- a/measure/build.gradle.kts+++ b/measure/build.gradle.kts@@ -15,21 +15,15 @@ android { } } -androidComponents {- onVariants { variant ->- variant.sources.jniLibs?.addStaticSourceDirectory(- layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath- )- }-}--// Visual-inertial odometry engine (Rust). See measure/src/main/rust/.-rustNativeLib("measure_vio", "measure")-+// Visual-inertial tracking runs on OpenCV (org.opencv:opencv, Maven Central — see+// the catalog entry for provenance). The home-grown Rust `measure_vio` engine is no+// longer wired into the measurement flow: its crate stays in the tree at+// measure/src/main/rust/ for reference but is referenced by nothing. dependencies { implementation(libs.androidx.camera.core) implementation(libs.androidx.camera.camera2) implementation(libs.androidx.camera.lifecycle) implementation(libs.androidx.camera.compose) implementation(libs.androidx.datastore.preferences)+ implementation(libs.opencv) }
measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.kt b/measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.ktdeleted file mode 100644index 84b3c0cff0..0000000000--- a/measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.kt+++ /dev/null@@ -1,134 +0,0 @@-// PACKAGE STRUCTURE EXCEPTION (JNI): FQN frozen for native RegisterNatives/symbol mangling-package com.vayunmathur.measure.domain--/**- * JNI bridge to the Rust visual-inertial odometry engine (`measure/src/main/rust`).- *- * [available] guards every call: Compose previews, unit tests and any non-arm64 host- * have no `.so` to load, and the measure UI degrades to "AR unavailable" rather than- * crashing. Same pattern as the astronomy engine's native bridge.- */-object MeasureNative {-- val available: Boolean = runCatching { System.loadLibrary("measure_vio") }.isSuccess-- /** Quality codes mirroring the Rust `vio::Quality` discriminants. */- const val QUALITY_INITIALISING = 0- const val QUALITY_LIMITED = 1- const val QUALITY_GOOD = 2- const val QUALITY_LOST = 3-- /** Returns a session handle, or 0 on failure. */- fun createSession(fx: Double, fy: Double, cx: Double, cy: Double): Long =- if (!available) 0L else nativeCreateSession(fx, fy, cx, cy)-- fun destroySession(handle: Long) {- if (available && handle != 0L) nativeDestroySession(handle)- }-- fun reset(handle: Long) {- if (available && handle != 0L) nativeReset(handle)- }-- /**- * Feed one luminance plane. [rowStride] is passed through so the caller can hand- * over the CameraX `ImageProxy` Y plane without repacking it first.- */- fun pushFrame(- handle: Long,- yPlane: ByteArray,- width: Int,- height: Int,- rowStride: Int,- timestampNs: Long,- ): Int =- if (!available || handle == 0L) QUALITY_LOST- else nativePushFrame(handle, yPlane, width, height, rowStride, timestampNs)-- /**- * Push a batch of IMU samples packed as `[tNs, gx, gy, gz, ax, ay, az]` per sample.- * Batched because at 400 Hz per-sample JNI overhead would exceed the integration cost.- */- fun pushImu(handle: Long, packed: DoubleArray) {- if (available && handle != 0L && packed.isNotEmpty()) nativePushImu(handle, packed)- }-- /**- * Screen tap to metric world point: `[x, y, z, onPlane]`, or null while tracking- * has no metric scale yet.- */- fun rayToWorld(handle: Long, px: Float, py: Float): DoubleArray? {- if (!available || handle == 0L) return null- return nativeRayToWorld(handle, px, py)?.takeIf { it.size == 4 }- }-- /**- * All sane hit candidates along a screen ray, parsed from the flat- * native array. Selection policy ([HitSelector]) is applied by the- * caller so it stays unit-testable; empty when not measurable.- */- fun hitTest(handle: Long, px: Float, py: Float): List<HitCandidate> {- if (!available || handle == 0L) return emptyList()- val flat = nativeHitTest(handle, px, py) ?: return emptyList()- if (flat.size % HIT_CANDIDATE_STRIDE != 0) return emptyList()- return flat.toList().chunked(HIT_CANDIDATE_STRIDE).mapNotNull { c ->- val kind = when (c[0].toInt()) {- KIND_PLANE -> HitKind.Plane- KIND_FEATURE -> HitKind.FeaturePoint- else -> return@mapNotNull null- }- HitCandidate(- kind = kind,- position = Vec3(c[1], c[2], c[3]),- distanceM = c[4],- angularErrorDeg = c[5],- normalDotUp = c[6].takeIf { it >= 0.0 },- )- }- }-- private const val HIT_CANDIDATE_STRIDE = 7- private const val KIND_PLANE = 0- private const val KIND_FEATURE = 1-- /**- * `[quality, scaleConfidence, landmarkCount, trackedCount, hasPlane, gx, gy, gz]`,- * or null when the handle is unknown.- */- fun getState(handle: Long): DoubleArray? {- if (!available || handle == 0L) return null- return nativeGetState(handle)?.takeIf { it.size == 8 }- }-- /**- * Project metric world points to normalised screen coordinates.- * Input is a flat `[x, y, z]` array; output is `[nx, ny, visible]` per point.- */- fun projectPoints(handle: Long, world: DoubleArray, width: Double, height: Double): DoubleArray {- if (!available || handle == 0L || world.isEmpty()) return DoubleArray(0)- return nativeProjectPoints(handle, world, width, height) ?: DoubleArray(0)- }-- private external fun nativeCreateSession(fx: Double, fy: Double, cx: Double, cy: Double): Long- private external fun nativeDestroySession(handle: Long)- private external fun nativeReset(handle: Long)- private external fun nativePushFrame(- handle: Long,- yPlane: ByteArray,- width: Int,- height: Int,- rowStride: Int,- timestampNs: Long,- ): Int-- private external fun nativePushImu(handle: Long, packed: DoubleArray)- private external fun nativeRayToWorld(handle: Long, px: Float, py: Float): DoubleArray?- private external fun nativeHitTest(handle: Long, px: Float, py: Float): DoubleArray?- private external fun nativeGetState(handle: Long): DoubleArray?- private external fun nativeProjectPoints(- handle: Long,- world: DoubleArray,- width: Double,- height: Double,- ): DoubleArray?-}
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 57057022eb..282b5ef5dc 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt@@ -2,30 +2,32 @@ package com.vayunmathur.measure.platform import com.vayunmathur.measure.domain.HitCandidate import com.vayunmathur.measure.domain.HitSelector-import com.vayunmathur.measure.domain.MeasureNative+import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine /** * Seam between the AR flow and whatever produces hit candidates. *- * Production wraps the native VIO engine; tests and previews use- * [FakeArHitProvider]. Keeping candidate *selection* ([HitSelector])- * on this side of the seam is what makes the hit policy unit-testable- * without a device, a camera, or the `.so`.+ * Production wraps the OpenCV visual-inertial engine; tests and+ * previews use [FakeArHitProvider]. Keeping candidate *selection*+ * ([HitSelector]) on this side of the seam is what makes the hit+ * policy unit-testable without a device, a camera, or native code.+ * The [sessionHandle] argument is retained for the seam's shape; the+ * OpenCV provider resolves its engine directly and ignores it. */ interface ArHitProvider { /** The selected centre-reticle hit right now, or null. */ fun centreHit(sessionHandle: Long): HitCandidate? } -/** Production provider: native candidates through the shared selector. */-class NativeArHitProvider(- private val centrePx: () -> Pair<Float, Float>,+/** Production provider: OpenCV engine candidates through the shared selector. */+class OpenCvArHitProvider(+ private val engine: () -> OpenCvVioEngine?,+ private val analysisWidth: Int,+ private val analysisHeight: Int, ) : ArHitProvider { override fun centreHit(sessionHandle: Long): HitCandidate? {- if (sessionHandle == 0L) return null- val (px, py) = centrePx()- val candidates = MeasureNative.hitTest(sessionHandle, px, py)- return HitSelector.select(candidates)+ val eng = engine() ?: return null+ return HitSelector.select(eng.centreCandidates(analysisWidth, analysisHeight)) } }
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 fe795c3aee..d5cb28041a 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt@@ -4,11 +4,11 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.measure.data.model.Anchor import com.vayunmathur.measure.data.model.TrackingQuality import com.vayunmathur.measure.data.model.UnitSystem-import com.vayunmathur.measure.domain.MeasureNative import com.vayunmathur.measure.domain.areaIsTrustworthy import com.vayunmathur.measure.domain.lastSegmentLengthM import com.vayunmathur.measure.domain.polylineLengthM import com.vayunmathur.measure.domain.polygonArea+import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine import com.vayunmathur.measure.domain.polygonPerimeter import kotlinx.coroutines.launch @@ -187,7 +187,7 @@ internal fun MeasureViewModel.refreshFlowImpl(nowMs: Long = System.currentTimeMi // Camera permission outranks device-capability reasons: it is the // one the user can fix on the spot, after which the rest re-check. val unavailable = when {- !MeasureNative.available ->+ !engineAvailable -> com.vayunmathur.measure.domain.ArUnavailableReason.NativeEngineMissing !s.cameraPermissionGranted -> com.vayunmathur.measure.domain.ArUnavailableReason.CameraPermissionDenied@@ -195,7 +195,7 @@ internal fun MeasureViewModel.refreshFlowImpl(nowMs: Long = System.currentTimeMi } val flow = com.vayunmathur.measure.domain.ArFlow.derive( unavailable = unavailable,- hasSession = nativeSessionHandle != 0L && s.cameraPermissionGranted,+ hasSession = vioEngine != null && s.cameraPermissionGranted, quality = s.quality, reticleHit = s.reticleHit, scanningSinceMs = scanningSinceMs,@@ -212,9 +212,9 @@ internal fun MeasureViewModel.onReticleHitImpl( refreshFlowImpl() } -internal fun MeasureViewModel.onSessionChangedImpl(handle: Long) {- nativeSessionHandle = handle- if (handle == 0L) {+internal fun MeasureViewModel.onEngineChangedImpl(engine: OpenCvVioEngine?) {+ vioEngine = engine+ if (engine == null) { arState.value = arState.value.copy(reticleHit = null) } refreshFlowImpl()
measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.ktindex 97339ed609..288425da42 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt@@ -12,7 +12,7 @@ import com.vayunmathur.measure.data.model.SavedMeasurement import com.vayunmathur.measure.data.model.TrackingQuality import com.vayunmathur.measure.data.model.UnitSystem import com.vayunmathur.measure.data.model.distanceTo-import com.vayunmathur.measure.domain.MeasureNative+import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine import com.vayunmathur.measure.platform.sensor.ImuRecorder import com.vayunmathur.measure.platform.sensor.TiltSensor import com.vayunmathur.measure.domain.polygonArea@@ -57,8 +57,15 @@ class MeasureViewModel(app: Application) : AndroidViewModel(app), internal val diagnosticsState = MutableStateFlow(DiagnosticsUiState()) val diagnostics: StateFlow<DiagnosticsUiState> = diagnosticsState - /** Native VIO session handle, mirrored from the AR page so reset can reach it. */- internal var nativeSessionHandle: Long = 0L+ /** OpenCV engine, mirrored from the AR page so reset can reach it. */+ internal var vioEngine: OpenCvVioEngine? = null++ /**+ * Whether the tracking engine can run here. A seam (not a direct+ * static read) so flow tests can simulate a capable device:+ * native availability is false on every JVM test host.+ */+ internal var engineAvailable: Boolean = OpenCvVioEngine.available internal var scanningSinceMs: Long? = null internal var lostSinceMs: Long? = null@@ -138,7 +145,7 @@ class MeasureViewModel(app: Application) : AndroidViewModel(app), fun onReticleHit(hit: com.vayunmathur.measure.domain.HitCandidate?) = onReticleHitImpl(hit) - fun onSessionChanged(handle: Long) = onSessionChangedImpl(handle)+ fun onEngineChanged(engine: OpenCvVioEngine?) = onEngineChangedImpl(engine) fun setUnavailableReason(reason: com.vayunmathur.measure.domain.ArUnavailableReason?) { unavailableReason = reason@@ -150,7 +157,7 @@ class MeasureViewModel(app: Application) : AndroidViewModel(app), /** Poll the hit provider for the centre reticle and publish the result. */ fun refreshReticle() {- onReticleHit(hitProvider.centreHit(nativeSessionHandle))+ onReticleHit(hitProvider.centreHit(0L)) } override fun placeAtReticle() {@@ -212,8 +219,8 @@ class MeasureViewModel(app: Application) : AndroidViewModel(app), override fun resetTracking() { // Actually reset the engine, not just the UI: without this the // diagnostics Reset button cleared the anchor list while the- // native session kept its (possibly diverged) pose and map.- MeasureNative.reset(nativeSessionHandle)+ // engine kept its (possibly diverged) pose and map.+ vioEngine?.reset() clearAnchors() arState.value = arState.value.copy(quality = TrackingQuality.Initialising, hasPlane = false) }@@ -297,11 +304,3 @@ internal const val KEY_KEEP_SCREEN_ON = "measure_keep_screen_on" internal const val KEY_LEVEL_PITCH = "measure_level_pitch_offset" internal const val KEY_LEVEL_ROLL = "measure_level_roll_offset" internal const val KEY_LEVEL_EDGE = "measure_level_edge_offset"--/** Quality code from the native engine mapped onto the UI enum. */-fun trackingQualityFrom(code: Int): TrackingQuality = when (code) {- MeasureNative.QUALITY_LIMITED -> TrackingQuality.Limited- MeasureNative.QUALITY_GOOD -> TrackingQuality.Good- MeasureNative.QUALITY_LOST -> TrackingQuality.Lost- else -> TrackingQuality.Initialising-}
measure/src/main/java/com/vayunmathur/measure/platform/opencv/ImuIntegrator.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/opencv/ImuIntegrator.kt b/measure/src/main/java/com/vayunmathur/measure/platform/opencv/ImuIntegrator.ktnew file mode 100644index 0000000000..0fa0013dc5--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/platform/opencv/ImuIntegrator.kt@@ -0,0 +1,110 @@+package com.vayunmathur.measure.platform.opencv++import com.vayunmathur.measure.domain.Vec3+import com.vayunmathur.measure.domain.rotate3++/** 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)++/**+ * Short-window IMU displacement for visual-inertial scale alignment.+ *+ * 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.+ */+internal class ImuIntegrator {++ private val samples = ArrayList<ImuSample>()+ private var firstAccel: Vec3? = null++ /** 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)+ i += STRIDE+ }+ // Windows only ever look back a few seconds; cap the buffer.+ if (samples.size > MAX_SAMPLES) {+ samples.subList(0, samples.size - MAX_SAMPLES).clear()+ }+ }++ /** Mean accelerometer reading (camera frame), for gravity-up seeding. */+ fun meanAccelCam(): Vec3? {+ if (samples.isEmpty()) return firstAccel+ val n = samples.size+ return Vec3(+ samples.sumOf { it.ax } / n,+ samples.sumOf { it.ay } / n,+ samples.sumOf { it.az } / n,+ )+ }++ /**+ * 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.+ */+ 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+ }+ return Vec3(px, py, pz)+ }++ fun reset() {+ samples.clear()+ firstAccel = null+ }++ private companion object {+ const val GRAVITY = 9.81+ const val STRIDE = 7+ const val AX_OFFSET = 4+ const val AY_OFFSET = 5+ const val AZ_OFFSET = 6+ const val MAX_SAMPLES = 4000+ 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/opencv/OpenCvVioEngine.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/opencv/OpenCvVioEngine.kt b/measure/src/main/java/com/vayunmathur/measure/platform/opencv/OpenCvVioEngine.ktnew file mode 100644index 0000000000..ab6bdb8630--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/platform/opencv/OpenCvVioEngine.kt@@ -0,0 +1,545 @@+package com.vayunmathur.measure.platform.opencv++import com.vayunmathur.measure.data.model.TrackingQuality+import com.vayunmathur.measure.domain.FittedPlane+import com.vayunmathur.measure.domain.HitCandidate+import com.vayunmathur.measure.domain.HitKind+import com.vayunmathur.measure.domain.Pose3+import com.vayunmathur.measure.domain.Vec3+import com.vayunmathur.measure.domain.chainPose+import com.vayunmathur.measure.domain.estimateScale+import com.vayunmathur.measure.domain.gravityClass+import com.vayunmathur.measure.domain.PlaneClass+import com.vayunmathur.measure.domain.projectionMatrix+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.triangulate+import com.vayunmathur.measure.platform.Intrinsics+import kotlin.math.abs+import kotlin.math.atan2+import kotlin.math.sqrt+import org.opencv.android.OpenCVLoader+import org.opencv.calib3d.Calib3d+import org.opencv.core.CvType+import org.opencv.core.Mat+import org.opencv.core.MatOfByte+import org.opencv.core.MatOfFloat+import org.opencv.core.MatOfPoint2f+import org.opencv.core.Point+import org.opencv.core.Size+import org.opencv.core.TermCriteria+import org.opencv.imgproc.Imgproc+import org.opencv.video.Video++/** Per-frame result the analyzer forwards to the ViewModel. */+data class VioFrameResult(+ val quality: TrackingQuality,+ val hasPlane: Boolean,+ val trackedFeatures: Int,+ val landmarkCount: Int,+ val scaleConfidence: Double,+)++/** One triangulated landmark, in visual (scale-free) world units. */+private data class Landmark(val position: Vec3, var observations: Int)++/**+ * OpenCV visual-inertial tracker behind the AR measurement flow.+ *+ * Pipeline per analysis frame (all on the camera executor thread):+ * Shi-Tomasi corners (`goodFeaturesToTrack`) tracked with pyramidal+ * Lucas-Kanade (`calcOpticalFlowPyrLK`) and a forward-backward+ * consistency check; frame-to-frame motion from+ * `findEssentialMat` + `recoverPose`, chained into a world pose;+ * landmarks by DLT triangulation between keyframes (reprojection and+ * parallax filtered, math in `domain/VioMath`); the dominant surface+ * by RANSAC plane fit; and metric scale by aligning visual+ * displacements with double-integrated IMU displacement windows.+ *+ * Everything visual lives in scale-free units until the IMU scale+ * locks — projection is scale-invariant, so only quoted distances+ * wait for the lock, mirroring the old engine's "no metric scale, no+ * measurements" rule. All OpenCV handles are released per frame; a+ * missing native library degrades [available] to false and the UI+ * falls back to the manual tools instead of crashing.+ */+class OpenCvVioEngine(private val intrinsics: Intrinsics) {++ companion object {+ /** True when the OpenCV native library loaded on this device/host. */+ val available: Boolean by lazy {+ runCatching { OpenCVLoader.initDebug() }.getOrDefault(false)+ }++ private const val VALUES_PER_POINT = 3+ private const val MAX_CORNERS = 220+ 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 MAX_REPROJECTION_PX = 2.0+ private const val FB_ERROR_PX = 1.5+ private const val SCALE_CONFIDENCE_MIN = 0.6+ private const val SCALE_WINDOWS_MIN = 4+ private const val MAX_LANDMARKS = 400+ private const val LOST_AFTER_FAILURES = 3+ private const val PLANE_EXTENT_MARGIN_M = 0.5+ }++ private val cameraMatrix = doubleArrayOf(+ intrinsics.fx, 0.0, intrinsics.cx,+ 0.0, intrinsics.fy, intrinsics.cy,+ 0.0, 0.0, 1.0,+ )++ private var prevGray: Mat? = null+ private var prevPoints: List<Point> = emptyList()+ private var worldFromCam: Pose3 = Pose3.identity()+ private var keyframePose: Pose3? = null+ private var keyframePoints: List<Point> = emptyList()+ private var keyframeTimeNs: Long = 0L++ private val landmarks = ArrayList<Landmark>()+ private var plane: FittedPlane? = null+ private var planeExtentM: Double = 0.0++ private var scale: Double? = null+ private var scaleConfidence: Double = 0.0+ private val visualWindows = ArrayList<Vec3>()+ private val imuWindows = ArrayList<Vec3>()+ private var lastKeyframeCentre: Vec3? = null++ /** Gravity-up in world coordinates, seeded from the first accelerometer window. */+ private var worldUp: Vec3 = Vec3(0.0, 1.0, 0.0)+ private var upSeeded = false++ private val imu = ImuIntegrator()+ private var consecutiveFailures = 0+ private var framesSeen = 0++ @Volatile private var lastQuality: TrackingQuality = TrackingQuality.Initialising++ /** Feed the packed IMU batch (`[tNs, gx, gy, gz, ax, ay, az]` per sample). */+ fun pushImu(packed: DoubleArray) {+ imu.push(packed)+ if (!upSeeded) {+ imu.meanAccelCam()?.let { a ->+ val len = sqrt(a.x * a.x + a.y * a.y + a.z * a.z)+ if (len > 1.0) {+ // Accelerometer reads gravity reaction: up is -a, in the+ // first camera frame, which is the world frame by fiat.+ worldUp = Vec3(-a.x / len, -a.y / len, -a.z / len)+ upSeeded = true+ }+ }+ }+ }++ fun processFrame(+ yPlane: ByteArray,+ width: Int,+ height: Int,+ rowStride: Int,+ timestampNs: Long,+ ): VioFrameResult {+ framesSeen+++ val gray = grayMat(yPlane, width, height, rowStride)+ try {+ val prev = prevGray ?: return firstFrame(gray)+ val tracked = track(prev, gray, prevPoints)+ if (tracked == null || tracked.first.size < MIN_TRACKED_FOR_POSE) {+ return trackingFailure(gray, tracked?.first?.size ?: 0)+ }+ val (prevPts, currPts) = tracked+ val rel = recoverRelative(prevPts, currPts)+ if (rel == null) return poseFailure(gray, currPts)+ consecutiveFailures = 0+ worldFromCam = chainPose(worldFromCam, rel)+ updateKeyframes(prevPts, currPts, timestampNs)+ // Top features back up so slow attrition never starves the tracker.+ prevPoints = if (currPts.size < MAX_CORNERS / 2) {+ mergePoints(currPts, detect(gray))+ } else {+ currPts+ }+ prevGray?.release()+ prevGray = gray.clone()+ val q = when {+ scale == null -> TrackingQuality.Initialising+ currPts.size >= GOOD_TRACKED && landmarks.size >= GOOD_LANDMARKS ->+ TrackingQuality.Good+ else -> TrackingQuality.Limited+ }+ return result(q, currPts.size)+ } finally {+ gray.release()+ }+ }++ private fun firstFrame(gray: Mat): VioFrameResult {+ prevPoints = detect(gray)+ prevGray = gray.clone()+ return result(TrackingQuality.Initialising, prevPoints.size)+ }++ private fun trackingFailure(gray: Mat, trackedCount: Int): VioFrameResult {+ consecutiveFailures+++ prevPoints = detect(gray)+ prevGray?.release()+ prevGray = gray.clone()+ val q = when {+ consecutiveFailures >= LOST_AFTER_FAILURES -> TrackingQuality.Lost+ framesSeen < 30 -> TrackingQuality.Initialising+ else -> TrackingQuality.Limited+ }+ return result(q, trackedCount)+ }++ private fun poseFailure(gray: Mat, currPts: List<Point>): VioFrameResult {+ consecutiveFailures+++ prevPoints = currPts+ prevGray?.release()+ prevGray = gray.clone()+ return result(+ if (consecutiveFailures >= LOST_AFTER_FAILURES) {+ TrackingQuality.Lost+ } else {+ TrackingQuality.Limited+ },+ currPts.size,+ )+ }++ private fun updateKeyframes(prevPts: List<Point>, currPts: List<Point>, 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)+ }+ }++ private fun result(quality: TrackingQuality, tracked: Int): VioFrameResult {+ lastQuality = quality+ return VioFrameResult(+ quality = quality,+ hasPlane = plane != null,+ trackedFeatures = tracked,+ landmarkCount = landmarks.size,+ scaleConfidence = scaleConfidence,+ )+ }++ /** Centre-ray hit candidates: landmarks plus the fitted-plane intersection. */+ fun centreCandidates(width: Int, height: Int): List<HitCandidate> {+ val s = scale ?: return emptyList()+ val p = currentProjection()+ val centre = (width / 2.0) to (height / 2.0)+ val camCentre = worldFromCam.t+ val out = ArrayList<HitCandidate>()+ for (lm in landmarks) {+ val uv = project(p, lm.position) ?: continue+ val du = uv.first - centre.first+ val dv = uv.second - centre.second+ val angleDeg = Math.toDegrees(atan2(sqrt(du * du + dv * dv), intrinsics.fx))+ val distVisual = camCentre.distanceTo(lm.position)+ out += HitCandidate(+ kind = HitKind.FeaturePoint,+ position = lm.position * s,+ distanceM = distVisual * s,+ angularErrorDeg = angleDeg,+ )+ }+ plane?.let { pl ->+ val dir = centreRayWorld()+ val hit = pl.intersectRay(camCentre, dir) ?: return@let+ // Extent check: the infinite plane is not the surface. Only+ // hits near the observed inlier cloud may be placed on.+ if (hit.distanceTo(pl.point) <= planeExtentM) {+ out += HitCandidate(+ kind = HitKind.Plane,+ position = hit * s,+ distanceM = camCentre.distanceTo(hit) * s,+ angularErrorDeg = 0.0,+ normalDotUp = abs(+ pl.normal.x * worldUp.x + pl.normal.y * worldUp.y ++ pl.normal.z * worldUp.z,+ ),+ )+ }+ }+ return out+ }++ /**+ * Project metric world points to normalised screen coordinates+ * (`[nx, ny, visible]` per point), the contract the overlay has+ * always consumed. [width]/[height] are analysis-stream pixels.+ */+ fun projectPoints(world: DoubleArray, width: Double, height: Double): DoubleArray {+ if (world.isEmpty()) return DoubleArray(0)+ val s = scale ?: return DoubleArray(world.size / 3 * 3)+ val p = currentProjection()+ val out = DoubleArray((world.size / 3) * 3)+ for (i in 0 until world.size / 3) {+ val visual = Vec3(world[i * 3] / s, world[i * 3 + 1] / s, world[i * 3 + 2] / s)+ val uv = project(p, visual)+ out[i * 3] = (uv?.first ?: 0.0) / width+ out[i * 3 + 1] = (uv?.second ?: 0.0) / height+ out[i * 3 + 2] = if (uv != null) 1.0 else 0.0+ }+ return out+ }++ fun reset() {+ prevGray?.release()+ prevGray = null+ prevPoints = emptyList()+ worldFromCam = Pose3.identity()+ keyframePose = null+ keyframePoints = emptyList()+ landmarks.clear()+ plane = null+ planeExtentM = 0.0+ scale = null+ scaleConfidence = 0.0+ visualWindows.clear()+ imuWindows.clear()+ lastKeyframeCentre = null+ imu.reset()+ consecutiveFailures = 0+ framesSeen = 0+ lastQuality = TrackingQuality.Initialising+ }++ fun close() {+ prevGray?.release()+ prevGray = null+ }++ // -- OpenCV stages -------------------------------------------------++ private fun grayMat(yPlane: ByteArray, width: Int, height: Int, rowStride: Int): Mat {+ val mat = Mat(height, width, CvType.CV_8UC1)+ if (rowStride == width) {+ mat.put(0, 0, yPlane, 0, width * height)+ } else {+ val row = ByteArray(width)+ for (r in 0 until height) {+ System.arraycopy(yPlane, r * rowStride, row, 0, width)+ mat.put(r, 0, row)+ }+ }+ return mat+ }++ private fun detect(gray: Mat): List<Point> {+ val corners = org.opencv.core.MatOfPoint()+ try {+ Imgproc.goodFeaturesToTrack(+ gray, corners, MAX_CORNERS, 0.01, 10.0, Mat(), 3, false, 0.04,+ )+ val rough = corners.toList()+ if (rough.isEmpty()) return emptyList()+ // The Java binding returns integer-quantised corners; refine+ // to sub-pixel before LK seeds from them.+ val refined = MatOfPoint2f(*rough.toTypedArray())+ try {+ Imgproc.cornerSubPix(+ gray, refined, Size(5.0, 5.0), Size(-1.0, -1.0),+ TermCriteria(TermCriteria.EPS or TermCriteria.COUNT, 30, 0.01),+ )+ return refined.toList()+ } finally {+ refined.release()+ }+ } finally {+ corners.release()+ }+ }++ /** LK tracking with forward-backward check; returns (prev, curr) survivors. */+ private fun track(prev: Mat, curr: Mat, points: List<Point>): Pair<List<Point>, List<Point>>? {+ if (points.isEmpty()) return null+ val prevMat = MatOfPoint2f(*points.toTypedArray())+ val currMat = MatOfPoint2f()+ val backMat = MatOfPoint2f()+ val status = MatOfByte()+ val err = MatOfFloat()+ val backStatus = MatOfByte()+ val backErr = MatOfFloat()+ val criteria = TermCriteria(TermCriteria.EPS or TermCriteria.COUNT, 30, 0.01)+ try {+ Video.calcOpticalFlowPyrLK(+ prev, curr, prevMat, currMat, status, err, Size(21.0, 21.0), 3, criteria,+ )+ Video.calcOpticalFlowPyrLK(+ curr, prev, currMat, backMat, backStatus, backErr, Size(21.0, 21.0), 3, criteria,+ )+ val st = status.toArray()+ val bst = backStatus.toArray()+ val currList = currMat.toList()+ val backList = backMat.toList()+ val outPrev = ArrayList<Point>()+ val outCurr = ArrayList<Point>()+ for (i in points.indices) {+ if (st[i].toInt() == 0 || bst[i].toInt() == 0) continue+ val fb = points[i].distanceTo(backList[i])+ if (fb > FB_ERROR_PX) continue+ outPrev += points[i]+ outCurr += currList[i]+ }+ return outPrev to outCurr+ } catch (e: org.opencv.core.CvException) {+ return null+ } finally {+ prevMat.release(); currMat.release(); backMat.release()+ status.release(); err.release(); backStatus.release(); backErr.release()+ }+ }++ /** Essential-matrix relative pose (A -> B), or null when degenerate. */+ private fun recoverRelative(prevPts: List<Point>, currPts: List<Point>): Pose3? {+ val k = Mat(3, 3, CvType.CV_64F)+ val p1 = MatOfPoint2f(*prevPts.toTypedArray())+ val p2 = MatOfPoint2f(*currPts.toTypedArray())+ val r = Mat()+ val t = Mat()+ val mask = Mat()+ try {+ k.put(0, 0, *cameraMatrix)+ val e = Calib3d.findEssentialMat(p1, p2, k, Calib3d.RANSAC, 0.999, 1.0)+ if (e.empty()) {+ e.release()+ return null+ }+ val inliers = Calib3d.recoverPose(e, p1, p2, k, r, t, mask)+ e.release()+ if (inliers < MIN_TRACKED_FOR_POSE || r.empty() || t.empty()) return null+ val rd = DoubleArray(9)+ r.get(0, 0, rd)+ val td = DoubleArray(3)+ t.get(0, 0, td)+ val tn = sqrt(td[0] * td[0] + td[1] * td[1] + td[2] * td[2])+ if (tn < 1e-9) return null+ // recoverPose translation is unit-length by construction.+ return Pose3(rd, Vec3(td[0] / tn, td[1] / tn, td[2] / tn))+ } catch (e: org.opencv.core.CvException) {+ return null+ } finally {+ k.release(); p1.release(); p2.release(); r.release(); t.release(); mask.release()+ }+ }++ private fun onKeyframe(prevKfPose: Pose3, currPts: List<Point>, 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)+ var added = 0+ for (i in 0 until pairs) {+ val a = kfPoints[i].x to kfPoints[i].y+ val b = currPts[i].x to currPts[i].y+ val world = triangulate(pa, a, pb, b) ?: continue+ val errA = reprojectionErrorPx(pa, world, a)+ val errB = reprojectionErrorPx(pb, world, b)+ if (errA > MAX_REPROJECTION_PX || errB > MAX_REPROJECTION_PX) continue+ if (landmarks.any { it.position.distanceTo(world) < 0.01 }) continue+ landmarks += Landmark(world, observations = 2)+ added+++ }+ if (landmarks.size > MAX_LANDMARKS) {+ landmarks.subList(0, landmarks.size - MAX_LANDMARKS).clear()+ }+ if (added > 0) refitPlane()+ updateScaleWindows(timestampNs)+ }+ }++ private fun setKeyframe(points: List<Point>, timestampNs: Long) {+ keyframePose = worldFromCam+ keyframePoints = points+ keyframeTimeNs = timestampNs+ lastKeyframeCentre = worldFromCam.t+ }++ private fun updateScaleWindows(timestampNs: Long) {+ val centre = worldFromCam.t+ val last = lastKeyframeCentre ?: return+ val visual = centre - last+ val imuDisp = imu.displacementBetween(+ keyframeTimeNs, timestampNs, worldFromCam.r, worldUp,+ )+ if (imuDisp != null) {+ visualWindows += visual+ imuWindows += imuDisp+ if (visualWindows.size > 12) {+ visualWindows.removeAt(0)+ imuWindows.removeAt(0)+ }+ estimateScale(visualWindows, imuWindows)?.let { est ->+ scaleConfidence = est.confidence+ if (est.pairs >= SCALE_WINDOWS_MIN && est.confidence >= SCALE_CONFIDENCE_MIN) {+ scale = est.scale+ }+ }+ }+ lastKeyframeCentre = centre+ }++ private fun refitPlane() {+ if (landmarks.size < 12) return+ val fitted = ransacPlane(landmarks.map { it.position }) ?: return+ val (pl, inliers) = fitted+ if (gravityClass(pl.normal, worldUp) == PlaneClass.Slanted) return+ plane = pl+ // Observed extent: farthest inlier from the centroid, plus slack.+ planeExtentM = inliers.maxOfOrNull { it.distanceTo(pl.point) }+ ?.plus(PLANE_EXTENT_MARGIN_M) ?: 0.0+ }++ private fun currentProjection(): DoubleArray =+ projectionMatrix(cameraMatrix, worldFromCam)++ /** World-space direction of the centre-pixel ray. */+ private fun centreRayWorld(): Vec3 {+ // The centre pixel back-projects onto the optical axis, so the+ // camera-space ray is +Z; rotate it into the world frame.+ val camDir = Vec3(0.0, 0.0, 1.0)+ val worldDir = rotate3(worldFromCam.r, camDir)+ val len = sqrt(worldDir.x * worldDir.x + worldDir.y * worldDir.y + worldDir.z * worldDir.z)+ return Vec3(worldDir.x / len, worldDir.y / len, worldDir.z / len)+ }++ private fun meanFlow(a: List<Point>, b: List<Point>): 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 fun mergePoints(tracked: List<Point>, fresh: List<Point>): List<Point> {+ val out = ArrayList(tracked)+ for (p in fresh) {+ if (out.any { it.distanceTo(p) < 10.0 }) continue+ out += p+ if (out.size >= MAX_CORNERS) break+ }+ return out+ }+}++private operator fun Vec3.times(s: Double): Vec3 = Vec3(x * s, y * s, z * s)+private fun Point.distanceTo(other: Point): Double {+ val dx = x - other.x+ val dy = y - other.y+ return sqrt(dx * dx + dy * dy)+}
measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.kt b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.ktindex bfa5bfcc52..d5e9ce5c80 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.kt@@ -30,7 +30,6 @@ import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.measure.data.model.TrackingQuality import com.vayunmathur.measure.domain.ArFlowState import com.vayunmathur.measure.domain.ArUnavailableReason-import com.vayunmathur.measure.domain.MeasureNative import com.vayunmathur.measure.domain.Units import com.vayunmathur.measure.platform.ArMeasureActions import com.vayunmathur.measure.platform.ArMeasureUiState@@ -62,10 +61,6 @@ fun ArMeasureContent( UnavailableNotice(unavailableMessage(unavailableReason), onOpenRuler) return@Box }- !MeasureNative.available -> {- UnavailableNotice(stringResource(R.string.ar_unavailable_native), onOpenRuler)- return@Box- } !state.cameraPermissionGranted -> { UnavailableNotice(stringResource(R.string.ar_unavailable_camera), onOpenRuler) return@Box
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 12f768eae8..26eb4b0cc9 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt@@ -9,7 +9,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue@@ -23,11 +22,10 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.ui.rememberPermissionRequest import com.vayunmathur.measure.Route import com.vayunmathur.measure.domain.ArUnavailableReason-import com.vayunmathur.measure.domain.MeasureNative+import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine import com.vayunmathur.measure.platform.CameraIntrinsicsResolver import com.vayunmathur.measure.platform.MeasureViewModel-import com.vayunmathur.measure.platform.NativeArHitProvider-import com.vayunmathur.measure.platform.trackingQualityFrom+import com.vayunmathur.measure.platform.OpenCvArHitProvider import com.vayunmathur.measure.platform.updateDiagnosticsImpl import com.vayunmathur.measure.ui.components.MeasureBottomBar import com.vayunmathur.measure.ui.components.ANALYSIS_SIZE@@ -37,7 +35,7 @@ import kotlinx.coroutines.delay @Composable fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { val state by viewModel.ar.collectAsState()- var sessionHandle by remember { mutableLongStateOf(0L) }+ var engine by remember { mutableStateOf<OpenCvVioEngine?>(null) } var screenPoints by remember { mutableStateOf<List<Offset?>>(emptyList()) } var canvasSize by remember { mutableStateOf(Size.Zero) } val context = LocalContext.current@@ -49,17 +47,19 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { // would otherwise coach "move your phone" forever (the old flow // never called timestampsAlignWithSensors at all). LaunchedEffect(Unit) {- viewModel.hitProvider = NativeArHitProvider {- (ANALYSIS_SIZE.width / 2f) to (ANALYSIS_SIZE.height / 2f)- }+ viewModel.hitProvider = OpenCvArHitProvider(+ engine = { engine },+ analysisWidth = ANALYSIS_SIZE.width,+ analysisHeight = ANALYSIS_SIZE.height,+ ) viewModel.setUnavailableReason(availabilityReason(context)) } // Continuous centre-reticle hit test: the reticle, not the finger, // is the placement point, and it must snap to the best sane hit // every frame rather than resolving one raw ray at tap instant.- LaunchedEffect(sessionHandle) {- if (sessionHandle == 0L) return@LaunchedEffect+ LaunchedEffect(engine) {+ if (engine == null) return@LaunchedEffect while (true) { viewModel.refreshReticle() delay(RETICLE_INTERVAL_MS)@@ -68,7 +68,8 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { // Reproject anchors whenever the anchor set or the pose changes. LaunchedEffect(state.anchors, state.quality, canvasSize) {- if (sessionHandle == 0L || canvasSize == Size.Zero || state.anchors.isEmpty()) {+ val eng = engine+ if (eng == null || canvasSize == Size.Zero || state.anchors.isEmpty()) { screenPoints = emptyList() return@LaunchedEffect }@@ -82,8 +83,7 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { // The engine projects with analysis-stream intrinsics and // normalises by the size it is given, so it must be given the // analysis size, not the canvas size.- val projected = MeasureNative.projectPoints(- sessionHandle,+ val projected = eng.projectPoints( flat, ANALYSIS_SIZE.width.toDouble(), ANALYSIS_SIZE.height.toDouble(),@@ -108,15 +108,15 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { screenPoints = screenPoints, onCanvasSized = { canvasSize = it }, cameraContent = {- if (cameraGranted && MeasureNative.available) {+ if (cameraGranted && OpenCvVioEngine.available) { MeasureCamera( imuRecorder = viewModel.imuRecorder, onTrackingUpdate = { q, hasPlane ->- viewModel.onTrackingUpdate(trackingQualityFrom(q), hasPlane)+ viewModel.onTrackingUpdate(q, hasPlane) },- onSessionReady = {- sessionHandle = it- viewModel.onSessionChanged(it)+ onEngineReady = {+ engine = it+ viewModel.onEngineChanged(it) }, onDiagnostics = { fps, skew, imuHz, tracked, landmarks, confidence -> viewModel.updateDiagnosticsImpl {@@ -128,7 +128,7 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { featureCount = tracked, landmarkCount = landmarks, scaleConfidence = confidence,- nativeEngineAvailable = MeasureNative.available,+ nativeEngineAvailable = OpenCvVioEngine.available, ) } },@@ -144,7 +144,7 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { /** Explicit availability states, checked once before the session starts. */ private fun availabilityReason(context: Context): ArUnavailableReason? {- if (!MeasureNative.available) return ArUnavailableReason.NativeEngineMissing+ if (!OpenCvVioEngine.available) return ArUnavailableReason.NativeEngineMissing val sensors = context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager ?: return ArUnavailableReason.MotionSensorsMissing val hasGyro = sensors.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED) != null ||
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 cb99136a1c..1abaaedc8d 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@@ -23,8 +23,9 @@ import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.repeatOnLifecycle-import com.vayunmathur.measure.domain.MeasureNative+import com.vayunmathur.measure.data.model.TrackingQuality import com.vayunmathur.measure.platform.CameraIntrinsicsResolver+import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine import com.vayunmathur.measure.platform.sensor.ImuRecorder import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow@@ -40,17 +41,18 @@ typealias Diagnostics = (Double, Double, Double, Int, Int, Double) -> Unit internal val ANALYSIS_SIZE = Size(640, 480) /**- * Camera viewfinder plus the frame pump that drives the VIO engine.+ * Camera viewfinder plus the frame pump that drives the OpenCV tracker. *- * The analyser hands the Y plane straight to JNI. No Bitmap is allocated and no colour- * conversion happens: tracking only needs luminance, and an RGB conversion every frame- * would dominate the pipeline's cost.+ * The analyser hands the Y plane straight to the engine. No Bitmap is+ * allocated and no colour conversion happens: tracking only needs+ * luminance, and an RGB conversion every frame would dominate the+ * pipeline's cost. */ @Composable fun MeasureCamera( imuRecorder: ImuRecorder,- onTrackingUpdate: (quality: Int, hasPlane: Boolean) -> Unit,- onSessionReady: (handle: Long) -> Unit,+ onTrackingUpdate: (quality: TrackingQuality, hasPlane: Boolean) -> Unit,+ onEngineReady: (engine: OpenCvVioEngine?) -> Unit, modifier: Modifier = Modifier, onDiagnostics: Diagnostics = { _, _, _, _, _, _ -> }, ) {@@ -63,8 +65,8 @@ fun MeasureCamera( lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { val executor = Executors.newSingleThreadExecutor() var provider: ProcessCameraProvider? = null- val handle = createSession(context)- onSessionReady(handle)+ val engine = createEngine(context)+ onEngineReady(engine) try { provider = ProcessCameraProvider.awaitInstance(context) provider.unbindAll()@@ -91,7 +93,7 @@ fun MeasureCamera( .also { it.setAnalyzer( executor,- VioFrameAnalyzer(handle, imuRecorder, onTrackingUpdate, onDiagnostics),+ OpenCvFrameAnalyzer(engine, imuRecorder, onTrackingUpdate, onDiagnostics), ) } @@ -107,9 +109,9 @@ fun MeasureCamera( imuRecorder.stop() provider?.unbindAll() executor.shutdown()- MeasureNative.destroySession(handle)+ engine?.close() surfaceRequest.value = null- onSessionReady(0L)+ onEngineReady(null) } } }@@ -119,15 +121,16 @@ fun MeasureCamera( } } -private fun createSession(context: Context): Long {- val intr = CameraIntrinsicsResolver.resolve(context, ANALYSIS_SIZE) ?: return 0L- return MeasureNative.createSession(intr.fx, intr.fy, intr.cx, intr.cy)+private fun createEngine(context: Context): OpenCvVioEngine? {+ if (!OpenCvVioEngine.available) return null+ val intr = CameraIntrinsicsResolver.resolve(context, ANALYSIS_SIZE) ?: return null+ return OpenCvVioEngine(intr) } -internal class VioFrameAnalyzer(- private val handle: Long,+internal class OpenCvFrameAnalyzer(+ private val engine: OpenCvVioEngine?, private val imuRecorder: ImuRecorder,- private val onTrackingUpdate: (Int, Boolean) -> Unit,+ private val onTrackingUpdate: (TrackingQuality, Boolean) -> Unit, private val onDiagnostics: Diagnostics, ) : ImageAnalysis.Analyzer { @@ -137,12 +140,12 @@ internal class VioFrameAnalyzer( override fun analyze(image: ImageProxy) { try {- if (handle == 0L) return+ val eng = engine ?: return // Drain IMU first so every sample older than this frame is already queued,- // which is what lets the engine preintegrate over the correct interval.+ // which is what lets the engine align its scale windows. val imu = imuRecorder.drain()- if (imu.isNotEmpty()) MeasureNative.pushImu(handle, imu)+ if (imu.isNotEmpty()) eng.pushImu(imu) val plane = image.planes[0] val src = plane.buffer@@ -151,18 +154,14 @@ internal class VioFrameAnalyzer( src.get(dst, 0, needed) val tNs = image.imageInfo.timestamp- val quality = MeasureNative.pushFrame(- handle = handle,+ val result = eng.processFrame( yPlane = dst, width = image.width, height = image.height, rowStride = plane.rowStride, timestampNs = tNs, )-- val state = MeasureNative.getState(handle)- val hasPlane = state != null && state[4] > 0.5- onTrackingUpdate(quality, hasPlane)+ onTrackingUpdate(result.quality, result.hasPlane) if (lastFrameNs != 0L) { frameIntervalNs = (frameIntervalNs * 3 + (tNs - lastFrameNs)) / 4@@ -177,9 +176,9 @@ internal class VioFrameAnalyzer( fps, skewMs, imuRecorder.rateHz(),- state?.get(3)?.toInt() ?: 0,- state?.get(2)?.toInt() ?: 0,- state?.get(1) ?: 0.0,+ result.trackedFeatures,+ result.landmarkCount,+ result.scaleConfidence, ) } finally { image.close()
measure/src/test/java/com/vayunmathur/measure/MainActivityAndAnalyzerTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/MainActivityAndAnalyzerTest.kt b/measure/src/test/java/com/vayunmathur/measure/MainActivityAndAnalyzerTest.ktindex 9744310bb8..f48972c4e1 100644--- a/measure/src/test/java/com/vayunmathur/measure/MainActivityAndAnalyzerTest.kt+++ b/measure/src/test/java/com/vayunmathur/measure/MainActivityAndAnalyzerTest.kt@@ -9,10 +9,9 @@ import androidx.camera.core.impl.TagBundle import androidx.camera.core.impl.utils.ExifData import androidx.test.core.app.ApplicationProvider import com.vayunmathur.measure.data.model.TrackingQuality-import com.vayunmathur.measure.domain.MeasureNative import com.vayunmathur.measure.platform.MeasureViewModel import com.vayunmathur.measure.platform.sensor.ImuRecorder-import com.vayunmathur.measure.ui.components.VioFrameAnalyzer+import com.vayunmathur.measure.ui.components.OpenCvFrameAnalyzer import java.nio.ByteBuffer import kotlin.test.Test import kotlin.test.assertEquals@@ -67,55 +66,29 @@ class MainActivityAndAnalyzerTest { override fun getImage(): android.media.Image? = null } - @Test fun analyzerWithNoSessionJustClosesFrames() {+ @Test fun analyzerWithNoEngineJustClosesFrames() { val imu = ImuRecorder(app) var tracking = 0- val analyzer = VioFrameAnalyzer(0L, imu, { _, _ -> tracking++ }, { _, _, _, _, _, _ -> })+ val analyzer = OpenCvFrameAnalyzer(null, imu, { _, _ -> tracking++ }, { _, _, _, _, _, _ -> }) val image = FakeImage(ts = 1_000L) analyzer.analyze(image) assertTrue(image.closed) assertEquals(0, tracking) } - @Test fun analyzerPumpsImuAndReportsPerFrame() {- val sensorManager = app.getSystemService(android.content.Context.SENSOR_SERVICE) as android.hardware.SensorManager- shadowOf(sensorManager).addSensor(ShadowSensor.newInstance(Sensor.TYPE_GYROSCOPE_UNCALIBRATED))- shadowOf(sensorManager).addSensor(ShadowSensor.newInstance(Sensor.TYPE_ACCELEROMETER_UNCALIBRATED))- val imu = ImuRecorder(app)- imu.start()- fun ev(type: Int, values: FloatArray, ts: Long) = SensorEventBuilder.newBuilder()- .setSensor(ShadowSensor.newInstance(type)).setValues(values).setTimestamp(ts).build()- imu.onSensorChanged(ev(Sensor.TYPE_GYROSCOPE_UNCALIBRATED, floatArrayOf(1f, 2f, 3f), 0L))- imu.onSensorChanged(ev(Sensor.TYPE_ACCELEROMETER_UNCALIBRATED, floatArrayOf(0f, 0f, 9.81f), 1_000_000L))-- val handle = if (MeasureNative.available) {- MeasureNative.createSession(500.0, 500.0, 320.0, 240.0)- } else {- 4242L // guards in the bridge keep every call off the native side- }- val qualities = mutableListOf<Pair<Int, Boolean>>()- val diags = mutableListOf<List<Double>>()- val analyzer = VioFrameAnalyzer(- handle,- imu,- { q, plane -> qualities += q to plane },- { fps, skew, imuHz, tracked, landmarks, confidence ->- diags += listOf(fps, skew, imuHz, tracked.toDouble(), landmarks.toDouble(), confidence)- },+ @Test fun engineIsUnavailableWithoutNativeLibrary() {+ // Robolectric hosts have no OpenCV native library: the engine+ // must report unavailable so the AR page falls back cleanly,+ // and constructing one must still be safe (no native calls in+ // the constructor) because the tests build stand-ins.+ assertEquals(false, com.vayunmathur.measure.platform.opencv.OpenCvVioEngine.available)+ val engine = com.vayunmathur.measure.platform.opencv.OpenCvVioEngine(+ com.vayunmathur.measure.platform.Intrinsics(500.0, 500.0, 320.0, 240.0, true) )- val first = FakeImage(ts = 2_000_000L)- analyzer.analyze(first)- val second = FakeImage(ts = 18_000_000L)- analyzer.analyze(second)- assertTrue(first.closed && second.closed)- assertEquals(2, qualities.size)- assertEquals(2, diags.size)- // Second frame has a 16 ms interval behind it: fps is now positive- // (or zero only when the first-frame interval never seeded).- assertTrue(diags[1][0] >= 0.0)- assertTrue(diags[1][2] >= 0.0)- if (MeasureNative.available && handle != 0L) MeasureNative.destroySession(handle)- imu.stop()+ assertEquals(0, engine.centreCandidates(640, 480).size)+ assertEquals(3, engine.projectPoints(doubleArrayOf(1.0, 2.0, 3.0), 640.0, 480.0).size)+ engine.reset()+ engine.close() shadowOf(Looper.getMainLooper()).idle() }
measure/src/test/java/com/vayunmathur/measure/domain/DomainExtraTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/domain/DomainExtraTest.kt b/measure/src/test/java/com/vayunmathur/measure/domain/DomainExtraTest.ktindex a51b65472c..b9db06e283 100644--- a/measure/src/test/java/com/vayunmathur/measure/domain/DomainExtraTest.kt+++ b/measure/src/test/java/com/vayunmathur/measure/domain/DomainExtraTest.kt@@ -73,34 +73,4 @@ class DomainExtraTest { assertEquals(listOf("Distance", "Area", "Perimeter", "Angle", "Height"), MeasurementKind.entries.map { it.name }) assertEquals(listOf("Metric", "Imperial"), UnitSystem.entries.map { it.name }) }-- @Test fun nativeBridgeDegradesCleanly() {- val n = MeasureNative- // Whatever the host provides, the guarded contract holds: a zero- // handle is always "lost", empty projections, no rays or state.- assertEquals(MeasureNative.QUALITY_LOST, n.pushFrame(0L, ByteArray(4), 2, 2, 2, 0L))- assertEquals(null, n.rayToWorld(0L, 1f, 1f))- assertEquals(null, n.getState(0L))- assertEquals(0, n.projectPoints(0L, doubleArrayOf(1.0, 2.0, 3.0), 100.0, 100.0).size)- assertEquals(0, n.projectPoints(1L, DoubleArray(0), 100.0, 100.0).size)- n.destroySession(0L)- n.reset(0L)- n.pushImu(0L, doubleArrayOf(1.0))- n.pushImu(1L, DoubleArray(0))- if (n.available) {- val handle = n.createSession(500.0, 500.0, 320.0, 240.0)- assertTrue(handle != 0L, "host engine should create a session")- val frame = ByteArray(640 * 480) { 128.toByte() }- val quality = n.pushFrame(handle, frame, 640, 480, 640, 1_000_000L)- assertTrue(quality in 0..3, "quality=$quality")- n.pushImu(handle, doubleArrayOf(1e9, 0.0, 0.0, 0.0, 0.0, 0.0, 9.81))- val state = n.getState(handle)- if (state != null) assertEquals(8, state.size)- n.reset(handle)- n.destroySession(handle)- n.destroySession(handle)- } else {- assertEquals(0L, n.createSession(500.0, 500.0, 320.0, 240.0))- }- } }
measure/src/test/java/com/vayunmathur/measure/platform/ArFlowViewModelTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/platform/ArFlowViewModelTest.kt b/measure/src/test/java/com/vayunmathur/measure/platform/ArFlowViewModelTest.ktindex a87dd2b845..b2248095d2 100644--- a/measure/src/test/java/com/vayunmathur/measure/platform/ArFlowViewModelTest.kt+++ b/measure/src/test/java/com/vayunmathur/measure/platform/ArFlowViewModelTest.kt@@ -22,8 +22,16 @@ class ArFlowViewModelTest { private fun readyVm(): MeasureViewModel { val vm = MeasureViewModel(app)+ vm.engineAvailable = true vm.setCameraPermission(true)- vm.onSessionChanged(42L)+ // A stand-in engine: construction touches no native code (the+ // OpenCV library only loads behind OpenCvVioEngine.available),+ // which is exactly the seam the flow tests need.+ vm.onEngineChanged(+ com.vayunmathur.measure.platform.opencv.OpenCvVioEngine(+ com.vayunmathur.measure.platform.Intrinsics(500.0, 500.0, 320.0, 240.0, true)+ )+ ) vm.onTrackingUpdate(TrackingQuality.Good, hasPlane = true) return vm }
measure/src/test/java/com/vayunmathur/measure/platform/MeasureViewModelTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/platform/MeasureViewModelTest.kt b/measure/src/test/java/com/vayunmathur/measure/platform/MeasureViewModelTest.ktindex 5513be4147..6348c46f43 100644--- a/measure/src/test/java/com/vayunmathur/measure/platform/MeasureViewModelTest.kt+++ b/measure/src/test/java/com/vayunmathur/measure/platform/MeasureViewModelTest.kt@@ -283,12 +283,4 @@ class MeasureViewModelTest { store.clear() } - @Test fun trackingQualityCodesMap() {- assertEquals(TrackingQuality.Limited, trackingQualityFrom(com.vayunmathur.measure.domain.MeasureNative.QUALITY_LIMITED))- assertEquals(TrackingQuality.Good, trackingQualityFrom(com.vayunmathur.measure.domain.MeasureNative.QUALITY_GOOD))- assertEquals(TrackingQuality.Lost, trackingQualityFrom(com.vayunmathur.measure.domain.MeasureNative.QUALITY_LOST))- assertEquals(TrackingQuality.Initialising, trackingQualityFrom(com.vayunmathur.measure.domain.MeasureNative.QUALITY_INITIALISING))- assertEquals(TrackingQuality.Initialising, trackingQualityFrom(99))- assertEquals(TrackingQuality.Initialising, trackingQualityFrom(-1))- } }
measure/src/test/java/com/vayunmathur/measure/ui/MeasureContentsCoverageTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/ui/MeasureContentsCoverageTest.kt b/measure/src/test/java/com/vayunmathur/measure/ui/MeasureContentsCoverageTest.ktindex b127b3e8a4..898b244651 100644--- a/measure/src/test/java/com/vayunmathur/measure/ui/MeasureContentsCoverageTest.kt+++ b/measure/src/test/java/com/vayunmathur/measure/ui/MeasureContentsCoverageTest.kt@@ -165,7 +165,7 @@ class MeasureContentsCoverageTest { assertTrue(opened) } - // MeasureNative.available is true under Robolectric (loadLibrary is+ // OpenCvVioEngine.available is false under Robolectric (no native // shadowed), so the full tracking UI renders; without camera permission // the unavailable notice is the reachable guard. @Test@@ -369,21 +369,16 @@ class MeasureContentsCoverageTest { } @Test- fun nativeBridgeGuardsRejectZeroHandle() {- // Zero is never a live session: every bridge entry must refuse it- // without touching the native engine.- assertEquals(null, com.vayunmathur.measure.domain.MeasureNative.rayToWorld(0L, 10f, 20f))- assertEquals(null, com.vayunmathur.measure.domain.MeasureNative.getState(0L))- assertEquals(- 0,- com.vayunmathur.measure.domain.MeasureNative- .projectPoints(0L, doubleArrayOf(1.0, 2.0, 3.0), 100.0, 100.0).size,- )- assertEquals(- 0,- com.vayunmathur.measure.domain.MeasureNative- .projectPoints(1L, DoubleArray(0), 100.0, 100.0).size,+ fun engineWithoutScaleProjectsNothingVisible() {+ // No IMU scale lock means no metric world: candidates are empty+ // and projections report invisible rather than guessing.+ val engine = com.vayunmathur.measure.platform.opencv.OpenCvVioEngine(+ com.vayunmathur.measure.platform.Intrinsics(500.0, 500.0, 320.0, 240.0, true) )+ assertEquals(0, engine.centreCandidates(640, 480).size)+ val projected = engine.projectPoints(doubleArrayOf(1.0, 2.0, 3.0), 640.0, 480.0)+ assertEquals(3, projected.size)+ assertEquals(0.0, projected[2]) } @Test