measure: rebuild AR measuring flow
- Commit
b7fc1512d523e6d3cd4253d9d15b4397aa4ffcd0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 02:06 UTC (19 days ago)
- Parents
f92a3bb
Rebuild around the seams from the previous commit, keeping the Rust VIO engine and every non-AR tool intact. This is the "session config + hit strategy + placement + fallback" layer the audit found missing; ARCore/Play Services remain deliberately out (no-Play-Services premise, nothing in SUPPLY_CHAIN_RISKS.md or the catalog, and the shared catalog is outside measure/ scope). Engine (Rust, measure_vio): - hit_candidates() (new vio_hit.rs, split for the 500-line rule): plane hits must be 0.15-8 m away and land within the observed inlier extent (+0.75 m), feature points must be in that range and within 2.5 degrees of the ray. ray_to_world now selects from those candidates instead of returning the nearest landmark at any angle or any point on an infinite plane. - New JNI nativeHitTest returns the candidate list; Kotlin applies the unit-tested HitSelector policy, so selection is testable without a device. Gyro bias is now actually estimated at start-up while stationary (the estimator existed, unused). Flow (Kotlin): - ArHitProvider seam (Native/Fake), centre-reticle polling at 100 ms in the page; placement only from ArFlowState.Ready (Good tracking + sane hit), at the reticle pose on any tap or the Place button. Limited can no longer place scale-guess anchors. Anchors are individually removable, plus undo/clear. - Availability is explicit before the session starts: native engine, camera permission, gyro/accel presence, and the previously never-called camera/IMU timestamp check. Scanning (25 s) and Lost (15 s) time out into a fallback card offering the existing on-screen Ruler tool and a retry; unavailable states are explanation screens with the same exit, never a dead camera view. UI state stays in-screen and typed (flow state in ArMeasureUiState; no navigation state added). - Readouts: last segment stays distanceM, plus open-polyline total and per-segment mid-point labels on the overlay; closed area is only quoted when the polygon passes the planarity check that used to be dead code, with an explicit unreliable warning otherwise. Also fixes the bent-quad fixture in MeasureMathTest (it bent within its own plane, so planarity was correctly zero). Verified: :measure:compileDevKotlin green; cargo test -p measure_vio 46+9 green including new off-ray/out-of-range hit regressions; :measure:testDevUnitTest green (134 tests; the settings-persistence test flakes once under full-suite load - documented DataStore/Robolectric race in that test - and passes alone and on rerun). Physical-device checks remain: see report.
Diff
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.ktindex d61fd4e9f9..84b3c0cff0 100644--- a/measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.kt+++ b/measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.kt@@ -62,6 +62,35 @@ object MeasureNative { 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.@@ -94,6 +123,7 @@ object MeasureNative { 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,
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.ktnew file mode 100644index 0000000000..57057022eb--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt@@ -0,0 +1,35 @@+package com.vayunmathur.measure.platform++import com.vayunmathur.measure.domain.HitCandidate+import com.vayunmathur.measure.domain.HitSelector+import com.vayunmathur.measure.domain.MeasureNative++/**+ * 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`.+ */+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>,+) : 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)+ }+}++/** Deterministic provider for tests/previews. */+class FakeArHitProvider(var hit: HitCandidate? = null) : ArHitProvider {+ override fun centreHit(sessionHandle: Long): HitCandidate? = hit+}
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 2257087f92..fe795c3aee 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt@@ -4,7 +4,10 @@ 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.data.model.distanceTo+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.domain.polygonPerimeter import kotlinx.coroutines.launch@@ -133,6 +136,14 @@ internal fun MeasureViewModel.setPixelsPerMmImpl(v: Float) { } internal fun MeasureViewModel.onTrackingUpdateImpl(quality: TrackingQuality, hasPlane: Boolean) {+ val now = System.currentTimeMillis()+ when (quality) {+ TrackingQuality.Initialising, TrackingQuality.Limited ->+ if (scanningSinceMs == null) scanningSinceMs = now+ TrackingQuality.Good -> scanningSinceMs = null+ TrackingQuality.Lost -> if (lostSinceMs == null) lostSinceMs = now+ }+ if (quality != TrackingQuality.Lost) lostSinceMs = null arState.value = if (quality == TrackingQuality.Lost) { // Anchors from before a loss sit in a world frame the engine can // no longer re-observe (see TrackingQuality.Lost); leaving them@@ -143,17 +154,70 @@ internal fun MeasureViewModel.onTrackingUpdateImpl(quality: TrackingQuality, has hasPlane = hasPlane, anchors = emptyList(), distanceM = null,+ totalDistanceM = null, areaM2 = null,+ areaTrustworthy = true, perimeterM = null, polygonClosed = false, ) } else { arState.value.copy(quality = quality, hasPlane = hasPlane) }+ if (quality == TrackingQuality.Lost) {+ arState.value = arState.value.copy(reticleHit = null)+ }+ refreshFlowImpl() } internal fun MeasureViewModel.setCameraPermissionImpl(granted: Boolean) {+ if (!granted) {+ unavailableReason = com.vayunmathur.measure.domain.ArUnavailableReason.CameraPermissionDenied+ } else if (unavailableReason ==+ com.vayunmathur.measure.domain.ArUnavailableReason.CameraPermissionDenied+ ) {+ unavailableReason = null+ } arState.value = arState.value.copy(cameraPermissionGranted = granted)+ refreshFlowImpl()+}++/** Recompute the typed flow state from availability/session/quality/reticle. */+internal fun MeasureViewModel.refreshFlowImpl(nowMs: Long = System.currentTimeMillis()) {+ val s = arState.value+ // 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 ->+ com.vayunmathur.measure.domain.ArUnavailableReason.NativeEngineMissing+ !s.cameraPermissionGranted ->+ com.vayunmathur.measure.domain.ArUnavailableReason.CameraPermissionDenied+ else -> unavailableReason+ }+ val flow = com.vayunmathur.measure.domain.ArFlow.derive(+ unavailable = unavailable,+ hasSession = nativeSessionHandle != 0L && s.cameraPermissionGranted,+ quality = s.quality,+ reticleHit = s.reticleHit,+ scanningSinceMs = scanningSinceMs,+ lostSinceMs = lostSinceMs,+ nowMs = nowMs,+ )+ if (flow != s.flowState) arState.value = s.copy(flowState = flow)+}++internal fun MeasureViewModel.onReticleHitImpl(+ hit: com.vayunmathur.measure.domain.HitCandidate?,+) {+ arState.value = arState.value.copy(reticleHit = hit)+ refreshFlowImpl()+}++internal fun MeasureViewModel.onSessionChangedImpl(handle: Long) {+ nativeSessionHandle = handle+ if (handle == 0L) {+ arState.value = arState.value.copy(reticleHit = null)+ }+ refreshFlowImpl() } /** Called by the AR page with a world point resolved by the native engine. */@@ -174,16 +238,22 @@ internal fun MeasureViewModel.updateDiagnosticsImpl(update: DiagnosticsUiState.( * polygon is explicitly closed, since an open chain has no meaningful area. */ internal fun ArMeasureUiState.recomputedImpl(): ArMeasureUiState {- val distance = if (anchors.size >= 2) {- anchors[anchors.size - 2].distanceTo(anchors[anchors.size - 1])+ val trustworthy = areaIsTrustworthy(anchors)+ val area = if (polygonClosed && anchors.size >= 3 && trustworthy) {+ polygonArea(anchors) } else { null }- val area = if (polygonClosed && anchors.size >= 3) polygonArea(anchors) else null val perimeter = if (polygonClosed && anchors.size >= 3) { polygonPerimeter(anchors, closed = true) } else { null }- return copy(distanceM = distance, areaM2 = area, perimeterM = perimeter)+ return copy(+ distanceM = lastSegmentLengthM(anchors),+ totalDistanceM = polylineLengthM(anchors),+ areaM2 = area,+ areaTrustworthy = trustworthy,+ perimeterM = perimeter,+ ) }
measure/src/main/java/com/vayunmathur/measure/platform/MeasureUiContract.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureUiContract.kt b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureUiContract.ktindex d6ebdcf2e6..9abd9d8b5c 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureUiContract.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureUiContract.kt@@ -98,10 +98,14 @@ data class RulerUiState( data class ArMeasureUiState( val quality: TrackingQuality = TrackingQuality.Initialising, val anchors: List<Anchor> = emptyList(),- /** Metres. Null when fewer than two anchors are placed. */+ /** Metres, last segment. Null when fewer than two anchors are placed. */ val distanceM: Double? = null,+ /** Metres, whole open polyline. Null when fewer than two anchors. */+ val totalDistanceM: Double? = null, /** Square metres. Null unless the polygon is closed with three or more anchors. */ val areaM2: Double? = null,+ /** False when a closed polygon is too bent out of plane to quote an area. */+ val areaTrustworthy: Boolean = true, /** Metres. Null unless the polygon is closed. */ val perimeterM: Double? = null, val polygonClosed: Boolean = false,@@ -109,12 +113,20 @@ data class ArMeasureUiState( val hasPlane: Boolean = false, val unitSystem: UnitSystem = UnitSystem.Metric, val cameraPermissionGranted: Boolean = false,+ /** Typed flow state: the only source the page uses to gate placement. */+ val flowState: com.vayunmathur.measure.domain.ArFlowState =+ com.vayunmathur.measure.domain.ArFlowState.NoSession,+ /** Selected centre-reticle hit, mirrored for the overlay. */+ val reticleHit: com.vayunmathur.measure.domain.HitCandidate? = null, ) interface ArMeasureActions { /** Screen-space tap, normalised to 0..1 on both axes so the page need not know the resolution. */ fun placeAnchor(nx: Float, ny: Float) {}+ /** Place a point at the current centre reticle hit (the primary placement path). */+ fun placeAtReticle() {} fun undoAnchor() {}+ fun removeAnchor(id: Long) {} fun clearAnchors() {} fun closePolygon() {} fun saveCurrentMeasurement(label: String) {}
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 4936a0d01a..97339ed609 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt@@ -60,6 +60,13 @@ class MeasureViewModel(app: Application) : AndroidViewModel(app), /** Native VIO session handle, mirrored from the AR page so reset can reach it. */ internal var nativeSessionHandle: Long = 0L + internal var scanningSinceMs: Long? = null+ internal var lostSinceMs: Long? = null+ internal var unavailableReason: com.vayunmathur.measure.domain.ArUnavailableReason? = null++ /** Hit provider seam; the page swaps in the native-backed one. */+ var hitProvider: ArHitProvider = FakeArHitProvider()+ internal var nextAnchorId = 1L internal var nextMeasurementId = 1L @@ -129,6 +136,38 @@ class MeasureViewModel(app: Application) : AndroidViewModel(app), /** Called by the AR page with a world point resolved by the native engine. */ fun addResolvedAnchor(x: Double, y: Double, z: Double, onPlane: Boolean) = addResolvedAnchorImpl(x, y, z, onPlane) + fun onReticleHit(hit: com.vayunmathur.measure.domain.HitCandidate?) = onReticleHitImpl(hit)++ fun onSessionChanged(handle: Long) = onSessionChangedImpl(handle)++ fun setUnavailableReason(reason: com.vayunmathur.measure.domain.ArUnavailableReason?) {+ unavailableReason = reason+ refreshFlowImpl()+ }++ /** Re-derive the flow state (drives scanning/lost timeouts). */+ fun tickFlow() = refreshFlowImpl()++ /** Poll the hit provider for the centre reticle and publish the result. */+ fun refreshReticle() {+ onReticleHit(hitProvider.centreHit(nativeSessionHandle))+ }++ override fun placeAtReticle() {+ val hit = arState.value.reticleHit ?: return+ if (!com.vayunmathur.measure.domain.ArFlow.canPlace(arState.value.flowState)) return+ addResolvedAnchor(+ hit.position.x, hit.position.y, hit.position.z,+ onPlane = hit.kind == com.vayunmathur.measure.domain.HitKind.Plane,+ )+ }++ override fun removeAnchor(id: Long) {+ val anchors = arState.value.anchors.filterNot { it.id == id }+ arState.value = arState.value.copy(anchors = anchors, polygonClosed = false)+ .recomputedImpl()+ }+ override fun undoAnchor() { val anchors = arState.value.anchors.dropLast(1) arState.value = arState.value.copy(anchors = anchors, polygonClosed = false).recomputedImpl()@@ -138,7 +177,9 @@ class MeasureViewModel(app: Application) : AndroidViewModel(app), arState.value = arState.value.copy( anchors = emptyList(), distanceM = null,+ totalDistanceM = null, areaM2 = null,+ areaTrustworthy = true, perimeterM = null, polygonClosed = false, )
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 805b2320f9..69eca9e50d 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.kt@@ -17,11 +17,13 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.IconUndo@@ -32,8 +34,11 @@ import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.measure.R 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.domain.segmentsOf import com.vayunmathur.measure.platform.ArMeasureActions import com.vayunmathur.measure.platform.ArMeasureUiState @@ -43,9 +48,9 @@ fun ArMeasureContent( actions: ArMeasureActions, screenPoints: List<Offset?> = emptyList(), onCanvasSized: (Size) -> Unit = {},- onTap: (Float, Float) -> Unit = { _, _ -> }, cameraContent: @Composable () -> Unit = {}, onOpenSettings: () -> Unit = {},+ onOpenRuler: () -> Unit = {}, bottomBar: @Composable () -> Unit = {}, ) { AppScaffold(@@ -56,13 +61,21 @@ fun ArMeasureContent( ) { padding -> Box(Modifier.fillMaxSize().padding(padding)) { - if (!MeasureNative.available) {- UnavailableNotice(stringResource(R.string.ar_unavailable_native))- return@Box- }- if (!state.cameraPermissionGranted) {- UnavailableNotice(stringResource(R.string.ar_unavailable_camera))- return@Box+ // Unavailable is a real screen with an exit, never a dead camera view.+ val unavailableReason = (state.flowState as? ArFlowState.Unavailable)?.reason+ when {+ unavailableReason != null -> {+ 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+ } } cameraContent()@@ -71,7 +84,7 @@ fun ArMeasureContent( state = state, screenPoints = screenPoints, onCanvasSized = onCanvasSized,- onTap = onTap,+ onTap = { actions.placeAtReticle() }, modifier = Modifier.fillMaxSize(), ) @@ -80,7 +93,12 @@ fun ArMeasureContent( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp), ) {- TrackingBanner(state.quality, state.hasPlane)+ TrackingBanner(state)+ val timedOut = (state.flowState as? ArFlowState.Scanning)?.timedOut == true ||+ (state.flowState as? ArFlowState.TrackingLost)?.timedOut == true+ if (timedOut) {+ FallbackCard(onOpenRuler = onOpenRuler, onRetry = { actions.resetTracking() })+ } } Column(@@ -89,7 +107,23 @@ fun ArMeasureContent( verticalArrangement = Arrangement.spacedBy(8.dp), ) { ReadoutCard(state)+ if (state.anchors.isNotEmpty()) {+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ state.anchors.forEachIndexed { index, anchor ->+ OutlinedButton(onClick = { actions.removeAnchor(anchor.id) }) {+ Text(stringResource(R.string.ar_anchor_point, index + 1) + " ×")+ }+ }+ }+ } Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(+ onClick = { actions.placeAtReticle() },+ enabled = state.flowState is ArFlowState.Ready,+ ) {+ IconAdd()+ Text(stringResource(R.string.ar_place_point))+ } OutlinedButton( onClick = { actions.undoAnchor() }, enabled = state.anchors.isNotEmpty(),@@ -108,46 +142,99 @@ fun ArMeasureContent( } } +@Composable+private fun unavailableMessage(reason: ArUnavailableReason): String = when (reason) {+ ArUnavailableReason.NativeEngineMissing -> stringResource(R.string.ar_unavailable_native)+ ArUnavailableReason.CameraPermissionDenied -> stringResource(R.string.ar_unavailable_camera)+ ArUnavailableReason.CameraTimestampMismatch -> stringResource(R.string.ar_unavailable_timestamps)+ ArUnavailableReason.MotionSensorsMissing -> stringResource(R.string.ar_unavailable_sensors)+}+ /**- * Coaching banner.- *- * While initialising this is not decoration — monocular visual-inertial tracking cannot- * recover metric scale from rotation alone, so the user genuinely has to translate the- * device before any distance exists. Saying so plainly is more useful than a spinner.+ * Coaching banner, driven by the typed flow state. While scanning this+ * is not decoration: monocular VIO cannot recover metric scale from+ * rotation alone, so the user genuinely has to translate the device.+ * Manually constructed states (previews/tests) fall back to the+ * quality-based wording they always used. */ @Composable-private fun TrackingBanner(quality: TrackingQuality, hasPlane: Boolean) {- val (message, color) = when (quality) {+private fun TrackingBanner(state: ArMeasureUiState) {+ val (message, color) = when (val flow = state.flowState) {+ is ArFlowState.Unavailable -> return+ is ArFlowState.Ready ->+ stringResource(R.string.ar_ready_place) to MaterialTheme.colorScheme.primaryContainer+ ArFlowState.Searching ->+ stringResource(R.string.ar_searching) to MaterialTheme.colorScheme.tertiaryContainer+ is ArFlowState.Scanning ->+ if (flow.timedOut) {+ stringResource(R.string.ar_scanning_timeout) to MaterialTheme.colorScheme.errorContainer+ } else if (state.quality == TrackingQuality.Limited) {+ stringResource(R.string.ar_tracking_limited) to MaterialTheme.colorScheme.tertiaryContainer+ } else {+ stringResource(R.string.ar_scanning) to MaterialTheme.colorScheme.tertiaryContainer+ }+ is ArFlowState.TrackingLost ->+ if (flow.timedOut) {+ stringResource(R.string.ar_lost_timeout) to MaterialTheme.colorScheme.errorContainer+ } else {+ stringResource(R.string.ar_tracking_lost) to MaterialTheme.colorScheme.errorContainer+ }+ ArFlowState.NoSession -> legacyBanner(state)+ }+ Box(+ Modifier+ .clip(RoundedCornerShape(12.dp))+ .background(color)+ .padding(horizontal = 14.dp, vertical = 8.dp)+ ) {+ Text(message, style = MaterialTheme.typography.bodyMedium)+ }+}++@Composable+private fun legacyBanner(state: ArMeasureUiState): Pair<String, androidx.compose.ui.graphics.Color> =+ when (state.quality) { TrackingQuality.Initialising -> stringResource(R.string.ar_tracking_initialising) to MaterialTheme.colorScheme.tertiaryContainer- TrackingQuality.Limited -> stringResource(R.string.ar_tracking_limited) to MaterialTheme.colorScheme.tertiaryContainer- TrackingQuality.Lost -> stringResource(R.string.ar_tracking_lost) to MaterialTheme.colorScheme.errorContainer- TrackingQuality.Good -> stringResource(- if (hasPlane) R.string.ar_tracking_ready else R.string.ar_tracking_ready_no_surface+ if (state.hasPlane) R.string.ar_tracking_ready else R.string.ar_tracking_ready_no_surface ) to MaterialTheme.colorScheme.primaryContainer }++@Composable+private fun FallbackCard(onOpenRuler: () -> Unit, onRetry: () -> Unit) { Box( Modifier .clip(RoundedCornerShape(12.dp))- .background(color)- .padding(horizontal = 14.dp, vertical = 8.dp)+ .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.9f))+ .padding(horizontal = 14.dp, vertical = 10.dp) ) {- Text(message, style = MaterialTheme.typography.bodyMedium)+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Text(stringResource(R.string.ar_fallback_title), style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(R.string.ar_fallback_body),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(onClick = onOpenRuler) { Text(stringResource(R.string.ar_open_ruler)) }+ OutlinedButton(onClick = onRetry) { Text(stringResource(R.string.ar_try_again)) }+ }+ } } } @Composable private fun ReadoutCard(state: ArMeasureUiState) {- if (state.distanceM == null && state.areaM2 == null) return+ if (state.distanceM == null && state.areaM2 == null && !state.polygonClosed) return Box( Modifier .clip(RoundedCornerShape(12.dp))@@ -161,6 +248,21 @@ private fun ReadoutCard(state: ArMeasureUiState) { style = MaterialTheme.typography.headlineSmall, ) }+ state.totalDistanceM?.let { total ->+ if (state.anchors.size > 2) {+ Text(+ stringResource(R.string.ar_total, Units.formatLength(total, state.unitSystem)),+ style = MaterialTheme.typography.bodyMedium,+ )+ }+ }+ if (state.polygonClosed && !state.areaTrustworthy) {+ Text(+ stringResource(R.string.ar_area_unreliable),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.error,+ )+ } state.areaM2?.let { Text( stringResource(R.string.ar_area, Units.formatArea(it, state.unitSystem)),@@ -182,45 +284,64 @@ private fun ReadoutCard(state: ArMeasureUiState) { } /**- * Anchor and edge overlay.- *- * Anchors are drawn from screen positions the engine projected from their world- * coordinates, so this layer holds no projection maths and stays previewable.+ * Anchor/edge overlay with a continuous centre reticle. The reticle is+ * the placement point: any tap (or the Place button) places at the+ * reticle hit, never at the finger's raw ray, so what the user sees+ * centred is exactly what gets measured. */ @Composable private fun ArOverlay( state: ArMeasureUiState, screenPoints: List<Offset?>, onCanvasSized: (Size) -> Unit,- onTap: (Float, Float) -> Unit,+ onTap: () -> Unit, modifier: Modifier = Modifier, ) { val primary = MaterialTheme.colorScheme.primary val onPrimary = MaterialTheme.colorScheme.onPrimary- val measurable = state.quality == TrackingQuality.Good ||- state.quality == TrackingQuality.Limited+ val error = MaterialTheme.colorScheme.error+ val ready = state.flowState is ArFlowState.Ready+ val searching = state.flowState is ArFlowState.Searching+ val segments = segmentsOf(state.anchors)+ val segmentLabels = segments.map { Units.formatLength(it.lengthM, state.unitSystem) } Canvas( modifier .onSizeChanged { onCanvasSized(Size(it.width.toFloat(), it.height.toFloat())) }- .pointerInput(measurable) {- if (!measurable) return@pointerInput- detectTapGestures { pos ->- onTap(pos.x / size.width, pos.y / size.height)- }+ .pointerInput(ready) {+ if (!ready) return@pointerInput+ detectTapGestures { onTap() } } ) {- // Reticle at the centre, showing where a tap would land.- if (measurable) {+ // Reticle at the centre: filled when a sane hit is selected,+ // hollow while searching, hidden until tracking starts.+ if (ready || searching) { val c = Offset(size.width / 2f, size.height / 2f)- drawCircle(primary.copy(alpha = 0.9f), 6f, c)- drawCircle(primary.copy(alpha = 0.4f), 22f, c, style = Stroke(2f))+ val reticleColor = if (ready) primary else error+ drawCircle(reticleColor.copy(alpha = 0.9f), 6f, c)+ drawCircle(reticleColor.copy(alpha = 0.4f), 22f, c, style = Stroke(2f)) } for (i in 0 until screenPoints.size - 1) { val a = screenPoints[i] val b = screenPoints[i + 1]- if (a != null && b != null) drawLine(primary, a, b, 4f)+ if (a != null && b != null) {+ drawLine(primary, a, b, 4f)+ // Mid-point distance label for this segment.+ val label = segmentLabels.getOrNull(i)+ if (label != null) {+ val mid = Offset((a.x + b.x) / 2f, (a.y + b.y) / 2f)+ drawContext.canvas.nativeCanvas.drawText(+ label,+ mid.x,+ mid.y - 12f,+ android.graphics.Paint().apply {+ textSize = 36f+ textAlign = android.graphics.Paint.Align.CENTER+ },+ )+ }+ } } if (state.polygonClosed && screenPoints.size >= 3) { val a = screenPoints.last()@@ -236,7 +357,7 @@ private fun ArOverlay( } @Composable-private fun UnavailableNotice(message: String) {+private fun UnavailableNotice(message: String, onOpenRuler: () -> Unit = {}) { Column( modifier = Modifier.fillMaxSize().padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally,@@ -251,5 +372,11 @@ private fun UnavailableNotice(message: String) { style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, )+ Text(+ stringResource(R.string.ar_fallback_body),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ OutlinedButton(onClick = onOpenRuler) { Text(stringResource(R.string.ar_open_ruler)) } } }
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 d40a85b174..12f768eae8 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt@@ -1,7 +1,10 @@ package com.vayunmathur.measure.ui import android.Manifest+import android.content.Context import android.content.pm.PackageManager+import android.hardware.Sensor+import android.hardware.SensorManager import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState@@ -13,15 +16,17 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size-import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext import androidx.core.content.ContextCompat import androidx.compose.foundation.layout.fillMaxSize 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.CameraIntrinsicsResolver import com.vayunmathur.measure.platform.MeasureViewModel+import com.vayunmathur.measure.platform.NativeArHitProvider import com.vayunmathur.measure.platform.trackingQualityFrom import com.vayunmathur.measure.platform.updateDiagnosticsImpl import com.vayunmathur.measure.ui.components.MeasureBottomBar@@ -35,11 +40,33 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { var sessionHandle by remember { mutableLongStateOf(0L) } var screenPoints by remember { mutableStateOf<List<Offset?>>(emptyList()) } var canvasSize by remember { mutableStateOf(Size.Zero) }+ val context = LocalContext.current val cameraGranted = rememberCameraPermission { viewModel.setCameraPermission(it) } - // Reproject anchors whenever the anchor set or the pose changes. Projection lives- // in the engine because it owns the current pose and the intrinsics.+ // Availability is decided before any camera work: a device whose+ // camera clock cannot fuse with its IMU, or with no gyro/accel,+ // 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.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+ while (true) {+ viewModel.refreshReticle()+ delay(RETICLE_INTERVAL_MS)+ }+ }++ // 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()) { screenPoints = emptyList()@@ -54,17 +81,15 @@ 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: passing canvas pixels- // compressed every anchor into the top-left of the screen.+ // analysis size, not the canvas size. val projected = MeasureNative.projectPoints( sessionHandle, flat, ANALYSIS_SIZE.width.toDouble(), ANALYSIS_SIZE.height.toDouble(), )- // The third component is the engine's visibility flag: points- // behind the camera project to (0, 0, false) and must not be- // drawn as an anchor in the top-left corner.+ // Third component is the visibility flag: points behind the+ // camera must not be drawn in the top-left corner. screenPoints = projected.toList().chunked(3).map { c -> if (c[2] > 0.5) { Offset(c[0].toFloat() * canvasSize.width, c[1].toFloat() * canvasSize.height)@@ -72,6 +97,7 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { null } }+ viewModel.tickFlow() delay(PROJECTION_INTERVAL_MS) } }@@ -81,21 +107,6 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { actions = viewModel, screenPoints = screenPoints, onCanvasSized = { canvasSize = it },- onTap = { nx, ny ->- if (canvasSize != Size.Zero) {- // rayToWorld unprojects with analysis-stream intrinsics, so- // the tap must be scaled into analysis pixels, not canvas- // pixels (the two differ by the screen/analysis ratio).- val hit = MeasureNative.rayToWorld(- sessionHandle,- nx * ANALYSIS_SIZE.width,- ny * ANALYSIS_SIZE.height,- )- if (hit != null) {- viewModel.addResolvedAnchor(hit[0], hit[1], hit[2], hit[3] > 0.5)- }- }- }, cameraContent = { if (cameraGranted && MeasureNative.available) { MeasureCamera(@@ -105,7 +116,7 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { }, onSessionReady = { sessionHandle = it- viewModel.nativeSessionHandle = it+ viewModel.onSessionChanged(it) }, onDiagnostics = { fps, skew, imuHz, tracked, landmarks, confidence -> viewModel.updateDiagnosticsImpl {@@ -126,10 +137,27 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { } }, onOpenSettings = { backStack.add(Route.Settings) },+ onOpenRuler = { backStack.add(Route.Ruler) }, bottomBar = { MeasureBottomBar(backStack, Route.ArMeasure) }, ) } +/** Explicit availability states, checked once before the session starts. */+private fun availabilityReason(context: Context): ArUnavailableReason? {+ if (!MeasureNative.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 ||+ sensors.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null+ val hasAccel = sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER_UNCALIBRATED) != null ||+ sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null+ if (!hasGyro || !hasAccel) return ArUnavailableReason.MotionSensorsMissing+ if (!CameraIntrinsicsResolver.timestampsAlignWithSensors(context)) {+ return ArUnavailableReason.CameraTimestampMismatch+ }+ return null+}+ /** Requests CAMERA lazily, so the four sensor tools never trigger a camera prompt. */ @Composable private fun rememberCameraPermission(onResult: (Boolean) -> Unit): Boolean {@@ -152,3 +180,4 @@ private fun rememberCameraPermission(onResult: (Boolean) -> Unit): Boolean { } private const val PROJECTION_INTERVAL_MS = 33L+private const val RETICLE_INTERVAL_MS = 100L
measure/src/main/res/values/strings.xml
diff --git a/measure/src/main/res/values/strings.xml b/measure/src/main/res/values/strings.xmlindex 77a0bff768..cae2a21c78 100644--- a/measure/src/main/res/values/strings.xml+++ b/measure/src/main/res/values/strings.xml@@ -123,6 +123,21 @@ <!-- ArMeasureContent: reason shown under ar_unavailable_title when the camera permission has not been granted. --> <string name="ar_unavailable_camera">Camera access is needed to measure in AR.</string>+ <string name="ar_unavailable_timestamps">This camera\'s timestamps can\'t be matched with the motion sensors, so AR tracking can\'t work reliably on this device.</string>+ <string name="ar_unavailable_sensors">This device is missing the motion sensors AR tracking needs.</string>+ <string name="ar_scanning">Move your phone slowly sideways to scan the surface</string>+ <string name="ar_searching">Point the centre marker at a surface</string>+ <string name="ar_ready_place">Tap anywhere, or use +, to place a point</string>+ <string name="ar_place_point">Place point</string>+ <string name="ar_total">Total %1$s</string>+ <string name="ar_area_unreliable">Shape is not flat — area not quoted</string>+ <string name="ar_fallback_title">Use the ruler instead</string>+ <string name="ar_fallback_body">AR tracking isn\'t available, but you can still measure on screen with the ruler tool.</string>+ <string name="ar_open_ruler">Open ruler</string>+ <string name="ar_try_again">Try AR again</string>+ <string name="ar_scanning_timeout">Still no tracking — check light and texture, or use the ruler</string>+ <string name="ar_lost_timeout">Tracking hasn\'t recovered — restart it or use the ruler</string>+ <string name="ar_anchor_point">Point %1$d</string> <!-- SavedMeasurementsContent: heading of the empty state. --> <string name="saved_empty_title">No saved measurements</string> <!-- SavedMeasurementsContent: body of the empty state, telling the user how to add one. -->
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 0fe08e93ed..1aaa74d3e1 100644--- a/measure/src/main/rust/src/lib.rs+++ b/measure/src/main/rust/src/lib.rs@@ -198,6 +198,46 @@ mod jni_bindings { .resolve::<jni::errors::LogErrorAndDefault>() } + /// All sane hit candidates along a screen ray, as a flat array of+ /// `[kind, x, y, z, distanceM, angularErrorDeg, normalDotUp]` per+ /// candidate (7 values each). Selection policy lives in Kotlin+ /// (HitSelector) so it is unit-testable; the engine only reports+ /// candidates that already pass its distance/angle/extent sanity.+ #[no_mangle]+ pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativeHitTest<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ handle: jlong,+ px: jfloat,+ py: jfloat,+ ) -> jdoubleArray {+ env.with_env(|env| -> jni::errors::Result<jdoubleArray> {+ let vals: Vec<f64> = {+ let guard = sessions().lock().unwrap();+ match guard.get(&handle) {+ Some(s) => s+ .hit_candidates(px, py)+ .iter()+ .flat_map(|c| {+ [+ c.kind as f64,+ c.point[0],+ c.point[1],+ c.point[2],+ c.distance_m,+ c.angular_error_rad.to_degrees(),+ c.normal_dot_up,+ ]+ })+ .collect(),+ None => Vec::new(),+ }+ };+ Ok(make_double_array(env, &vals))+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+ }+ /// Diagnostics snapshot: /// `[quality, scaleConfidence, landmarkCount, trackedCount, hasPlane, gx, gy, gz]`. #[no_mangle]
measure/src/main/rust/src/vio.rs
diff --git a/measure/src/main/rust/src/vio.rs b/measure/src/main/rust/src/vio.rsindex 12c6580450..602c78ef82 100644--- a/measure/src/main/rust/src/vio.rs+++ b/measure/src/main/rust/src/vio.rs@@ -19,7 +19,7 @@ use crate::align::{align_visual_inertial, refine_gravity, AlignmentResult, Keyfr use crate::epipolar::{recover_pose, NPt}; use crate::klt::{track, Pyramid}; use crate::plane::{fit_plane_ransac, Plane};-use crate::preintegrate::{preintegrate, ImuSample, Preintegrated};+use crate::preintegrate::{estimate_gyro_bias, is_stationary, preintegrate, ImuSample, Preintegrated}; use crate::triangulate::{triangulate_checked, CameraPose}; use vision_core::features::detect_and_describe; use vision_core::imgbuf::Gray;@@ -255,7 +255,21 @@ impl VioSession { (0..n as u64).map(|i| start + i).collect() } + /// Capture the gyro bias while the device is still at start-up.+ /// Biases were previously left at zero for the whole session even+ /// though preintegrate.rs already had the estimator: every interval+ /// then integrated a constant rotation offset as if it were motion.+ fn calibrate_gyro_bias_if_stationary(&mut self) {+ if self.gyro_bias.norm() > 1e-9 || self.frame_count > 120 {+ return;+ }+ if is_stationary(&self.pending_imu, 0.05, 0.5) {+ self.gyro_bias = estimate_gyro_bias(&self.pending_imu);+ }+ }+ fn add_keyframe(&mut self, t_ns: i64) {+ self.calibrate_gyro_bias_if_stationary(); // Correspondences between the previous keyframe and now, matched by // feature id. Previously the relative pose was estimated between the // last two *frames* and then composed onto the last *keyframe*, which@@ -457,42 +471,14 @@ impl VioSession { /// surface, not two independently noisy depths. Falls back to the nearest landmark /// along the ray when no plane is available. pub fn ray_to_world(&self, px: f32, py: f32) -> Option<(Vector3<f64>, bool)> {- if self.quality == Quality::Initialising || self.quality == Quality::Lost {- return None;- }- let (nx, ny) = self.intr.unproject(px, py);- // Camera ray in world coordinates.- let dir_cam = Vector3::new(nx, ny, 1.0);- let rt = self.pose.r.transpose();- let dir_world = rt * dir_cam;- let origin = self.pose.center();-- if let Some(ref plane) = self.plane {- if let Some(hit) = plane.intersect_ray(&origin, &dir_world) {- return Some((hit, true));- }- }-- // Nearest landmark by angle to the ray.- let dn = dir_world.norm();- if dn < 1e-9 || self.landmarks.is_empty() {- return None;- }- let unit = dir_world / dn;- let mut best: Option<(f64, Vector3<f64>)> = None;- for lm in &self.landmarks {- let v = *lm - origin;- let along = v.dot(&unit);- if along <= 0.0 {- continue;- }- let perp = (v - unit * along).norm();- if best.as_ref().is_none_or(|(d, _)| perp < *d) {- best = Some((perp, *lm));- }+ let candidates = self.hit_candidates(px, py);+ // Plane first (it lies on the ray), else the smallest angular error.+ if let Some(c) = candidates.iter().find(|c| c.kind == HitCandidate::KIND_PLANE) {+ return Some((c.point, true)); }- best.map(|(_, p)| (p, false))+ candidates.first().map(|c| (c.point, false)) } } +include!("vio_hit.rs"); include!("vio_part1.rs");\ No newline at end of file
measure/src/main/rust/src/vio_hit.rs
diff --git a/measure/src/main/rust/src/vio_hit.rs b/measure/src/main/rust/src/vio_hit.rsnew file mode 100644index 0000000000..7a671521f8--- /dev/null+++ b/measure/src/main/rust/src/vio_hit.rs@@ -0,0 +1,133 @@+impl VioSession {+ /// All sane hits along a screen ray, best feature point first.+ ///+ /// The previous implementation returned the landmark with the smallest+ /// perpendicular distance with no threshold, and intersected one+ /// infinite plane with no distance or extent check, so any tap+ /// produced a confident point however meaningless it was. Candidates+ /// here must lie within [MIN_HIT_DISTANCE_M, MAX_HIT_DISTANCE_M] of+ /// the camera; feature points must sit within MAX_FEATURE_ANGLE_RAD+ /// of the ray; a plane hit must fall near the observed inlier extent+ /// rather than anywhere on the infinite fitted plane.+ pub fn hit_candidates(&self, px: f32, py: f32) -> Vec<HitCandidate> {+ if self.quality == Quality::Initialising || self.quality == Quality::Lost {+ return Vec::new();+ }+ let (nx, ny) = self.intr.unproject(px, py);+ let dir_cam = Vector3::new(nx, ny, 1.0);+ let rt = self.pose.r.transpose();+ let dir_world = rt * dir_cam;+ let origin = self.pose.center();+ let dn = dir_world.norm();+ if dn < 1e-9 {+ return Vec::new();+ }+ let unit = dir_world / dn;+ let mut out = Vec::new();++ if let Some(ref plane) = self.plane {+ if let Some(hit) = plane.intersect_ray(&origin, &dir_world) {+ let dist = (hit - origin).norm();+ if (MIN_HIT_DISTANCE_M..=MAX_HIT_DISTANCE_M).contains(&dist)+ && self.within_plane_extent(plane, &hit)+ {+ let up = -self.gravity;+ let normal_dot_up = if up.norm() > 1e-9 {+ (plane.normal.dot(&up) / up.norm()).abs()+ } else {+ 1.0+ };+ out.push(HitCandidate {+ kind: HitCandidate::KIND_PLANE,+ point: hit,+ distance_m: dist,+ angular_error_rad: 0.0,+ normal_dot_up,+ });+ }+ }+ }++ let mut features: Vec<HitCandidate> = Vec::new();+ for lm in &self.landmarks {+ let v = *lm - origin;+ let along = v.dot(&unit);+ if !(MIN_HIT_DISTANCE_M..=MAX_HIT_DISTANCE_M).contains(&along) {+ continue;+ }+ let perp = (v - unit * along).norm();+ let angle = (perp / along).atan();+ if angle > MAX_FEATURE_ANGLE_RAD {+ continue;+ }+ features.push(HitCandidate {+ kind: HitCandidate::KIND_FEATURE,+ point: *lm,+ distance_m: along,+ angular_error_rad: angle,+ normal_dot_up: -1.0,+ });+ }+ features.sort_by(|a, b| {+ a.angular_error_rad+ .total_cmp(&b.angular_error_rad)+ .then_with(|| a.distance_m.total_cmp(&b.distance_m))+ });+ features.truncate(MAX_FEATURE_CANDIDATES);+ out.extend(features);+ out+ }++ /// A plane hit must land near where the plane was actually observed:+ /// within the inlier spread around their centroid, plus a margin.+ fn within_plane_extent(&self, plane: &Plane, hit: &Vector3<f64>) -> bool {+ if plane.inliers.is_empty() || self.landmarks.is_empty() {+ return true;+ }+ let mut centroid = Vector3::zeros();+ let mut count = 0usize;+ for &i in &plane.inliers {+ if let Some(p) = self.landmarks.get(i) {+ centroid += *p;+ count += 1;+ }+ }+ if count == 0 {+ return true;+ }+ centroid /= count as f64;+ let mut max_r = 0.0f64;+ for &i in &plane.inliers {+ if let Some(p) = self.landmarks.get(i) {+ max_r = max_r.max((*p - centroid).norm());+ }+ }+ (*hit - centroid).norm() <= max_r + PLANE_EXTENT_MARGIN_M+ }+}+++/// One sane hit along a ray. `kind` mirrors the Kotlin HitKind ordinals+/// used across JNI: 0 = plane, 1 = feature point. `normal_dot_up` is -1+/// when the hit has no surface normal.+#[derive(Clone, Copy, Debug)]+pub struct HitCandidate {+ pub kind: i32,+ pub point: Vector3<f64>,+ pub distance_m: f64,+ pub angular_error_rad: f64,+ pub normal_dot_up: f64,+}++impl HitCandidate {+ pub const KIND_PLANE: i32 = 0;+ pub const KIND_FEATURE: i32 = 1;+}++const MIN_HIT_DISTANCE_M: f64 = 0.15;+const MAX_HIT_DISTANCE_M: f64 = 8.0;+/// ~2.5 degrees: a tap is only allowed to claim a landmark near its ray.+const MAX_FEATURE_ANGLE_RAD: f64 = 0.0436;+const PLANE_EXTENT_MARGIN_M: f64 = 0.75;+const MAX_FEATURE_CANDIDATES: usize = 8;+
measure/src/main/rust/src/vio_part1.rs
diff --git a/measure/src/main/rust/src/vio_part1.rs b/measure/src/main/rust/src/vio_part1.rsindex e2818dd5ed..b3d628d9ba 100644--- a/measure/src/main/rust/src/vio_part1.rs+++ b/measure/src/main/rust/src/vio_part1.rs@@ -96,6 +96,26 @@ mod tests { assert!(!existing.contains(&(11.0, 11.0))); } + #[test]+ fn hit_test_rejects_a_landmark_far_off_the_ray() {+ // Regression: the old ray cast returned this landmark anyway.+ let mut s = VioSession::new(intr());+ s.quality = Quality::Good;+ s.landmarks = vec![Vector3::new(3.0, 0.0, 2.0)];+ assert!(s.hit_candidates(320.0, 240.0).is_empty());+ assert!(s.ray_to_world(320.0, 240.0).is_none());+ }++ #[test]+ fn hit_test_accepts_a_landmark_on_the_ray_within_range() {+ let mut s = VioSession::new(intr());+ s.quality = Quality::Good;+ s.landmarks = vec![Vector3::new(0.0, 0.0, 2.0), Vector3::new(0.0, 0.0, 20.0)];+ let hits = s.hit_candidates(320.0, 240.0);+ assert_eq!(hits.len(), 1, "out-of-range landmark must be filtered");+ assert!((hits[0].distance_m - 2.0).abs() < 1e-9);+ }+ #[test] fn median_of_even_and_odd_lengths() { assert!((median(&mut [3.0, 1.0, 2.0]) - 2.0).abs() < 1e-9);
measure/src/test/java/com/vayunmathur/measure/domain/MeasureMathTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/domain/MeasureMathTest.kt b/measure/src/test/java/com/vayunmathur/measure/domain/MeasureMathTest.ktindex 7114e175c8..3c6de8f24a 100644--- a/measure/src/test/java/com/vayunmathur/measure/domain/MeasureMathTest.kt+++ b/measure/src/test/java/com/vayunmathur/measure/domain/MeasureMathTest.kt@@ -35,7 +35,7 @@ class MeasureMathTest { ) assertTrue(areaIsTrustworthy(flat)) val bent = flat.mapIndexed { i, anchor ->- if (i == 3) anchor.copy(z = 0.4) else anchor+ if (i == 3) anchor.copy(y = 0.4) else anchor } assertFalse(areaIsTrustworthy(bent)) }
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.ktnew file mode 100644index 0000000000..a87dd2b845--- /dev/null+++ b/measure/src/test/java/com/vayunmathur/measure/platform/ArFlowViewModelTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.measure.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.measure.data.model.TrackingQuality+import com.vayunmathur.measure.domain.ArFlowState+import com.vayunmathur.measure.domain.HitCandidate+import com.vayunmathur.measure.domain.HitKind+import com.vayunmathur.measure.domain.Vec3+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class ArFlowViewModelTest {++ private val app get() = ApplicationProvider.getApplicationContext<Application>()++ private fun readyVm(): MeasureViewModel {+ val vm = MeasureViewModel(app)+ vm.setCameraPermission(true)+ vm.onSessionChanged(42L)+ vm.onTrackingUpdate(TrackingQuality.Good, hasPlane = true)+ return vm+ }++ @Test fun reticleHitMakesFlowReadyAndPlacementUsesIt() {+ val vm = readyVm()+ assertEquals(ArFlowState.Searching, vm.ar.value.flowState)+ vm.hitProvider = FakeArHitProvider(+ HitCandidate(HitKind.Plane, Vec3(0.0, 0.0, 0.0), 1.5)+ )+ vm.refreshReticle()+ assertIs<ArFlowState.Ready>(vm.ar.value.flowState)+ vm.placeAtReticle()+ assertEquals(1, vm.ar.value.anchors.size)+ assertTrue(vm.ar.value.anchors.single().onPlane)++ // A second reticle point completes a segment + polyline total.+ vm.onReticleHit(HitCandidate(HitKind.Plane, Vec3(3.0, 4.0, 0.0), 5.0))+ vm.placeAtReticle()+ assertEquals(5.0, vm.ar.value.distanceM)+ assertEquals(5.0, vm.ar.value.totalDistanceM)+ }++ @Test fun placementIsRefusedWithoutASolidHit() {+ val vm = readyVm()+ vm.placeAtReticle() // Searching: no hit, no anchor, no crash.+ assertTrue(vm.ar.value.anchors.isEmpty())++ // Limited tracking must never place, even with a hit in hand.+ vm.onTrackingUpdate(TrackingQuality.Limited, hasPlane = true)+ vm.onReticleHit(HitCandidate(HitKind.FeaturePoint, Vec3(1.0, 0.0, 0.0), 1.0))+ assertIs<ArFlowState.Scanning>(vm.ar.value.flowState)+ vm.placeAtReticle()+ assertTrue(vm.ar.value.anchors.isEmpty())+ }++ @Test fun anchorsAreRemovableIndividually() {+ val vm = readyVm()+ vm.addResolvedAnchor(0.0, 0.0, 0.0, onPlane = true)+ vm.addResolvedAnchor(1.0, 0.0, 0.0, onPlane = true)+ vm.addResolvedAnchor(2.0, 0.0, 0.0, onPlane = true)+ val middle = vm.ar.value.anchors[1]+ vm.removeAnchor(middle.id)+ assertEquals(2, vm.ar.value.anchors.size)+ assertEquals(2.0, vm.ar.value.distanceM) // remaining points are 2 m apart+ assertNull(vm.ar.value.areaM2)+ }+}