# AR distance measurement and clearance check

Use `io.github.sceneview:arsceneview:4.76.0` in an Android Compose app. Follow
the [Android setup](../quickstart.md) for the toolchain and AR manifest. These
examples use the rear camera on an ARCore-supported device. Camera permission,
ARCore availability and session lifecycle are handled by `ARSceneView`.

## Measure between two taps

Tap two detected surfaces. Anchor poses can refine as tracking improves, so read
their positions again on each session update. Hide the tape while tracking is lost.

```kotlin
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.google.ar.core.Anchor
import com.google.ar.core.Config
import com.google.ar.core.Frame
import com.google.ar.core.TrackingState
import dev.romainguy.kotlin.math.length
import io.github.sceneview.ar.ARSceneView
import io.github.sceneview.ar.arcore.createAnchorOrNull
import io.github.sceneview.ar.arcore.isValid
import io.github.sceneview.ar.arcore.position
import io.github.sceneview.ar.rememberARCameraNode
import io.github.sceneview.math.Position
import io.github.sceneview.rememberEngine
import io.github.sceneview.rememberMaterialLoader
import io.github.sceneview.rememberOnGestureListener

@Composable
fun DistanceMeasureScreen() {
    val engine = rememberEngine()
    val materialLoader = rememberMaterialLoader(engine)
    val cameraNode = rememberARCameraNode(engine)
    val anchors = remember { mutableStateListOf<Anchor>() }
    var latestFrame by remember { mutableStateOf<Frame?>(null) }
    var points by remember { mutableStateOf<List<Position>>(emptyList()) }
    val tapeMaterial = remember(materialLoader) {
        materialLoader.createUnlitColorInstance(Color(0xFF00C853))
    }

    Box(Modifier.fillMaxSize()) {
        ARSceneView(
            modifier = Modifier.fillMaxSize(),
            engine = engine,
            materialLoader = materialLoader,
            cameraNode = cameraNode,
            planeFindingMode = Config.PlaneFindingMode.HORIZONTAL_AND_VERTICAL,
            onSessionCreated = {
                anchors.clear()
                points = emptyList()
                latestFrame = null
            },
            onSessionUpdated = { _, frame ->
                val tracking = frame.camera.trackingState == TrackingState.TRACKING
                latestFrame = frame.takeIf { tracking }
                points = if (tracking && anchors.all {
                    it.trackingState == TrackingState.TRACKING
                }) anchors.map { it.pose.position } else emptyList()
            },
            onGestureListener = rememberOnGestureListener(
                onSingleTapConfirmed = { event, _ ->
                    if (anchors.size < 2) {
                        latestFrame?.hitTest(event)?.firstOrNull {
                            it.isValid(point = false, depthPoint = false,
                                instantPlacementPoint = false, planePoseInPolygon = true)
                        }?.createAnchorOrNull()?.let { anchors.add(it) }
                    }
                }
            ),
        ) {
            anchors.forEach { anchor ->
                key(anchor) {
                    AnchorNode(anchor = anchor) {
                        SphereNode(radius = 0.012f, materialInstance = tapeMaterial)
                    }
                }
            }
            if (points.size == 2) {
                val start = points[0]
                val end = points[1]
                val distance = length(end - start)
                if (distance > 0.001f) {
                    TubeNode(points = listOf(start, end), radius = 0.004f,
                        materialInstance = tapeMaterial)
                    TextNode(
                        text = "%.2f m".format(distance),
                        position = (start + end) * 0.5f + Position(0f, 0.06f, 0f),
                        widthMeters = 0.28f,
                        heightMeters = 0.09f,
                        cameraPositionProvider = { cameraNode.worldPosition },
                    )
                }
            }
        }
        Button(
            onClick = { anchors.clear(); points = emptyList() },
            modifier = Modifier.align(Alignment.BottomCenter).padding(24.dp),
        ) { Text("Clear") }
    }
}
```

`AnchorNode` owns its anchor and detaches it when removed from composition;
clearing the state removes both pins. `materialLoader` owns the remembered material.
`TubeNode` gives the tape a visible radius in metres. Keep measurements short and
check them against a physical ruler: tracking drift and imperfect surface hits
affect the result.

## Check a known-size volume against a detected surface

This procedural box is 2.10 m wide, 0.85 m high and 0.92 m deep. Its bottom is at
local Y = 0. Scaling is disabled to preserve those dimensions after the entrance
animation. The callback tests the rendered box's complete world transform, so the
verdict follows dragging, rotation and changes to the tracked polygon.

```kotlin
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.google.ar.core.TrackingState
import io.github.sceneview.DimensionMarks
import io.github.sceneview.ar.AutoPlacementNode
import io.github.sceneview.ar.AutoPlacementScene
import io.github.sceneview.ar.PlacementBoundsFit
import io.github.sceneview.ar.placementBoundsFit
import io.github.sceneview.ar.rememberAutoPlacementState
import io.github.sceneview.material.setColor
import io.github.sceneview.math.Position
import io.github.sceneview.math.Size
import io.github.sceneview.rememberEngine
import io.github.sceneview.rememberMaterialLoader
import com.google.android.filament.Box as FilamentBox

@Composable
fun SurfaceClearanceScreen() {
    val engine = rememberEngine()
    val materials = rememberMaterialLoader(engine)
    val state = rememberAutoPlacementState()
    SideEffect { state.allowsScaling = false }
    val size = remember { Size(2.10f, 0.85f, 0.92f) }
    val bounds = remember(size) {
        FilamentBox(floatArrayOf(0f, size.y / 2f, 0f),
            floatArrayOf(size.x / 2f, size.y / 2f, size.z / 2f))
    }
    val color = Color(0x552979FF)
    val material = remember(materials) { materials.createColorInstance(color) }
    var fit by remember { mutableStateOf<PlacementBoundsFit?>(null) }

    Box(Modifier.fillMaxSize()) {
        AutoPlacementScene(
            assetReady = true,
            modifier = Modifier.fillMaxSize(),
            state = state,
            engine = engine,
            materialLoader = materials,
        ) { placement ->
            key(placement) {
                AutoPlacementNode(placement = placement, state = state, size = size) { opacity ->
                    SideEffect { material.setColor(color.copy(alpha = color.alpha * opacity)) }
                    CubeNode(
                        size = size,
                        center = Position(0f, size.y / 2f, 0f),
                        materialInstance = material,
                        apply = {
                            isEditable = true
                            isPositionEditable = false
                            isRotationEditable = false
                            isScaleEditable = false
                            onFrame = {
                                fit = if (placement.anchor.trackingState == TrackingState.TRACKING) {
                                    placement.planeOrNull?.placementBoundsFit(bounds, worldTransform)
                                } else null
                            }
                        },
                    )
                    DimensionMarks(size = size, format = { "%.0f cm".format(it * 100f) })
                }
            }
        }
        val verdict = if (state.hasPlacement) fit else null
        Text(
            text = when {
                verdict == null -> "Surface clearance unknown"
                verdict.fits -> "Rendered footprint fits tracked area (%.0f cm margin)"
                    .format(verdict.marginMeters * 100f)
                else -> "Rendered footprint extends beyond tracked area"
            },
            modifier = Modifier.align(Alignment.TopCenter).padding(top = 48.dp),
            color = Color.White,
        )
    }
}
```

The entrance animation briefly grows the box to its full dimensions; the label
describes the **rendered footprint**, including that animation.
`placementBoundsFit` projects all eight box corners onto the plane polygon. Its
signed margin measures clearance to the polygon edges; `null` means no usable
verdict. A negative result can mean the scan is incomplete. This is a surface
coverage check: it does not test ceiling height, obstacles, structural support or
whether an object can pass through a doorway. `DimensionMarks` displays the supplied
dimensions; it does not measure the room.

For a GLB at its authored size, see [native AR product placement](native-ar-product-placement.md).

Source patterns: [ARMeasureDemo.kt](https://github.com/sceneview/sceneview/blob/v4.76.0/samples/android-demo/src/main/java/io/github/sceneview/demo/demos/ARMeasureDemo.kt),
[AutoPlacementScene.kt](https://github.com/sceneview/sceneview/blob/v4.76.0/arsceneview/src/main/java/io/github/sceneview/ar/AutoPlacementScene.kt)
and [PlacementBoundsFit.kt](https://github.com/sceneview/sceneview/blob/v4.76.0/arsceneview/src/main/java/io/github/sceneview/ar/PlacementBoundsFit.kt).
Verified by source inspection at 4.76.0; these snippets were not compiled or run on a device.
