diff --git a/CoreScopeViewer/Features/FieldTools/FieldToolsScreen.swift b/CoreScopeViewer/Features/FieldTools/FieldToolsScreen.swift index 32a1da99..70fd374b 100644 --- a/CoreScopeViewer/Features/FieldTools/FieldToolsScreen.swift +++ b/CoreScopeViewer/Features/FieldTools/FieldToolsScreen.swift @@ -571,6 +571,9 @@ struct FieldToolsScreen: View { NodeVisionScreen(name: target.name, target: coordinate, repeaterKey: { if case .node(let node) = target { return node.publicKey } return nil + }(), role: { + if case .node(let node) = target { return node.role } + return nil }()) } } diff --git a/CoreScopeViewer/Features/NodeDetail/NodeDetailScreen.swift b/CoreScopeViewer/Features/NodeDetail/NodeDetailScreen.swift index 778947a0..3a8b258e 100644 --- a/CoreScopeViewer/Features/NodeDetail/NodeDetailScreen.swift +++ b/CoreScopeViewer/Features/NodeDetail/NodeDetailScreen.swift @@ -76,7 +76,7 @@ struct NodeDetailScreen: View { let item = FieldCatalogItem.node(displayedNode) if let coordinate = item.coordinate { NodeVisionScreen(name: item.name, target: coordinate, - repeaterKey: displayedNode.publicKey) + repeaterKey: displayedNode.publicKey, role: displayedNode.role) } } diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index 532f6e5b..40ab8e52 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -6,6 +6,7 @@ struct NodeVisionScreen: View { private let initialName: String? private let initialTarget: FieldCoordinate? private let initialRepeaterKey: String? + private let initialRole: String? private let catalog: [MeshNode] private let discoveryRegion: String? private let catalogIsLoading: Bool @@ -32,11 +33,12 @@ struct NodeVisionScreen: View { @State private var showsDiagnostics = false #endif - init(name: String? = nil, target: FieldCoordinate? = nil, repeaterKey: String? = nil, catalog: [MeshNode] = [], discoveryRegion: String? = nil, + init(name: String? = nil, target: FieldCoordinate? = nil, repeaterKey: String? = nil, role: String? = nil, catalog: [MeshNode] = [], discoveryRegion: String? = nil, catalogIsLoading: Bool = false) { initialName = name initialTarget = target initialRepeaterKey = repeaterKey + initialRole = role self.catalog = catalog self.discoveryRegion = discoveryRegion self.catalogIsLoading = catalogIsLoading @@ -47,12 +49,35 @@ struct NodeVisionScreen: View { private var target: FieldCoordinate? { focusedNode.flatMap { FieldCatalogItem.node($0).coordinate } ?? initialTarget } private var repeaterKey: String? { focusedNode?.publicKey ?? initialRepeaterKey } @Environment(AnalyzerSettings.self) private var settings - @State private var antennaElevation: Double? + @State private var displayedAltitude: Double? + @State private var ground: [VisionTerrainPoint: Double] = [:] + @State private var terrain = VisionTerrainCache(provider: OpenMeteoElevationProvider()) + + private var spotlightPoint: VisionTerrainPoint? { + target.flatMap { VisionTerrainPoint(key: repeaterKey ?? "", coordinate: $0) } + } + + private var terrainPoints: Set { + var points = Set(nearbyNodes.compactMap { terrainPoint(for: $0.node) }) + if let spotlightPoint { points.insert(spotlightPoint) } + return points + } + + private func terrainPoint(for node: MeshNode) -> VisionTerrainPoint? { + FieldCatalogItem.node(node).coordinate.flatMap { VisionTerrainPoint(key: node.publicKey, coordinate: $0) } + } + + private var spotlightHeight: VisionAntennaHeight { + VisionAntennaHeight(role: focusedNode?.role ?? initialRole, reported: installHeight) + } + + private var antennaElevation: Double? { + spotlightPoint.flatMap { ground[$0] }.map { $0 + spotlightHeight.meters } + } @State private var installHeight: Double? @State private var targetStatus: String? @State private var verticalArrowShown = false @State private var bottomOverlayHeight: CGFloat = 0 - @State private var elevationProvider = OpenMeteoElevationProvider() @Environment(\.isHingedDevice) private var isHingedDevice @Environment(\.colorScheme) private var colorScheme @Environment(\.dismiss) private var dismiss @@ -103,7 +128,9 @@ struct NodeVisionScreen: View { VStack(alignment: .leading, spacing: 16) { Text("The compass shows where the camera is pointing. Markers show node names and distances from you. Smaller markers follow the node’s direction and may stagger vertically to keep labels readable.") Text("Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view.") - Text("When enough elevation data is available, NodeVision uses it to place the focused marker vertically. “Elevation Uncertain” means its height on screen is a rough guide.") + Text("When your phone’s altitude is missing or too uncertain, markers show which way to turn. Their height on screen doesn’t indicate whether a node is above or below you.") + Text("When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dashed outline marks an approximate placement based on a default height or a less precise phone altitude.") + markerStylePreview Divider() VStack(alignment: .leading, spacing: 8) { Label("Location privacy", systemImage: "info.circle") @@ -193,22 +220,20 @@ struct NodeVisionScreen: View { if backend.sourceSession.isCurrent, !Task.isCancelled { repeaterMetadata = metadata } } .task(id: "\(settings.sourceSession.id)|\(repeaterKey ?? "")") { - antennaElevation = nil installHeight = nil targetStatus = nil - guard let repeaterKey, let target, settings.sourceIsReady else { return } + guard let repeaterKey, settings.sourceIsReady else { return } let backend = AnalyzerBackendFactory.make(settings: settings) let metadata = await FieldCatalogRepository.shared.repeaterMetadata(for: backend) guard backend.sourceSession.isCurrent, !Task.isCancelled else { return } let reported = metadata[repeaterKey] targetStatus = reported?.status - guard let height = reported?.applicableHeightMeters(), - let point = try? NodePlannerCoordinate(latitude: target.latitude, longitude: target.longitude) else { return } - installHeight = height - let terrain = try? await elevationProvider.elevations(for: [point, point]) - guard backend.sourceSession.isCurrent, !Task.isCancelled, - let ground = terrain?.samples.first?.elevationMeters else { return } - antennaElevation = ground + height + installHeight = reported?.applicableHeightMeters() + } + .task(id: terrainPoints) { + let resolved = await terrain.resolve(terrainPoints) + guard !Task.isCancelled else { return } + ground = resolved } .task(id: needsLocation) { if needsLocation { location.start() } else { location.stop() } @@ -238,7 +263,13 @@ struct NodeVisionScreen: View { regionalCatalog.configure(settings: settings) await regionalCatalog.loadNodes(region: discoveryRegion) } - .onChange(of: discoveryCatalog) { refreshDiscoveryNodes() } + .onChange(of: discoveryCatalog) { + if let key = focusedNode?.publicKey, + let updated = discoveryCatalog.first(where: { $0.publicKey == key }) { + focusedNode = updated + } + refreshDiscoveryNodes() + } .onChange(of: repeaterMetadata.reportedStatuses) { refreshDiscoveryNodes() } .onChange(of: showsLiveCamera && cameraAvailable, initial: true) { _, keepsScreenAwake in if keepsScreenAwake { @@ -324,23 +355,32 @@ struct NodeVisionScreen: View { } } } - let markerWidth = min(192, max(0, pane.size.width - 32)) + let markerTier = Self.markerTier(distance: geometry?.distanceMeters ?? 0) + let markerWidth = min(Self.markerWidth(tier: markerTier), + max(0, pane.size.width - 32)) let edge = max(0, pane.size.width / 2 - markerWidth / 2 - 8) let offscreen = offset.map { abs($0 * pane.size.width / 2) > max(0, edge + (arrowShown ? -6 : 6)) } ?? false let showSettings = location.status == .denied || AVCaptureDevice.authorizationStatus(for: .video) == .denied let truncatedName = fullNameHeight > markerNameHeight + 1 + let nearDistance = max(5, fix?.horizontalAccuracyMeters ?? 0) + let distances = nearbyNodes.map(\.geometry.distanceMeters) + [geometry?.distanceMeters].compactMap { $0 } + let closestDistance = distances.filter { $0 > nearDistance }.min() + let altitude = stableVisionAltitude(previous: displayedAltitude, current: fix?.altitudeMeters, + distance: closestDistance) + let mode = VisionElevationMode(altitude: altitude, accuracy: fix?.verticalAccuracyMeters, + distances: distances, nearDistance: nearDistance) let placement = markerHeight(size: pane.size, insets: insets, distance: geometry?.distanceMeters, - fix: fix, pitch: heading?.pitchDegrees) + mode: mode, pitch: heading?.pitchDegrees) let verticalEdge = placement.edge let useVerticalArrow = verticalEdge != nil && (!offscreen || abs(placement.offset ?? 0) > abs(offset ?? 0)) let showsBottomArrow = cameraAvailable && !near && offset != nil && useVerticalArrow && verticalEdge == .below - let markerVisible = cameraAvailable && !near && offset != nil && !offscreen && verticalEdge == nil + let markerVisible = placement.y != nil && cameraAvailable && !near && offset != nil && !offscreen && verticalEdge == nil let discoveryMarkers = discoveryMarkers(size: pane.size, insets: insets, fix: fix, - heading: heading, tangent: tangent, + heading: heading, tangent: tangent, mode: mode, focusedX: markerVisible ? offset.map { pane.size.width * (1 + $0) / 2 } : nil, - focusedY: placement.y, focusedWidth: markerWidth) + focusedY: placement.y ?? 0, focusedWidth: markerWidth) ZStack { Rectangle().fill(.background) if cameraAvailable { @@ -357,9 +397,10 @@ struct NodeVisionScreen: View { } .animation(reduceMotion ? nil : .easeInOut(duration: 0.24), value: Set(discoveryMarkers.map(\.id))) - if cameraAvailable, !near, !showsBottomArrow, let offset { + .id(mode == .guide) + if cameraAvailable, !near, !showsBottomArrow, let offset, placement.y != nil || offscreen { direction(offset, offscreen: offscreen, verticalEdge: useVerticalArrow ? verticalEdge : nil, - markerWidth: markerWidth, markerY: placement.y, estimated: placement.offset != nil, + markerWidth: markerWidth, markerTier: markerTier, markerY: placement.y ?? pane.size.height * 0.43, estimated: mode != .guide, approximate: placement.approximate, size: pane.size, geometry: geometry) } VStack(spacing: 0) { @@ -393,6 +434,14 @@ struct NodeVisionScreen: View { if cameraAvailable, let heading, let tangent { compass(heading: heading.trueHeadingDegrees, tangent: tangent, width: pane.size.width) } + if cameraAvailable, heading != nil, tangent != nil, fix != nil, mode == .guide, + target != nil || !discoveryMarkers.isEmpty { + Text("Phone altitude uncertain") + .font(.caption) + .foregroundStyle(supportingTextColor) + .padding(.horizontal, 16) + .padding(.vertical, 4) + } } .padding(.top, insets.top) .background { @@ -473,7 +522,7 @@ struct NodeVisionScreen: View { if let installHeight { HStack(spacing: 8) { Image(systemName: "arrow.up.and.down") - .foregroundStyle(nodeNameColor) + .foregroundStyle(overlayInk) .accessibilityHidden(true) Text("Reported install height") .foregroundStyle(supportingTextColor) @@ -532,7 +581,7 @@ struct NodeVisionScreen: View { } } .buttonStyle(.bordered) - .tint(nodeNameColor) + .tint(overlayInk) .padding(.bottom, insets.bottom + 8) } } @@ -543,6 +592,7 @@ struct NodeVisionScreen: View { } .clipped() .onChange(of: verticalEdge != nil, initial: true) { _, value in verticalArrowShown = value } + .onChange(of: altitude, initial: true) { displayedAltitude = altitude } } } } @@ -565,10 +615,25 @@ struct NodeVisionScreen: View { }.sorted { ($0.geometry.distanceMeters, $0.node.publicKey) < ($1.geometry.distanceMeters, $1.node.publicKey) } } + private static func markerTier(distance: Double) -> Int { + if distance < 500 { return 0 } + if distance < 2_000 { return 1 } + return 2 + } + + private static func markerWidth(tier: Int) -> CGFloat { + [132, 112, 96][tier] + } + + private static func markerNameFont(tier: Int) -> Font { + .monaspace(tier == 0 ? .subheadline : .caption).weight(.semibold) + } + private struct DiscoveryMarker: Identifiable { let candidate: NearbyNode let x: CGFloat let y: CGFloat + let approximate: Bool let rowOffset: CGFloat let width: CGFloat let tier: Int @@ -577,20 +642,15 @@ struct NodeVisionScreen: View { } private func discoveryMarkers(size: CGSize, insets: EdgeInsets, fix: FieldLocationSample?, - heading: FieldHeadingSample?, tangent: Double?, + heading: FieldHeadingSample?, tangent: Double?, mode: VisionElevationMode, focusedX: CGFloat?, focusedY: CGFloat, focusedWidth: CGFloat) -> [DiscoveryMarker] { guard isDiscovery, cameraAvailable, let fix, let heading, let tangent, tangent > 0, let pitch = heading.pitchDegrees, let verticalTangent = optics?.halfHeightTangent(size), verticalTangent > 0 else { return [] } - let minY = insets.top + 130 + let minY = insets.top + 166 let maxY = size.height - insets.bottom - 100 guard minY < maxY else { return [] } - let vertical = FieldGeometry.cameraBearingGuideOffset(pitch: pitch, halfHeightTangent: verticalTangent) - let y = size.height * (1 - vertical) / 2 - guard (minY...maxY).contains(y) else { return [] } let selectedID = inspectedNode?.publicKey - let rowSpacing: CGFloat = 92 - let rowYs = [y, y + rowSpacing <= maxY ? y + rowSpacing : y - rowSpacing] var occupied: [CGRect] = [] if let focusedX { occupied.append(CGRect(x: focusedX - focusedWidth / 2, y: focusedY - 88, @@ -605,18 +665,29 @@ struct NodeVisionScreen: View { let offset = FieldGeometry.cameraHorizontalOffset(bearing: bearing, heading: heading.trueHeadingDegrees, halfWidthTangent: tangent), abs(offset) < 1 else { return } - let tier = candidate.geometry.distanceMeters < 500 ? 0 : candidate.geometry.distanceMeters < 2_000 ? 1 : 2 - let width: CGFloat = [132, 112, 96][tier] + let tier = Self.markerTier(distance: candidate.geometry.distanceMeters) + let width = Self.markerWidth(tier: tier) let x = size.width * CGFloat(1 + offset) / 2 let left = x - width / 2 - 5 let paddedWidth = width + 10 guard left >= insets.leading, left + paddedWidth <= size.width - insets.trailing else { return } - // Stagger labels vertically without changing the projected bearing. - for rowY in rowYs where rowY >= minY { + let height = VisionAntennaHeight(role: candidate.node.role, + reported: repeaterMetadata[candidate.node.publicKey]?.applicableHeightMeters()) + let antenna = terrainPoint(for: candidate.node).flatMap { ground[$0] }.map { $0 + height.meters } + let distance = candidate.geometry.distanceMeters + guard let vertical = mode.offset(distance: distance, antenna: antenna, pitch: pitch, + tangent: verticalTangent) else { return } + let projectedY = size.height * CGFloat(1 - vertical) / 2 + guard let y = discoveryMarkerY(projectedY: projectedY, paneHeight: size.height, + minimumY: minY, maximumY: maxY) else { return } + let approximate = mode.isApproximate(distance: distance, height: height) + let nudges: [CGFloat] = mode == .guide ? [0, y + 92 <= maxY ? 92 : -92] : [0, 24, -24, 48, -48, 72, -72, 92, -92] + for nudge in nudges { + let rowY = min(max(y + nudge, minY), maxY) let bounds = CGRect(x: left, y: rowY - 84, width: paddedWidth, height: 88) guard !occupied.contains(where: { $0.intersects(bounds) }) else { continue } occupied.append(bounds) - markers.append(DiscoveryMarker(candidate: candidate, x: x, y: y, + markers.append(DiscoveryMarker(candidate: candidate, x: x, y: y, approximate: approximate, rowOffset: rowY - y, width: width, tier: tier)) break } @@ -638,7 +709,7 @@ struct NodeVisionScreen: View { } label: { VStack(spacing: 2) { Text(FieldCatalogItem.node(node).name) - .font(.monaspace(marker.tier == 0 ? .subheadline : .caption).weight(.semibold)) + .font(Self.markerNameFont(tier: marker.tier)) .foregroundStyle(nodeNameColor) .lineLimit(2) distance(marker.candidate.geometry, style: .caption2) @@ -649,12 +720,8 @@ struct NodeVisionScreen: View { .frame(width: marker.width) .frame(minHeight: 44) .padding(.bottom, 9) - .background { overlaySurface(NodeVisionMarkerShape()) } - .overlay { - if selected { NodeVisionMarkerShape().stroke(nodeNameColor, lineWidth: 2) } - } + .background { markerSurface(approximate: marker.approximate, emphasized: selected) } .contentShape(Rectangle()) - .opacity(marker.tier == 2 && !selected ? 0.90 : 1) } .buttonStyle(.plain) .accessibilityAddTraits(selected ? .isSelected : []) @@ -679,11 +746,13 @@ struct NodeVisionScreen: View { } } label: { HStack { - Text(item.name).font(.monaspace(.subheadline).weight(.semibold)) + Text(item.name) + .font(.monaspace(.subheadline).weight(.semibold)) + .foregroundStyle(nodeNameColor) Spacer(minLength: 10) Image(systemName: expandsInspection ? "chevron.down" : "chevron.up") } - .foregroundStyle(nodeNameColor) + .foregroundStyle(overlayInk) .frame(minHeight: 44) .contentShape(Rectangle()) } @@ -770,6 +839,10 @@ struct NodeVisionScreen: View { } private var nodeNameColor: Color { + colorScheme == .dark ? overlayInk.mix(with: .white, by: 0.55) : overlayInk + } + + private var overlayInk: Color { colorScheme == .dark ? NodeScopeStyle.signal : NodeScopeStyle.signal.mix(with: NodeScopeStyle.deepNavy, by: 0.45) @@ -800,18 +873,58 @@ struct NodeVisionScreen: View { .contentShape(Capsule()) } .buttonStyle(.plain) - .foregroundStyle(nodeNameColor) + .foregroundStyle(overlayInk) + } + + private var markerStylePreview: some View { + ViewThatFits(in: .horizontal) { + HStack(alignment: .top, spacing: 24) { + markerStyleExample("Higher-confidence elevation", approximate: false) + markerStyleExample("Approx. elevation", approximate: true) + } + .fixedSize(horizontal: true, vertical: false) + + VStack(alignment: .leading, spacing: 12) { + markerStyleExample("Higher-confidence elevation", approximate: false) + markerStyleExample("Approx. elevation", approximate: true) + } + } + } + + private func markerStyleExample(_ label: LocalizedStringKey, approximate: Bool) -> some View { + HStack(spacing: 10) { + markerSurface(approximate: approximate, emphasized: false) + .frame(width: 38, height: 28) + .accessibilityHidden(true) + Text(label) + .font(.caption) + .fixedSize(horizontal: false, vertical: true) + } + } + + private func markerSurface(approximate: Bool, emphasized: Bool, spotlight: Bool = false) -> some View { + let shape = NodeVisionMarkerShape() + let width: CGFloat = emphasized ? 3 : 2 + let borderColor = spotlight ? NodeScopeStyle.activity : overlayInk + let backing = colorScheme == .dark ? NodeScopeStyle.deepNavy : Color(uiColor: .systemBackground) + return overlaySurface(shape, drawsBorder: false) + .overlay { shape.stroke(backing, lineWidth: width + 2) } + .overlay { + shape.stroke(borderColor, style: StrokeStyle( + lineWidth: width, lineCap: .round, lineJoin: .round, dash: approximate ? [7, 6] : [])) + } } - private func overlaySurface(_ shape: S, pinned: Bool = false) -> some View { + private func overlaySurface(_ shape: S, drawsBorder: Bool = true) -> some View { return shape.fill(.regularMaterial) .overlay { shape.fill(colorScheme == .light ? Color(uiColor: .systemBackground).opacity(0.85) : .clear) } .overlay { shape.fill(overlayGradient) } .overlay { - shape.stroke(pinned ? NodeScopeStyle.activity : NodeScopeStyle.signal.opacity(0.4), - lineWidth: pinned ? (colorScheme == .light ? 2 : 1.5) : 1) + if drawsBorder { + shape.stroke(NodeScopeStyle.signal.opacity(0.4), lineWidth: 1) + } } .shadow(color: .black.opacity(0.24), radius: 5, x: 0, y: 2) } @@ -849,31 +962,21 @@ struct NodeVisionScreen: View { } private func markerHeight(size: CGSize, insets: EdgeInsets, distance: Double?, - fix: FieldLocationSample?, pitch: Double?) -> (y: CGFloat, approximate: Bool, decision: String, offset: Double?, edge: VerticalEdge?) { + mode: VisionElevationMode, pitch: Double?) -> (y: CGFloat?, approximate: Bool, decision: String, offset: Double?, edge: VerticalEdge?) { let fallback = size.height * 0.43 + let modeName = mode == .guide ? "All markers: pitch guide" : "All markers: elevation" guard let pitch, let tangent = optics?.halfHeightTangent(size), tangent > 0 else { - return (fallback, false, "Guide: waiting for pitch or camera", nil, nil) + return (nil, false, modeName + " · waiting for pitch or camera", nil, nil) } - let estimatedOffset: Double? - let decision: String - var approximate = false - if let distance, let antennaElevation, let altitude = fix?.altitudeMeters, - let accuracy = fix?.verticalAccuracyMeters { - estimatedOffset = FieldGeometry.cameraVerticalOffset( - distance: distance, antennaElevation: antennaElevation, phoneElevation: altitude, - phoneAccuracy: accuracy, pitch: pitch, halfHeightTangent: tangent - ) - let uncertainty = FieldGeometry.cameraElevationUncertainty(distance: distance, phoneAccuracy: accuracy) - approximate = estimatedOffset != nil && uncertainty > 8 - decision = estimatedOffset == nil ? "Guide: accuracy or viewing angle" : approximate ? "Approximate estimate" : "Elevation estimate" - } else { - estimatedOffset = nil - decision = antennaElevation == nil ? "Guide: antenna elevation unavailable" : "Guide: phone altitude unavailable" + guard let distance, let offset = mode.offset(distance: distance, antenna: antennaElevation, + pitch: pitch, tangent: tangent) else { + return (nil, false, modeName + " · spotlight unplaced", nil, nil) } - let offset = estimatedOffset ?? FieldGeometry.cameraBearingGuideOffset(pitch: pitch, halfHeightTangent: tangent) + let approximate = mode.isApproximate(distance: distance, height: spotlightHeight) + let estimatedOffset = mode == .guide ? nil : offset let minimumY = insets.top + 166 let maximumY = size.height - insets.bottom - 100 - guard maximumY >= minimumY else { return (fallback, false, "Guide: short viewfinder", nil, nil) } + guard maximumY >= minimumY else { return (fallback, approximate, modeName + " · short viewfinder", nil, nil) } let projectedY = size.height * (1 - offset) / 2 let buffer: CGFloat = verticalArrowShown ? -6 : 6 let edge: VerticalEdge? @@ -881,7 +984,7 @@ struct NodeVisionScreen: View { else if projectedY < minimumY - buffer { edge = .above } else if projectedY > maximumY + buffer { edge = .below } else { edge = nil } - return (min(max(projectedY, minimumY), maximumY), approximate, decision, estimatedOffset, edge) + return (min(max(projectedY, minimumY), maximumY), approximate, modeName, estimatedOffset, edge) } #if DEBUG @@ -908,7 +1011,7 @@ struct NodeVisionScreen: View { .accessibilityLabel(edge == .above ? "Target above the view" : "Target below the view") } - private func direction(_ offset: Double, offscreen: Bool, verticalEdge: VerticalEdge?, markerWidth: CGFloat, + private func direction(_ offset: Double, offscreen: Bool, verticalEdge: VerticalEdge?, markerWidth: CGFloat, markerTier: Int, markerY: CGFloat, estimated: Bool, approximate: Bool, size: CGSize, geometry: FieldGeometryResult?) -> some View { let pixel = offset * size.width / 2 @@ -940,23 +1043,19 @@ struct NodeVisionScreen: View { .hidden() .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { fullNameHeight = $0 } } - .font(.monaspace(.subheadline).weight(.semibold)) + .font(Self.markerNameFont(tier: markerTier)) .foregroundStyle(nodeNameColor) - if let geometry { distance(geometry, style: .caption) } + if let geometry { distance(geometry, style: .caption2) } if approximate { Text("Approx. elevation").font(.caption2).foregroundStyle(supportingTextColor) - } else if !estimated { - Label("Elevation Uncertain", systemImage: "arrow.left.and.right") - .font(.caption2).foregroundStyle(supportingTextColor) - .accessibilityLabel("Elevation Uncertain. Use the marker for left or right direction.") } } .multilineTextAlignment(.center) - .padding(.horizontal, 9) - .padding(.vertical, 5) - .frame(maxWidth: markerWidth) + .padding(.horizontal, 6) + .padding(.vertical, 4) + .frame(width: markerWidth) .padding(.bottom, 9) - .background { overlaySurface(NodeVisionMarkerShape(), pinned: true) } + .background { markerSurface(approximate: approximate, emphasized: true, spotlight: true) } } .frame(width: markerWidth, height: 88, alignment: .bottom) .position(x: size.width / 2 + pixel, y: markerY - 44) @@ -1088,3 +1187,111 @@ private struct NodeVisionPreview: UIViewRepresentable { } } } + + +struct VisionAntennaHeight { + let meters: Double + let approximate: Bool + + init(role: String?, reported: Double?) { + let role = role == "room-server" ? GlossaryTerm.roomServer : role.flatMap { GlossaryTerm(role: $0) } + let reported = role == .repeater ? reported : nil + let preset: CoverageHeightPreset = role == .repeater || role == .roomServer ? .rooftop : .handheld + meters = reported ?? preset.meters + approximate = reported == nil + } +} + +enum VisionElevationMode: Equatable { + case guide + case elevation(altitude: Double, accuracy: Double) + + init(altitude: Double?, accuracy: Double?, distances: [Double], nearDistance: Double) { + guard let altitude, altitude.isFinite, let accuracy, accuracy.isFinite, accuracy > 0, + distances.filter({ $0 > nearDistance }).allSatisfy({ + FieldGeometry.cameraElevationUncertainty(distance: $0, phoneAccuracy: accuracy) <= 30 + }) else { + self = .guide + return + } + self = .elevation(altitude: altitude, accuracy: accuracy) + } + + func offset(distance: Double, antenna: Double?, pitch: Double, tangent: Double) -> Double? { + switch self { + case .guide: + FieldGeometry.cameraBearingGuideOffset(pitch: pitch, halfHeightTangent: tangent) + case let .elevation(altitude, accuracy): + antenna.flatMap { + FieldGeometry.cameraVerticalOffset(distance: distance, antennaElevation: $0, phoneElevation: altitude, + phoneAccuracy: accuracy, pitch: pitch, halfHeightTangent: tangent, clampAngle: true) + } + } + } + + func isApproximate(distance: Double, height: VisionAntennaHeight) -> Bool { + guard case let .elevation(_, accuracy) = self else { return false } + return height.approximate || FieldGeometry.cameraElevationUncertainty(distance: distance, phoneAccuracy: accuracy) > 8 + } +} + +struct VisionTerrainPoint: Hashable, Sendable { + let key: String + let coordinate: NodePlannerCoordinate + + init?(key: String, coordinate: FieldCoordinate) { + guard let point = try? NodePlannerCoordinate(latitude: coordinate.latitude, longitude: coordinate.longitude) + else { return nil } + self.key = key.lowercased() + self.coordinate = point + } +} + +actor VisionTerrainCache { + private let provider: any NodePlannerElevationProviding + private var elevations: [VisionTerrainPoint: Double] = [:] + private var attempted: Set = [] + + init(provider: any NodePlannerElevationProviding) { + self.provider = provider + } + + func resolve(_ points: Set) async -> [VisionTerrainPoint: Double] { + let missing = points.subtracting(attempted).sorted { + ($0.key, $0.coordinate.latitude, $0.coordinate.longitude) < + ($1.key, $1.coordinate.latitude, $1.coordinate.longitude) + } + for start in stride(from: 0, to: missing.count, by: OpenMeteoElevationProvider.maximumBatchSize) { + guard !Task.isCancelled else { break } + let batch = missing[start.. = [] + let coordinates = batch.map(\.coordinate).filter { seen.insert($0).inserted } + let request = coordinates.count == 1 ? coordinates + coordinates : coordinates + let profile = try? await provider.elevations(for: request) + guard !Task.isCancelled else { break } + attempted.formUnion(batch) + guard let profile else { continue } + var ground: [NodePlannerCoordinate: Double] = [:] + for sample in profile.samples where sample.elevationMeters.isFinite { + ground[sample.coordinate] = sample.elevationMeters + } + for point in batch { + elevations[point] = ground[point.coordinate] + } + } + return elevations + } +} + +/// Ignore altitude changes that move even the closest eligible marker less than 0.15°. +func stableVisionAltitude(previous: Double?, current: Double?, distance: Double?) -> Double? { + guard let current, current.isFinite else { return nil } + guard let previous, let distance else { return current } + return atan2(abs(current - previous), distance) < 0.15 * .pi / 180 ? previous : current +} + +/// Clamp to the label-safe area while the node is in or just outside the viewfinder. +func discoveryMarkerY(projectedY: CGFloat, paneHeight: CGFloat, minimumY: CGFloat, maximumY: CGFloat) -> CGFloat? { + guard (-24...(paneHeight + 24)).contains(projectedY) else { return nil } + return min(max(projectedY, minimumY), maximumY) +} diff --git a/CoreScopeViewer/Models/FieldGeometry.swift b/CoreScopeViewer/Models/FieldGeometry.swift index ad79725f..6d2809ac 100644 --- a/CoreScopeViewer/Models/FieldGeometry.swift +++ b/CoreScopeViewer/Models/FieldGeometry.swift @@ -147,15 +147,15 @@ enum FieldGeometry { /// Project a height estimate only when combined vertical uncertainty is small enough to be useful. static func cameraVerticalOffset( distance: Double, antennaElevation: Double, phoneElevation: Double, - phoneAccuracy: Double, pitch: Double, halfHeightTangent: Double + phoneAccuracy: Double, pitch: Double, halfHeightTangent: Double, clampAngle: Bool = false ) -> Double? { guard [distance, antennaElevation, phoneElevation, phoneAccuracy, pitch, halfHeightTangent].allSatisfy(\.isFinite), distance > 0, phoneAccuracy > 0, halfHeightTangent > 0, cameraElevationUncertainty(distance: distance, phoneAccuracy: phoneAccuracy) <= 30 else { return nil } let curvature = distance * distance / (2 * earthRadiusMeters) let angle = atan2(antennaElevation - phoneElevation - curvature, distance).degrees - pitch - guard abs(angle) < 89 else { return nil } - return tan(angle.radians) / halfHeightTangent + guard clampAngle || abs(angle) < 89 else { return nil } + return tan(min(max(angle, -89), 89).radians) / halfHeightTangent } /// Core Motion true-north coordinates are X north, Y west, Z up. diff --git a/CoreScopeViewer/Resources/Localizable.xcstrings b/CoreScopeViewer/Resources/Localizable.xcstrings index b462b88d..02c01b85 100644 --- a/CoreScopeViewer/Resources/Localizable.xcstrings +++ b/CoreScopeViewer/Resources/Localizable.xcstrings @@ -13620,6 +13620,22 @@ } } }, + "Higher-confidence elevation" : { + "localizations" : { + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Elevación de mayor confianza" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "Elevação mais confiável" + } + } + } + }, "Highlights in version %@" : { "localizations" : { "es" : { @@ -21575,6 +21591,22 @@ } } }, + "Phone altitude uncertain" : { + "localizations" : { + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Altitud del teléfono incierta" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "Altitude do celular incerta" + } + } + } + }, "Place a transmitter to find nearby known nodes." : { "localizations" : { "es" : { @@ -33013,18 +33045,34 @@ } } }, - "When enough elevation data is available, NodeVision uses it to place the focused marker vertically. “Elevation Uncertain” means its height on screen is a rough guide." : { + "When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dashed outline marks an approximate placement based on a default height or a less precise phone altitude." : { + "localizations" : { + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano. Un contorno discontinuo indica una posición aproximada basada en una altura predeterminada o en una altitud del teléfono menos precisa." + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil. Um contorno tracejado indica uma posição aproximada baseada em uma altura padrão ou em uma altitude do celular menos precisa." + } + } + } + }, + "When your phone’s altitude is missing or too uncertain, markers show which way to turn. Their height on screen doesn’t indicate whether a node is above or below you." : { "localizations" : { "es" : { "stringUnit" : { "state" : "translated", - "value" : "Cuando hay suficientes datos de elevación, NodeVision los usa para colocar el marcador destacado en el eje vertical. «Elevación incierta» significa que su altura en pantalla es orientativa." + "value" : "Cuando no se dispone de la altitud del teléfono o es demasiado imprecisa, los marcadores indican hacia dónde girar. Su altura en pantalla no indica si un nodo está por encima o por debajo de ti." } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "Quando há dados de elevação suficientes, o NodeVision os usa para posicionar o marcador destacado na vertical. “Elevação incerta” indica que a altura na tela é apenas uma referência." + "value" : "Quando a altitude do celular está indisponível ou é imprecisa demais, os marcadores mostram para onde virar. A altura deles na tela não indica se um nó está acima ou abaixo de você." } } } diff --git a/CoreScopeViewerTests/FieldGeometryTests.swift b/CoreScopeViewerTests/FieldGeometryTests.swift index 2f4e98b1..60d73204 100644 --- a/CoreScopeViewerTests/FieldGeometryTests.swift +++ b/CoreScopeViewerTests/FieldGeometryTests.swift @@ -1,3 +1,4 @@ +import Foundation import simd import Testing @testable import CoreScopeViewer @@ -160,3 +161,79 @@ struct FieldGeometryTests { #expect(FieldGeometry.deviceAxesUseMatrixRows(rows: turned, gravity: SIMD3(0, 0, -1)) == nil) } } + + +struct NodeVisionElevationTests { + @Test func discoveryMarkersLeaveTheEdgesWhenTiltedFartherAway() { + #expect(discoveryMarkerY(projectedY: -24, paneHeight: 800, minimumY: 166, maximumY: 700) == 166) + #expect(discoveryMarkerY(projectedY: 824, paneHeight: 800, minimumY: 166, maximumY: 700) == 700) + #expect(discoveryMarkerY(projectedY: -25, paneHeight: 800, minimumY: 166, maximumY: 700) == nil) + #expect(discoveryMarkerY(projectedY: 825, paneHeight: 800, minimumY: 166, maximumY: 700) == nil) + } + + @Test func reportedAndDefaultHeights() { + #expect(VisionAntennaHeight(role: "repeater", reported: 12).meters == 12) + #expect(!VisionAntennaHeight(role: "repeater", reported: 12).approximate) + for role in ["repeater", "room", "room-server"] { + #expect(VisionAntennaHeight(role: role, reported: nil).meters == CoverageHeightPreset.rooftop.meters) + #expect(VisionAntennaHeight(role: role, reported: nil).approximate) + } + #expect(VisionAntennaHeight(role: "companion", reported: 12).meters == CoverageHeightPreset.handheld.meters) + } + + @Test func placementModeAppliesToEveryMarker() { + let distances = [30.0, 500] + for mode in [ + VisionElevationMode(altitude: nil, accuracy: 2, distances: distances, nearDistance: 5), + VisionElevationMode(altitude: 100, accuracy: 10, distances: distances, nearDistance: 5) + ] { + #expect(mode == .guide) + #expect(mode.offset(distance: 30, antenna: nil, pitch: 2, tangent: 0.5) == + mode.offset(distance: 500, antenna: 150, pitch: 2, tangent: 0.5)) + } + let mode = VisionElevationMode(altitude: 100, accuracy: 2, distances: [500], nearDistance: 5) + #expect(mode == .elevation(altitude: 100, accuracy: 2)) + #expect(mode.offset(distance: 500, antenna: nil, pitch: 2, tangent: 0.5) == nil) + #expect(mode.offset(distance: 500, antenna: 150, pitch: 2, tangent: 0.5) != nil) + } + + @Test func altitudeDeadbandAccumulatesChanges() { + let stable = stableVisionAltitude(previous: 100, current: 100.2, distance: 100) + #expect(stable == 100) + #expect(stableVisionAltitude(previous: stable, current: 100.3, distance: 100) == 100.3) + #expect(stableVisionAltitude(previous: stable, current: nil, distance: 100) == nil) + } + + @Test func terrainBatchesCacheByNodeAndCoordinateAndKeepSuccessfulBatches() async throws { + let provider = VisionTestTerrainProvider() + let cache = VisionTerrainCache(provider: provider) + let points = try Set((0..<101).map { index in + let coordinate = try #require(FieldCoordinate(latitude: Double(index) / 100, longitude: 0)) + return try #require(VisionTerrainPoint(key: String(format: "%03d", index), coordinate: coordinate)) + }) + let first = await cache.resolve(points) + #expect(first.count == 100) + #expect(await provider.requests.map(\.count) == [100, 2]) + let cachedPoints = Set(first.keys) + _ = await cache.resolve(points) + #expect(await provider.requests.count == 2) + let coordinate = try #require(FieldCoordinate(latitude: 2, longitude: 0)) + let moved = try #require(VisionTerrainPoint(key: "000", coordinate: coordinate)) + let updated = await cache.resolve(cachedPoints.union([moved])) + #expect(updated[moved] == 42) + #expect(await provider.requests.last == [moved.coordinate, moved.coordinate]) + } +} + +private actor VisionTestTerrainProvider: NodePlannerElevationProviding { + private(set) var requests: [[NodePlannerCoordinate]] = [] + + func elevations(for coordinates: [NodePlannerCoordinate]) async throws -> NodePlannerTerrainProfile { + requests.append(coordinates) + if requests.count == 2 { throw NodePlannerElevationError.unavailable } + return NodePlannerTerrainProfile( + samples: coordinates.map { NodePlannerTerrainSample(coordinate: $0, elevationMeters: 42) }, + provenance: NodePlannerElevationProvenance(fetchedAt: .now, origin: .network) + ) + } +} diff --git a/ROADMAP.md b/ROADMAP.md index cf326dec..efccce89 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -473,6 +473,13 @@ Estimated Coverage shipped through 0.11.0. It includes: ## After 1.0 +- Evaluate Core Motion absolute altitude in NodeVision on supported iPhones. + First, log `CMAbsoluteAltitudeData` altitude and uncertainty alongside Core + Location readings in DEBUG. Compare stationary jitter, the response to a + known stair climb, and time spent in direction-only mode. Verify the altitude + reference matches the terrain data before using the Core Motion reading for + placement. Keep Core Location and the existing direction-only fallback for + unavailable, stale, or uncertain readings. - Expand packet details with raw hex, decoded fields, propagation timing, and a clearer per-observer observation timeline. - Add grouped and observation-level packet views where they improve diagnosis. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index a7340b47..5eb01fb6 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -12,7 +12,7 @@ val localProperties = Properties().apply { } val cartoKey = providers.environmentVariable("CARTO_API_KEY") .orElse(localProperties.getProperty("CARTO_API_KEY", "")).get() -/** Optional Google Maps (beta) provider; without a key only CARTO is offered. */ +/** Optional Google Maps provider; without a key only CARTO is offered. */ val googleMapsKey = providers.environmentVariable("GOOGLE_MAPS_API_KEY") .orElse(localProperties.getProperty("GOOGLE_MAPS_API_KEY", "")).get() /** Release signing comes only from the git-ignored local.properties; without it, release builds are unsigned. */ @@ -160,7 +160,7 @@ dependencies { implementation("com.squareup.okhttp3:okhttp:4.12.0") // OpenGL supports the full API 26+ device range, including non-Vulkan GPUs. implementation("org.maplibre.gl:android-sdk-opengl:13.6.1") - // Google Maps (beta): the native SDK with ordinary markers and no map ID (the free Maps SDK SKU). + // Google Maps: the native SDK with ordinary markers and no map ID (the free Maps SDK SKU). implementation("com.google.android.gms:play-services-maps:20.0.0") implementation("com.google.maps.android:android-maps-utils:4.0.0") // QR encoding for MeshCore contact codes (iOS uses Core Image's built-in generator). diff --git a/android/app/src/androidTest/java/org/nodescope/android/ConsistencyUiTest.kt b/android/app/src/androidTest/java/org/nodescope/android/ConsistencyUiTest.kt index f2214f4e..7a4da06b 100644 --- a/android/app/src/androidTest/java/org/nodescope/android/ConsistencyUiTest.kt +++ b/android/app/src/androidTest/java/org/nodescope/android/ConsistencyUiTest.kt @@ -49,7 +49,7 @@ class ConsistencyUiTest { @Test fun pausedSettingsUsesAccurateStatusAndConsistentHeadings() { compose.setContent { NodeScopeTheme(Appearance.DARK) { Surface(Modifier.fillMaxSize().systemBarsPadding()) { - SettingsScreen(AppPreferences(), LiveConnection.PAUSED, null, null, {}, {}, {}, {}, {}, {}) + SettingsScreen(AppPreferences(), LiveConnection.PAUSED, null, null, {}, {}, {}, {}, {}, {}, onMapLab = {}) } } } compose.onNodeWithText("Appearance").assertIsDisplayed() diff --git a/android/app/src/androidTest/java/org/nodescope/android/FoundationUiTest.kt b/android/app/src/androidTest/java/org/nodescope/android/FoundationUiTest.kt index 206d15cd..3abc19aa 100644 --- a/android/app/src/androidTest/java/org/nodescope/android/FoundationUiTest.kt +++ b/android/app/src/androidTest/java/org/nodescope/android/FoundationUiTest.kt @@ -221,7 +221,7 @@ class FoundationUiTest { var preferences by remember { mutableStateOf(AppPreferences()) } NodeScopeTheme(preferences.appearance) { SettingsScreen(preferences, LiveConnection.LIVE, null, null, { selected = it; preferences = preferences.copy(appearance = it) }, - {}, {}, {}, {}, {}) + {}, {}, {}, {}, {}, onMapLab = {}) } } compose.onNodeWithText("Dark").performClick().assertIsSelected() @@ -234,7 +234,7 @@ class FoundationUiTest { MeshNode("one", "North", "repeater", lastSeen = "2026-01-01T00:00:00Z"), MeshNode("two", "South", "sensor", lastSeen = "2026-01-01T00:00:00Z"), ) - compose.setContent { NodeScopeTheme(Appearance.SYSTEM) { NodeBrowser(nodes, 2, { selected = it }) } } + compose.setContent { NodeScopeTheme(Appearance.SYSTEM) { NodeBrowser(nodes, 2, onNode = { selected = it }) } } compose.onNodeWithText("Search name, public key, or role").performTextInput("SENSOR") compose.onNodeWithText("North").assertDoesNotExist() compose.onNodeWithText("South").performClick() diff --git a/android/app/src/androidTest/java/org/nodescope/android/LinkProfileUiTest.kt b/android/app/src/androidTest/java/org/nodescope/android/LinkProfileUiTest.kt index 27533996..c7e79362 100644 --- a/android/app/src/androidTest/java/org/nodescope/android/LinkProfileUiTest.kt +++ b/android/app/src/androidTest/java/org/nodescope/android/LinkProfileUiTest.kt @@ -101,18 +101,21 @@ class LinkProfileUiTest { @Test fun settingsUnitIsUsedWhenOpeningPlanner() { val preferences = mutableStateOf(org.nodescope.android.core.storage.AppPreferences( - onboarded = true, destination = "SETTINGS", distanceUnit = DistanceUnit.METRIC)) + onboarded = true, destination = "SETTINGS", storedDistanceUnit = DistanceUnit.METRIC)) compose.setContent { - CompositionLocalProvider(LocalDensity provides Density(3f, 1f)) { + CompositionLocalProvider( + LocalDensity provides Density(3f, 1f), + LocalDistanceUnit provides preferences.value.distanceUnit, + ) { NodeScopeTheme(Appearance.LIGHT) { org.nodescope.android.app.AppShell(preferences.value, org.nodescope.android.core.network.SessionState(), {}, {}, {}, {}, {}, nodeLibrary = org.nodescope.android.core.storage.NodeLibrary(), - onDistanceUnit = { preferences.value = preferences.value.copy(distanceUnit = it) }) + onDistanceUnit = { preferences.value = preferences.value.copy(storedDistanceUnit = it) }) } } } - compose.onNodeWithText("Imperial (mi)").performScrollTo().performClick() + compose.onNodeWithText("US (mi, ft)").performScrollTo().performClick() compose.runOnIdle { assertEquals(DistanceUnit.IMPERIAL, preferences.value.distanceUnit) } compose.onNodeWithText("Explore").performClick() compose.onNodeWithText("Node Planner").performScrollTo().performClick() diff --git a/android/app/src/androidTest/java/org/nodescope/android/MapControlsUiTest.kt b/android/app/src/androidTest/java/org/nodescope/android/MapControlsUiTest.kt index aef55d03..160b042e 100644 --- a/android/app/src/androidTest/java/org/nodescope/android/MapControlsUiTest.kt +++ b/android/app/src/androidTest/java/org/nodescope/android/MapControlsUiTest.kt @@ -16,7 +16,7 @@ import org.junit.Test import org.nodescope.android.core.design.NodeScopeTheme import org.nodescope.android.core.model.MeshNode import org.nodescope.android.core.storage.Appearance -import org.nodescope.android.feature.map.MapNodeSelectionSheet +import org.nodescope.android.feature.map.MapNodePreview import org.nodescope.android.feature.map.ReplayControls import org.nodescope.android.feature.map.ReplayRoute import java.io.File @@ -28,7 +28,7 @@ class MapControlsUiTest { var opened = false var visible by mutableStateOf(true) compose.setContent { NodeScopeTheme(Appearance.LIGHT) { - if (visible) MapNodeSelectionSheet( + if (visible) MapNodePreview( MeshNode("test-node", "A long repeater name in the neighborhood", "repeater", lastSeen = "2026-09-26T12:00:00Z"), onDetails = { opened = true; visible = false }, onDismiss = { visible = false }) } } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c1c4b659..db43c03c 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -7,7 +7,7 @@ - + diff --git a/android/app/src/main/java/org/nodescope/android/core/model/FieldContracts.kt b/android/app/src/main/java/org/nodescope/android/core/model/FieldContracts.kt index b72a0246..fbd657ed 100644 --- a/android/app/src/main/java/org/nodescope/android/core/model/FieldContracts.kt +++ b/android/app/src/main/java/org/nodescope/android/core/model/FieldContracts.kt @@ -88,7 +88,7 @@ sealed interface FieldQrCode { } private fun decode(value: String): String? = runCatching { - URLDecoder.decode(value, Charsets.UTF_8) + URLDecoder.decode(value, Charsets.UTF_8.name()) }.getOrNull() private fun publicKey(value: String): String? = value.lowercase().takeIf { key -> diff --git a/android/app/src/main/java/org/nodescope/android/core/model/FieldGeometry.kt b/android/app/src/main/java/org/nodescope/android/core/model/FieldGeometry.kt index b150e66d..4437caf4 100644 --- a/android/app/src/main/java/org/nodescope/android/core/model/FieldGeometry.kt +++ b/android/app/src/main/java/org/nodescope/android/core/model/FieldGeometry.kt @@ -109,14 +109,14 @@ object FieldGeometry { /** Project a height estimate only when combined vertical uncertainty is small enough to be useful. */ fun cameraVerticalOffset( distance: Double, antennaElevation: Double, phoneElevation: Double, - phoneAccuracy: Double, pitch: Double, halfHeightTangent: Double, + phoneAccuracy: Double, pitch: Double, halfHeightTangent: Double, clampAngle: Boolean = false, ): Double? { if (!listOf(distance, antennaElevation, phoneElevation, phoneAccuracy, pitch, halfHeightTangent).all(Double::isFinite) || distance <= 0 || phoneAccuracy <= 0 || halfHeightTangent <= 0 || cameraElevationUncertainty(distance, phoneAccuracy) > 30) return null val curvature = distance * distance / (2 * EARTH_RADIUS_METERS) val angle = Math.toDegrees(atan2(antennaElevation - phoneElevation - curvature, distance)) - pitch - if (kotlin.math.abs(angle) >= 89) return null - return kotlin.math.tan(Math.toRadians(angle)) / halfHeightTangent + if (!clampAngle && kotlin.math.abs(angle) >= 89) return null + return kotlin.math.tan(Math.toRadians(angle.coerceIn(-89.0, 89.0))) / halfHeightTangent } } diff --git a/android/app/src/main/java/org/nodescope/android/core/storage/Preferences.kt b/android/app/src/main/java/org/nodescope/android/core/storage/Preferences.kt index 6bf0516d..0ca41bb1 100644 --- a/android/app/src/main/java/org/nodescope/android/core/storage/Preferences.kt +++ b/android/app/src/main/java/org/nodescope/android/core/storage/Preferences.kt @@ -23,14 +23,14 @@ enum class DistanceUnit { companion object { fun defaultUnit(locale: Locale = Locale.getDefault()): DistanceUnit { - if (Build.VERSION.SDK_INT >= 24) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { return when (LocaleData.getMeasurementSystem(ULocale.forLocale(locale))) { LocaleData.MeasurementSystem.US -> IMPERIAL LocaleData.MeasurementSystem.UK -> UK else -> METRIC } } - // The host JVM has no Android ICU. Keep region mapping available to local unit tests. + // Older Android versions and the host JVM use the region mapping. return when (locale.country) { "US", "LR" -> IMPERIAL "GB", "MM" -> UK diff --git a/android/app/src/main/java/org/nodescope/android/feature/linkprofile/LinkProfileScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/linkprofile/LinkProfileScreen.kt index 3776cec7..cfd024dd 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/linkprofile/LinkProfileScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/linkprofile/LinkProfileScreen.kt @@ -156,7 +156,12 @@ fun LinkProfileScreen(model: LinkProfileViewModel, distanceUnit: DistanceUnit = // Side and lower panels: the header stays put while everything under it scrolls. val panel: @Composable (Modifier) -> Unit = { modifier -> Column(modifier.meshPageBackground()) { - Box(Modifier.padding(16.dp)) { header() } + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + if (!BuildConfig.MAPS_CONFIGURED) { + Text(stringResource(R.string.map_unavailable), style = MaterialTheme.typography.bodySmall) + } + header() + } Column(Modifier.weight(1f).verticalScroll(scroll).padding(horizontal = 16.dp).padding(bottom = 16.dp)) { details() } } } diff --git a/android/app/src/main/java/org/nodescope/android/feature/map/GoogleMapEngine.kt b/android/app/src/main/java/org/nodescope/android/feature/map/GoogleMapEngine.kt index 91e6c48e..3d086371 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/map/GoogleMapEngine.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/map/GoogleMapEngine.kt @@ -42,7 +42,7 @@ import kotlin.coroutines.resume import kotlin.math.hypot /* - * Google Maps (beta), the native Maps SDK: ordinary markers and no map ID, so map loads stay in + * Google Maps, the native Maps SDK: ordinary markers and no map ID, so map loads stay in * the free Maps SDK SKU. A map ID, cloud styling or advanced markers would bill as Dynamic Maps. */ diff --git a/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt b/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt index 209ea665..9a6b4846 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt @@ -2,9 +2,11 @@ package org.nodescope.android.feature.map import android.content.Context import androidx.core.content.edit +import com.google.android.gms.common.ConnectionResult +import com.google.android.gms.common.GoogleApiAvailability import org.nodescope.android.BuildConfig -/** Who draws the map: CARTO (the default) or, when the build has a key, Google Maps (beta). */ +/** The supported Android map providers. */ enum class MapProvider { CARTO, GOOGLE } /** @@ -17,15 +19,22 @@ data class MapProviderChoice(val provider: MapProvider = MapProvider.CARTO, val fun cartoStyle(darkTheme: Boolean) = cartoStyle ?: if (darkTheme) 2 else 0 } -/** A saved Google choice falls back to CARTO in a build without a Google key. */ -internal fun MapProviderChoice.available(googleConfigured: Boolean) = if (googleConfigured) this else copy(provider = MapProvider.CARTO) +internal fun googleMapsAvailable(context: Context): Boolean = + BuildConfig.GOOGLE_MAPS_CONFIGURED && + GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS + +/** A fallback changes the active provider while leaving the saved preference intact. */ +internal fun resolveMapProvider(saved: MapProvider?, googleAvailable: Boolean): MapProvider = + if (googleAvailable) saved ?: MapProvider.GOOGLE else MapProvider.CARTO fun loadMapProvider(context: Context): MapProviderChoice { val prefs = context.getSharedPreferences("map-provider", Context.MODE_PRIVATE) - val provider = MapProvider.entries.firstOrNull { it.name == prefs.getString("provider", null) } ?: MapProvider.CARTO + val savedProvider = prefs.getString("provider", null) + val provider = resolveMapProvider(MapProvider.entries.firstOrNull { it.name == savedProvider }, + googleMapsAvailable(context)) val type = GoogleMapType.entries.firstOrNull { it.name == prefs.getString("googleType", null) } ?: GoogleMapType.MAP val style = prefs.getInt("cartoStyle", -1).takeIf { it in 0..2 } - return MapProviderChoice(provider, type, style).available(BuildConfig.GOOGLE_MAPS_CONFIGURED) + return MapProviderChoice(provider, type, style) } fun saveMapProvider(context: Context, choice: MapProviderChoice) { diff --git a/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt index 79b309e1..a65d1512 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt @@ -80,7 +80,7 @@ fun MapScreen(snapshot: AnalyzerSnapshot?, focusedKey: String? = null, onNode: ( var search by remember { mutableStateOf(false) } var layersOpen by remember { mutableStateOf(false) } val context = LocalContext.current - // CARTO, or Google Maps (beta) when this build has a key; remembered across launches. + // Google Maps when supported, with the user’s map selection remembered across launches. var providerChoice by remember { mutableStateOf(loadMapProvider(context)) } fun choose(choice: MapProviderChoice) { providerChoice = choice; saveMapProvider(context, choice) } // A picked CARTO style sticks; until then it follows the app theme. @@ -840,7 +840,7 @@ internal fun MapLayersMenu(expanded: Boolean, onDismiss: () -> Unit, choice: Map onChoose: (MapProviderChoice) -> Unit) { val mode = choice.cartoStyle(darkTheme) DropdownMenu(expanded, onDismiss) { - val google = BuildConfig.GOOGLE_MAPS_CONFIGURED + val google = googleMapsAvailable(LocalContext.current) // Grouped by provider when there is more than one. if (google) MenuSectionHeader(stringResource(R.string.map_provider_carto)) listOf(R.string.standard, R.string.light, R.string.dark).forEachIndexed { index, label -> diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodes/NodeDetailScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodes/NodeDetailScreen.kt index d5d56c6e..f1756c62 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodes/NodeDetailScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodes/NodeDetailScreen.kt @@ -133,6 +133,7 @@ fun NodeDetailScreen( target = visionCoordinate, antennaHeight = metadata.value?.applicableHeightMeters(), initialStatus = metadata.value?.status, + targetRole = node?.role, ) { showsNodeVision = false } diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index 61129bfa..7ed061a5 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -5,6 +5,7 @@ import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut +import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics import androidx.compose.ui.layout.onGloballyPositioned @@ -43,9 +44,20 @@ import android.net.Uri import android.os.SystemClock import android.os.Build import android.location.altitude.AltitudeConverter +import androidx.compose.ui.draw.drawWithCache +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.drawscope.Stroke +import org.nodescope.android.feature.coverage.CoverageHeightPreset +import org.nodescope.android.feature.linkprofile.LinkTerrainProviding import java.io.File import java.io.IOException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import org.nodescope.android.feature.linkprofile.LinkTerrainProvider import org.nodescope.android.feature.linkprofile.ProfileCoordinate @@ -123,6 +135,7 @@ internal fun NodeVisionScreen( target: FieldCoordinate? = null, antennaHeight: Double? = null, initialStatus: String? = null, + targetRole: String? = null, catalog: List = emptyList(), catalogIsLoading: Boolean = false, loadMetadata: suspend () -> Map = { emptyMap() }, @@ -150,9 +163,16 @@ internal fun NodeVisionScreen( } val inspectedNode = catalog.firstOrNull { it.publicKey == inspectedKey } val focusedNode = catalog.firstOrNull { it.publicKey == focusedKey } + val reopenPreview = if (focusedNode != null && inspectedKey != focusedNode.publicKey) { + Modifier.clickable(role = Role.Button, onClickLabel = stringResource(R.string.nodevision_expand_details)) { + inspectedKey = focusedNode.publicKey + expandsInspection = true + } + } else Modifier val visionTarget = focusedNode?.visionCoordinate() ?: target val visionName = focusedNode?.displayName ?: name.orEmpty() - val visionHeight = focusedNode?.let { repeaterMetadata[it.publicKey.lowercase()]?.applicableHeightMeters() } ?: antennaHeight + val reportedHeight = focusedNode?.let { repeaterMetadata[it.publicKey.lowercase()]?.applicableHeightMeters() } ?: antennaHeight + val visionHeight = visionAntennaHeight(focusedNode?.role ?: targetRole, reportedHeight) val ownerStatus = when (focusedNode?.let { repeaterMetadata[it.publicKey.lowercase()]?.status } ?: initialStatus) { "maintenance" -> R.string.nodevision_owner_maintenance "decommissioned" -> R.string.nodevision_owner_decommissioned @@ -214,22 +234,23 @@ internal fun NodeVisionScreen( } val trueHeading = if (heading != null && declination != null) heading.degrees + declination else null - var antennaElevation by remember(visionTarget, visionHeight) { mutableStateOf(null) } - LaunchedEffect(visionTarget, visionHeight) { - if (visionHeight == null || visionTarget == null) return@LaunchedEffect - val point = ProfileCoordinate(visionTarget.latitude, visionTarget.longitude) - val provider = LinkTerrainProvider(File(context.cacheDir, "nodevision-elevation.json")) - antennaElevation = try { - provider.profile(listOf(point, point)).points.firstOrNull()?.elevationMeters?.plus(visionHeight) - } catch (_: IOException) { - null - } catch (_: IllegalArgumentException) { - null + val spotlightPoint = visionTarget?.let { VisionTerrainPoint(focusedNode?.publicKey.orEmpty().lowercase(), it) } + val terrainPoints = remember(nearby, spotlightPoint) { + buildSet { + nearby.mapNotNullTo(this) { it.node.terrainPoint() } + spotlightPoint?.let { add(it) } } } + val terrain = remember(context) { + VisionTerrainCache(LinkTerrainProvider(File(context.cacheDir, "nodevision-elevation.json"))) + } + var ground by remember(terrain) { mutableStateOf>(emptyMap()) } + LaunchedEffect(terrain, terrainPoints) { ground = terrain.resolve(terrainPoints) } + val antennaElevation = spotlightPoint?.let(ground::get)?.plus(visionHeight.meters) + var altitude by remember { mutableStateOf(null) } - LaunchedEffect(fix, active, antennaElevation) { - if (fix == null || !active || antennaElevation == null || Build.VERSION.SDK_INT < 34) { + LaunchedEffect(fix, active) { + if (fix == null || !active || Build.VERSION.SDK_INT < 34) { altitude = null return@LaunchedEffect } @@ -245,6 +266,7 @@ internal fun NodeVisionScreen( } } + var displayedAltitude by remember { mutableStateOf(null) } var optics by remember { mutableStateOf(null) } var cameraFailed by remember { mutableStateOf(false) } var showsDiagnostics by rememberSaveable { mutableStateOf(false) } @@ -257,12 +279,15 @@ internal fun NodeVisionScreen( val onSurface = MaterialTheme.colorScheme.onSurface val lightOverlay = surface.luminance() >= 0.5f val supportingText = lerp(onSurface, surface, if (lightOverlay) 0.10f else 0.22f) - val markerBorder = BorderStroke(if (lightOverlay) 2.dp else 1.5.dp, accent) val density = LocalDensity.current val markerShape = remember(density) { with(density) { visionMarkerShape(10.dp.toPx(), 9.dp.toPx(), 8.dp.toPx()) } } val blue = MaterialTheme.colorScheme.primary + val nodeNameColor = if (lightOverlay) blue else lerp(blue, onSurface, 0.55f) + val typography = MaterialTheme.typography + fun markerNameStyle(tier: Int) = if (tier == 0) typography.titleSmall else typography.labelMedium + val markerInk = if (lightOverlay) lerp(blue, onSurface, 0.25f) else blue val overlayTint = if (lightOverlay) { Brush.verticalGradient(listOf(blue.copy(alpha = 0.16f), blue.copy(alpha = 0.07f))) } else { @@ -296,7 +321,9 @@ internal fun NodeVisionScreen( val offset = if (!near && bearing != null && trueHeading != null && tangent != null && projection != null) { FieldGeometry.cameraHorizontalOffset(bearing, trueHeading, tangent)?.plus(projection.centerX * 2 - 1) } else null - val markerWidth = minOf(192.dp, (paneWidth - 32.dp).coerceAtLeast(0.dp)) + val markerTier = visionMarkerTier(geometry?.distanceMeters ?: 0.0) + val markerWidth = minOf(visionMarkerWidth(markerTier).dp, + (paneWidth - 32.dp).coerceAtLeast(0.dp)) val pixel = (offset ?: 0.0) * paneWidth.value / 2 val limit = (paneWidth.value / 2 - markerWidth.value / 2 - 8).coerceAtLeast(0f) val offscreen = abs(pixel) > (limit + if (edge) -6 else 6).coerceAtLeast(0f) @@ -314,16 +341,18 @@ internal fun NodeVisionScreen( val verticalTangent = projection?.halfHeightTangent val targetElevation = antennaElevation val phoneAltitude = altitude?.takeIf { now - it.fixTime <= 3_000 } - val verticalOffset = if (geometry != null && targetElevation != null && phoneAltitude != null && - heading != null && verticalTangent != null) { - FieldGeometry.cameraVerticalOffset(geometry.distanceMeters, targetElevation, - phoneAltitude.meters, phoneAltitude.accuracy, heading.pitch, verticalTangent) - } else null - val approximate = verticalOffset != null && phoneAltitude != null && geometry != null && - FieldGeometry.cameraElevationUncertainty(geometry.distanceMeters, phoneAltitude.accuracy) > 8 - val markerOffset = verticalOffset ?: if (heading != null && verticalTangent != null && verticalTangent > 0) { - FieldGeometry.cameraBearingGuideOffset(heading.pitch, verticalTangent) + val nearDistance = maxOf(5.0, fix?.accuracy?.toDouble() ?: 0.0) + val distances = nearby.map { it.geometry.distanceMeters } + listOfNotNull(geometry?.distanceMeters) + val closestDistance = distances.filter { it > nearDistance }.minOrNull() + val stableAltitude = stableVisionAltitude(displayedAltitude, phoneAltitude?.meters, closestDistance) + SideEffect { displayedAltitude = stableAltitude } + val mode = visionElevationMode(stableAltitude, phoneAltitude?.accuracy, distances, nearDistance) + val markerOffset = if (geometry != null && heading != null && verticalTangent != null && verticalTangent > 0) { + mode.offset(geometry.distanceMeters, targetElevation, heading.pitch, verticalTangent) } else null + val verticalOffset = markerOffset.takeUnless { mode == VisionElevationMode.Guide } + val approximate = markerOffset != null && geometry != null && + mode.isApproximate(geometry.distanceMeters, visionHeight) val safeTop = WindowInsets.safeDrawing.asPaddingValues().calculateTopPadding() val safeBottom = WindowInsets.safeDrawing.asPaddingValues().calculateBottomPadding() val minimumY = safeTop + 166.dp @@ -340,21 +369,25 @@ internal fun NodeVisionScreen( else -> null } val useVerticalArrow = verticalEdge != null && (!offscreen || abs(verticalOffset ?: 0.0) > abs(offset ?: 0.0)) - val markerVisible = showCamera && offset != null && !offscreen && verticalEdge == null + val markerVisible = markerOffset != null && showCamera && offset != null && !offscreen && verticalEdge == null val discoveryMarkers = if (discovery && showCamera && fix != null && projection != null && trueHeading != null && heading != null && verticalTangent != null && maximumY >= minimumY) { - val guide = FieldGeometry.cameraBearingGuideOffset(heading.pitch, verticalTangent) - val y = maxHeight.value * (projection.centerY - guide / 2) discoveryMarkers(discoveryNodes, inspectedKey, focusedKey, fix.accuracy.toDouble(), - trueHeading, projection, paneWidth.value.toDouble(), y, + trueHeading, projection, paneWidth.value.toDouble(), maxHeight.value.toDouble(), + heading.pitch, mode, + antenna = { node -> + val height = visionAntennaHeight(node.role, + repeaterMetadata[node.publicKey.lowercase()]?.applicableHeightMeters()) + node.terrainPoint()?.let(ground::get)?.plus(height.meters) to height + }, if (markerVisible) paneWidth.value / 2 + pixel else null, markerY.value.toDouble(), markerWidth.value.toDouble(), minimumY.value.toDouble(), maximumY.value.toDouble()) } else emptyList() - val retainedMarkers = remember { mutableStateMapOf() } + val retainedMarkers = remember(mode == VisionElevationMode.Guide) { mutableStateMapOf() } val visibleMarkers = discoveryMarkers.associateBy { it.node.publicKey } SideEffect { retainedMarkers.putAll(visibleMarkers) } (retainedMarkers.keys + visibleMarkers.keys).forEach { markerKey -> - key(markerKey) { + key(markerKey, mode == VisionElevationMode.Guide) { val marker = visibleMarkers[markerKey] ?: retainedMarkers.getValue(markerKey) val visible = markerKey in visibleMarkers val visibility = remember { MutableTransitionState(false) } @@ -371,22 +404,23 @@ internal fun NodeVisionScreen( ) { Box(Modifier.width(marker.width.dp).height(80.dp), contentAlignment = Alignment.BottomCenter) { Surface( + modifier = Modifier.fillMaxWidth(), enabled = visible, onClick = { inspectedKey = marker.node.publicKey expandsInspection = false }, shape = markerShape, - color = surface.copy(alpha = if (marker.tier == 2 && !selected) 0.90f else 0.98f), - border = if (selected) BorderStroke(2.dp, blue) else overlayBorder, + color = surface.copy(alpha = 0.98f), shadowElevation = 4.dp, ) { Column(Modifier.background(overlayTint) + .visionMarkerBorder(markerShape, markerInk, surface, marker.approximate, selected) .padding(bottom = 9.dp).padding(horizontal = 6.dp, vertical = 4.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text(marker.node.displayName, fontFamily = MonaspaceNeon, - style = if (marker.tier == 0) MaterialTheme.typography.titleSmall else MaterialTheme.typography.labelMedium, - color = blue, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) + style = markerNameStyle(marker.tier), + color = nodeNameColor, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) Text(stringResource(R.string.nodevision_distance_away, formatDistance(marker.distance / 1000, distanceUnit)), style = MaterialTheme.typography.labelSmall, fontFamily = MonaspaceNeon, textAlign = TextAlign.Center) @@ -397,7 +431,7 @@ internal fun NodeVisionScreen( } } val showsTargetCard = visionTarget != null && inspectedNode == null && - (!markerVisible || truncatedName || status != null || showSettings || visionHeight != null || ownerStatus != null) + (!markerVisible || truncatedName || status != null || showSettings || reportedHeight != null || ownerStatus != null) var targetCardTop by remember { mutableStateOf(null) } var discoveryControlsTop by remember { mutableStateOf(null) } SideEffect { verticalArrowShown = showCamera && offset != null && verticalEdge != null } @@ -434,22 +468,25 @@ internal fun NodeVisionScreen( ) { Icon(icon, stringResource(label), Modifier.size(48.dp).padding(8.dp), tint = accent) } - } else { + } else if (markerVisible) { // The bottom of the tip stays on the bearing band when the label wraps. Box(Modifier.offset(x = maxWidth / 2 + pixel.dp - markerWidth / 2, y = markerY - 88.dp) .width(markerWidth).height(88.dp), contentAlignment = Alignment.BottomCenter) { Surface( + modifier = Modifier.fillMaxWidth().then(reopenPreview), color = surface.copy(alpha = 0.98f), shape = markerShape, - border = markerBorder, shadowElevation = 4.dp, + shadowElevation = 4.dp, ) { - Column(Modifier.background(overlayTint).padding(bottom = 9.dp).padding(horizontal = 9.dp, vertical = 5.dp), horizontalAlignment = Alignment.CenterHorizontally) { - Text(visionName, style = MaterialTheme.typography.titleSmall, fontFamily = MonaspaceNeon, - color = MaterialTheme.colorScheme.primary, maxLines = 2, + Column(Modifier.background(overlayTint) + .visionMarkerBorder(markerShape, accent, surface, approximate, emphasized = true) + .padding(bottom = 9.dp).padding(horizontal = 6.dp, vertical = 4.dp), + horizontalAlignment = Alignment.CenterHorizontally) { + Text(visionName, style = markerNameStyle(markerTier), fontFamily = MonaspaceNeon, + color = nodeNameColor, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, onTextLayout = { truncatedName = it.hasVisualOverflow }) geometry?.let { Text(stringResource(R.string.nodevision_distance_away, formatDistance(it.distanceMeters / 1000, distanceUnit)), style = MaterialTheme.typography.labelSmall, fontFamily = MonaspaceNeon) } - if (approximate || verticalOffset == null) Text(stringResource( - if (approximate) R.string.nodevision_approx_elevation else R.string.nodevision_elevation_uncertain), + if (approximate) Text(stringResource(R.string.nodevision_approx_elevation), style = MaterialTheme.typography.labelSmall, fontFamily = androidx.compose.ui.text.font.FontFamily.Default, color = supportingText) } } @@ -506,16 +543,17 @@ internal fun NodeVisionScreen( Box(Modifier.align(Alignment.BottomCenter).padding(bottom = 3.dp).size(3.dp, 15.dp).background(accent, shape = androidx.compose.foundation.shape.CircleShape)) } } + if (showCamera && trueHeading != null && projection != null && fix != null && + mode == VisionElevationMode.Guide && (visionTarget != null || discoveryMarkers.isNotEmpty())) { + Text(stringResource(R.string.nodevision_phone_altitude_uncertain), + Modifier.padding(horizontal = 16.dp, vertical = 4.dp), + style = MaterialTheme.typography.bodySmall, color = supportingText) + } HorizontalDivider(color = MaterialTheme.colorScheme.primary.copy(alpha = 0.25f)) if (BuildConfig.DEBUG && showsDiagnostics) { - val decision = when { - heading == null || verticalTangent == null -> "Guide: waiting for pitch or camera" - targetElevation == null -> "Guide: antenna elevation unavailable" - phoneAltitude == null -> "Guide: phone altitude unavailable" - verticalOffset == null -> "Guide: accuracy or viewing angle" - approximate -> "Approximate estimate" - else -> "Elevation estimate" - } + val decision = if (mode == VisionElevationMode.Guide) "All markers: pitch guide" + else if (targetElevation == null) "All markers: elevation · spotlight unplaced" + else "All markers: elevation" val readout = "Phone ${debugMeters(phoneAltitude?.meters)} ±${debugMeters(phoneAltitude?.accuracy)} · " + "Antenna ${debugMeters(targetElevation)}\n$decision" Text(readout, Modifier.padding(5.dp), style = MaterialTheme.typography.labelSmall) @@ -548,21 +586,22 @@ internal fun NodeVisionScreen( targetCardTop = with(density) { coordinates.positionInParent().y.toDp() } } .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Bottom + WindowInsetsSides.Horizontal)) - .padding(horizontal = 16.dp).padding(bottom = if (discovery) 66.dp else 8.dp).widthIn(max = 340.dp), + .padding(horizontal = 16.dp).padding(bottom = if (discovery) 66.dp else 8.dp).widthIn(max = 340.dp) + .then(reopenPreview), color = surface.copy(alpha = 0.97f), shape = MaterialTheme.shapes.medium, border = overlayBorder, shadowElevation = 4.dp, ) { Column(Modifier.background(overlayTint).padding(horizontal = 14.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp), horizontalAlignment = Alignment.CenterHorizontally) { if (!markerVisible || truncatedName) { - Text(visionName, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center) + Text(visionName, style = MaterialTheme.typography.titleSmall, color = nodeNameColor, textAlign = TextAlign.Center) } if (!markerVisible) geometry?.let { Text(stringResource(R.string.nodevision_distance_away, formatDistance(it.distanceMeters / 1000, distanceUnit)), style = MaterialTheme.typography.labelSmall, fontFamily = MonaspaceNeon) } - if (visionHeight != null) { - val height = if (distanceUnit.usesFeet) visionHeight * 3.28084 else visionHeight + if (reportedHeight != null) { + val height = if (distanceUnit.usesFeet) reportedHeight * 3.28084 else reportedHeight val formattedHeight = java.text.NumberFormat.getNumberInstance().apply { maximumFractionDigits = 1 }.format(height) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { Icon(Icons.Default.ArrowUpward, contentDescription = null, Modifier.size(14.dp), @@ -607,7 +646,7 @@ internal fun NodeVisionScreen( .verticalScroll(rememberScrollState()).padding(horizontal = 12.dp, vertical = 8.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { Text(inspectedNode.displayName, Modifier.weight(1f).clickable { expandsInspection = !expandsInspection }, - style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) + style = MaterialTheme.typography.titleSmall, color = nodeNameColor) IconButton(onClick = { expandsInspection = !expandsInspection }) { Icon(if (expandsInspection) Icons.Default.ExpandMore else Icons.Default.ExpandLess, stringResource(if (expandsInspection) R.string.nodevision_collapse_details else R.string.nodevision_expand_details)) @@ -745,7 +784,14 @@ internal fun NodeVisionScreen( verticalArrangement = Arrangement.spacedBy(12.dp)) { Text(stringResource(R.string.nodevision_help_markers)) Text(stringResource(R.string.nodevision_help_focus)) + Text(stringResource(R.string.nodevision_help_phone_altitude)) Text(stringResource(R.string.nodevision_help_elevation)) + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + VisionMarkerStyleExample(R.string.nodevision_higher_confidence_elevation, + markerShape, markerInk, surface, overlayTint, approximate = false) + VisionMarkerStyleExample(R.string.nodevision_approx_elevation, + markerShape, markerInk, surface, overlayTint, approximate = true) + } HorizontalDivider() Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), @@ -780,24 +826,34 @@ internal fun NodeVisionScreen( } private data class NearbyVisionNode(val node: MeshNode, val geometry: FieldGeometryResult) +private fun visionMarkerTier(distance: Double): Int = when { + distance < 500 -> 0 + distance < 2_000 -> 1 + else -> 2 +} + +private fun visionMarkerWidth(tier: Int): Double = when (tier) { + 0 -> 132.0 + 1 -> 112.0 + else -> 96.0 +} + private data class DiscoveryMarker( - val node: MeshNode, val distance: Double, val x: Double, val y: Double, val width: Double, val tier: Int, + val node: MeshNode, val distance: Double, val x: Double, val y: Double, val width: Double, val tier: Int, val approximate: Boolean, ) private fun discoveryMarkers( nearby: List, inspectedKey: String?, focusedKey: String?, horizontalAccuracy: Double, - heading: Double, projection: VisionOptics, paneWidth: Double, y: Double, + heading: Double, projection: VisionOptics, paneWidth: Double, paneHeight: Double, + pitch: Double, mode: VisionElevationMode, antenna: (MeshNode) -> Pair, focusedX: Double?, focusedY: Double, focusedWidth: Double, minimumY: Double, maximumY: Double, ): List { - if (y !in minimumY..maximumY) return emptyList() val available = if (focusedX == null) 5 else 4 data class Bounds(val left: Double, val right: Double, val top: Double, val bottom: Double) { fun overlaps(other: Bounds): Boolean = left < other.right && right > other.left && top < other.bottom && bottom > other.top } - val rowSpacing = 92.0 - val rowYs = listOf(y, if (y + rowSpacing <= maximumY) y + rowSpacing else y - rowSpacing) val occupied = mutableListOf() if (focusedX != null) { occupied.add(Bounds(focusedX - focusedWidth / 2, focusedX + focusedWidth / 2, focusedY - 88, focusedY)) @@ -809,22 +865,25 @@ private fun discoveryMarkers( val bearing = candidate.geometry.initialBearingDegrees ?: return val offset = FieldGeometry.cameraHorizontalOffset(bearing, heading, projection.halfWidthTangent) ?: return val x = paneWidth * (projection.centerX + offset / 2) - val tier = when { - candidate.geometry.distanceMeters < 500 -> 0 - candidate.geometry.distanceMeters < 2_000 -> 1 - else -> 2 - } - val width = when (tier) { 0 -> 132.0; 1 -> 112.0; else -> 96.0 } + val tier = visionMarkerTier(candidate.geometry.distanceMeters) + val width = visionMarkerWidth(tier) val left = x - width / 2 - 5 val right = x + width / 2 + 5 if (left < 0 || right > paneWidth) return - // Stagger labels vertically without changing the projected bearing. - for (rowY in rowYs) { - if (rowY < minimumY) continue + val (elevation, height) = antenna(candidate.node) + val distance = candidate.geometry.distanceMeters + val vertical = mode.offset(distance, elevation, pitch, projection.halfHeightTangent) ?: return + val projectedY = paneHeight * (projection.centerY - vertical / 2) + val y = discoveryMarkerY(projectedY, paneHeight, minimumY, maximumY) ?: return + val approximate = mode.isApproximate(distance, height) + val nudges = if (mode == VisionElevationMode.Guide) listOf(0.0, if (y + 92 <= maximumY) 92.0 else -92.0) + else listOf(0.0, 24.0, -24.0, 48.0, -48.0, 72.0, -72.0, 92.0, -92.0) + for (nudge in nudges) { + val rowY = (y + nudge).coerceIn(minimumY, maximumY) val bounds = Bounds(left, right, rowY - 84, rowY + 4) if (occupied.any { it.overlaps(bounds) }) continue occupied.add(bounds) - markers.add(DiscoveryMarker(candidate.node, candidate.geometry.distanceMeters, x, rowY, width, tier)) + markers.add(DiscoveryMarker(candidate.node, candidate.geometry.distanceMeters, x, rowY, width, tier, approximate)) break } } @@ -1109,3 +1168,121 @@ private fun VisionCamera(modifier: Modifier, update: (VisionOptics?, Boolean) -> } } } + + +internal data class VisionAntennaHeight(val meters: Double, val approximate: Boolean) + +internal fun visionAntennaHeight(role: String?, reported: Double?): VisionAntennaHeight { + val normalized = role?.lowercase() + val height = reported.takeIf { normalized == "repeater" } + val preset = when (normalized) { + "repeater", "room", "room server", "room_server", "roomserver", "room-server" -> CoverageHeightPreset.ROOFTOP + else -> CoverageHeightPreset.HANDHELD + } + return VisionAntennaHeight(height ?: preset.meters, height == null) +} + +internal sealed interface VisionElevationMode { + data object Guide : VisionElevationMode + data class Elevation(val altitude: Double, val accuracy: Double) : VisionElevationMode + + fun offset(distance: Double, antenna: Double?, pitch: Double, tangent: Double): Double? = when (this) { + Guide -> FieldGeometry.cameraBearingGuideOffset(pitch, tangent) + is Elevation -> antenna?.let { + FieldGeometry.cameraVerticalOffset(distance, it, altitude, accuracy, pitch, tangent, clampAngle = true) + } + } + + fun isApproximate(distance: Double, height: VisionAntennaHeight): Boolean = + this is Elevation && (height.approximate || FieldGeometry.cameraElevationUncertainty(distance, accuracy) > 8) +} + +internal fun visionElevationMode( + altitude: Double?, accuracy: Double?, distances: List, nearDistance: Double, +): VisionElevationMode { + if (altitude == null || !altitude.isFinite() || accuracy == null || !accuracy.isFinite() || accuracy <= 0 || + distances.any { it > nearDistance && FieldGeometry.cameraElevationUncertainty(it, accuracy) > 30 }) { + return VisionElevationMode.Guide + } + return VisionElevationMode.Elevation(altitude, accuracy) +} + +internal data class VisionTerrainPoint(val key: String, val coordinate: ProfileCoordinate) { + constructor(key: String, coordinate: FieldCoordinate) : + this(key, ProfileCoordinate(coordinate.latitude, coordinate.longitude)) +} + +private fun MeshNode.terrainPoint(): VisionTerrainPoint? = + visionCoordinate()?.let { VisionTerrainPoint(publicKey.lowercase(), it) } + +internal class VisionTerrainCache(private val provider: LinkTerrainProviding) { + private val elevations = mutableMapOf() + private val attempted = mutableSetOf() + + suspend fun resolve(points: Set): Map { + val missing = points.filterNot(attempted::contains) + .sortedWith(compareBy({ it.key }, { it.coordinate.latitude }, { it.coordinate.longitude })) + for (batch in missing.chunked(100)) { + val coordinates = batch.map { it.coordinate }.distinct() + val request = if (coordinates.size == 1) coordinates + coordinates else coordinates + val profile = try { + provider.profile(request) + } catch (_: IOException) { + null + } catch (_: IllegalArgumentException) { + null + } + kotlin.coroutines.coroutineContext.ensureActive() + attempted.addAll(batch) + if (profile == null) continue + val ground = request.zip(profile.points).associate { (coordinate, point) -> coordinate to point.elevationMeters } + for (point in batch) { + ground[point.coordinate]?.takeIf(Double::isFinite)?.let { elevations[point] = it } + } + } + return elevations.toMap() + } +} + +/** Ignore altitude changes that move even the closest eligible marker less than 0.15°. */ +internal fun stableVisionAltitude(previous: Double?, current: Double?, distance: Double?): Double? { + if (current == null || !current.isFinite()) return null + if (previous == null || distance == null) return current + return if (kotlin.math.atan2(abs(current - previous), distance) < Math.toRadians(0.15)) previous else current +} + +/** Clamp to the label-safe area while the node is in or just outside the viewfinder. */ +internal fun discoveryMarkerY(projectedY: Double, paneHeight: Double, minimumY: Double, maximumY: Double): Double? { + if (projectedY !in -24.0..(paneHeight + 24)) return null + return projectedY.coerceIn(minimumY, maximumY) +} + +@Composable +private fun VisionMarkerStyleExample( + label: Int, shape: Shape, ink: Color, backing: Color, tint: Brush, approximate: Boolean, +) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { + Surface(shape = shape, color = backing) { + Box(Modifier.size(width = 38.dp, height = 28.dp) + .background(tint) + .visionMarkerBorder(shape, ink, backing, approximate, emphasized = false)) + } + Text(stringResource(label), style = MaterialTheme.typography.bodySmall) + } +} + +private fun Modifier.visionMarkerBorder( + shape: Shape, ink: Color, backing: Color, approximate: Boolean, emphasized: Boolean, +): Modifier = drawWithCache { + // The marker shape is a GenericShape. Draw inside the clipped Surface so the full width stays visible. + val path = (shape.createOutline(size, layoutDirection, this) as Outline.Generic).path + val width = if (emphasized) 3.dp.toPx() else 2.dp.toPx() + val baseStroke = Stroke(width = 2 * (width + 1.dp.toPx()), join = StrokeJoin.Round) + val pattern = if (approximate) PathEffect.dashPathEffect(floatArrayOf(7.dp.toPx(), 6.dp.toPx())) else null + val stroke = Stroke(width = 2 * width, cap = StrokeCap.Butt, join = StrokeJoin.Round, pathEffect = pattern) + onDrawWithContent { + drawContent() + drawPath(path, backing, style = baseStroke) + drawPath(path, ink, style = stroke) + } +} diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 1089c8ad..4c80c7cb 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -29,7 +29,7 @@ Aún puedes explorar nodos en Explorar y elegir tu analizador en Ajustes. Estándar CARTO - Google Maps · Beta + Google Maps Mapa Satélite Terreno @@ -1995,12 +1995,14 @@ Objetivo a la izquierda Objetivo a la derecha Abrir ajustes + Elevación de mayor confianza Elevación aprox. Acerca de NodeVision Privacidad de la ubicación Algunos propietarios indican deliberadamente una ubicación a poca distancia de la instalación real para evitar que se pueda identificar su domicilio u otro lugar privado. NodeVision apunta hacia la ubicación indicada. Nodo por encima del campo de visión Nodo por debajo del campo de visión + Altitud del teléfono incierta Elevación incierta %1$s m %1$s ft @@ -2018,7 +2020,8 @@ No se encontraron nodos cercanos. La brújula muestra hacia dónde apunta la cámara. Los marcadores muestran el nombre de cada nodo y la distancia hasta él. Los marcadores pequeños siguen la dirección del nodo y pueden colocarse a distintas alturas para que las etiquetas se lean bien. Toca un marcador para ver una vista previa del nodo. Elige «Destacar nodo» para resaltarlo al girar la cámara. Si eliges un nodo desde Cercanos, se destaca de inmediato. Cuando el nodo destacado queda fuera de la vista, las flechas en los bordes indican hacia dónde girar o inclinar la cámara. - Cuando hay suficientes datos de elevación, NodeVision los usa para colocar el marcador destacado en el eje vertical. «Elevación incierta» significa que su altura en pantalla es orientativa. + Cuando no se dispone de la altitud del teléfono o es demasiado imprecisa, los marcadores indican hacia dónde girar. Su altura en pantalla no indica si un nodo está por encima o por debajo de ti. + Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano. Un contorno discontinuo indica una posición aproximada basada en una altura predeterminada o en una altitud del teléfono menos precisa. Nodos a 10 mi o menos Nodos a 10 km o menos Destacar nodo diff --git a/android/app/src/main/res/values-pt-rBR/strings.xml b/android/app/src/main/res/values-pt-rBR/strings.xml index bfe1f68e..1dea736e 100644 --- a/android/app/src/main/res/values-pt-rBR/strings.xml +++ b/android/app/src/main/res/values-pt-rBR/strings.xml @@ -29,7 +29,7 @@ Você ainda pode explorar nós em Explorar e escolher seu analisador em Ajustes. Padrão CARTO - Google Maps · Beta + Google Maps Mapa Satélite Terreno @@ -1995,12 +1995,14 @@ Alvo à esquerda Alvo à direita Abrir ajustes + Elevação mais confiável Elevação aprox. Sobre o NodeVision Privacidade da localização Alguns proprietários informam intencionalmente uma localização a uma curta distância da instalação real para evitar que sua residência ou outro local privado seja identificado. O NodeVision aponta para a localização informada. Alvo acima da área visível Alvo abaixo da área visível + Altitude do celular incerta Elevação incerta %1$s m %1$s ft @@ -2018,7 +2020,8 @@ Nenhum nó próximo foi encontrado. A bússola mostra para onde a câmera aponta. Os marcadores mostram o nome de cada nó e a distância até ele. Os marcadores menores seguem a direção do nó e podem aparecer em alturas diferentes para facilitar a leitura. Toque em um marcador para ver uma prévia do nó. Escolha “Destacar nó” para realçá-lo ao girar a câmera. Ao escolher um nó em Próximos, ele é destacado na hora. Quando o nó destacado sai da área visível, as setas nas bordas indicam para onde girar ou inclinar a câmera. - Quando há dados de elevação suficientes, o NodeVision os usa para posicionar o marcador destacado na vertical. “Elevação incerta” indica que a altura na tela é apenas uma referência. + Quando a altitude do celular está indisponível ou é imprecisa demais, os marcadores mostram para onde virar. A altura deles na tela não indica se um nó está acima ou abaixo de você. + Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil. Um contorno tracejado indica uma posição aproximada baseada em uma altura padrão ou em uma altitude do celular menos precisa. Nós a até 10 mi de você Nós a até 10 km de você Destacar nó diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 2ed3a4e1..c09ada0a 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -29,7 +29,7 @@ You can still browse nodes in Explore and choose your analyzer in Settings. Standard CARTO - Google Maps · Beta + Google Maps Map Satellite Terrain @@ -1981,12 +1981,14 @@ Target to the left Target to the right Open Settings + Higher-confidence elevation Approx. elevation About NodeVision Location privacy Some node owners intentionally set the reported location a short distance from the actual installation to keep their home or another private location from being pinpointed. NodeVision points toward the reported location. Target above the view Target below the view + Phone altitude uncertain Elevation Uncertain %1$s m %1$s ft @@ -2004,7 +2006,8 @@ No nearby nodes found. The compass shows where the camera is pointing. Markers show node names and distances from you. Smaller markers follow the node’s direction and may stagger vertically to keep labels readable. Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view. - When enough elevation data is available, NodeVision uses it to place the focused marker vertically. “Elevation Uncertain” means its height on screen is a rough guide. + When your phone’s altitude is missing or too uncertain, markers show which way to turn. Their height on screen doesn’t indicate whether a node is above or below you. + When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dashed outline marks an approximate placement based on a default height or a less precise phone altitude. Nodes within 10 mi of you Nodes within 10 km of you Spotlight node diff --git a/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt b/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt index d19f142d..374de2a3 100644 --- a/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt +++ b/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt @@ -4,6 +4,21 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test +import java.io.IOException +import kotlinx.coroutines.runBlocking +import org.nodescope.android.feature.nodevision.VisionAntennaHeight +import org.nodescope.android.feature.nodevision.VisionElevationMode +import org.nodescope.android.feature.nodevision.VisionTerrainCache +import org.nodescope.android.feature.nodevision.VisionTerrainPoint +import org.nodescope.android.feature.nodevision.discoveryMarkerY +import org.nodescope.android.feature.nodevision.stableVisionAltitude +import org.nodescope.android.feature.nodevision.visionAntennaHeight +import org.nodescope.android.feature.nodevision.visionElevationMode +import org.nodescope.android.feature.coverage.CoverageHeightPreset +import org.nodescope.android.feature.linkprofile.ElevationPoint +import org.nodescope.android.feature.linkprofile.LinkTerrainProviding +import org.nodescope.android.feature.linkprofile.ProfileCoordinate +import org.nodescope.android.feature.linkprofile.TerrainProfile import org.nodescope.android.feature.nodevision.VisionHeadingWarmup import org.nodescope.android.core.model.FieldCardinalDirection import org.nodescope.android.core.model.FieldCoordinate @@ -110,3 +125,59 @@ class FieldGeometryTest { assertNull(warmup.settledHeading(20.0, 770)) } } + + +class NodeVisionElevationTest { + @Test fun discoveryMarkersLeaveTheEdgesWhenTiltedFartherAway() { + assertEquals(166.0, discoveryMarkerY(-24.0, 800.0, 166.0, 700.0)) + assertEquals(700.0, discoveryMarkerY(824.0, 800.0, 166.0, 700.0)) + assertNull(discoveryMarkerY(-25.0, 800.0, 166.0, 700.0)) + assertNull(discoveryMarkerY(825.0, 800.0, 166.0, 700.0)) + } + + @Test fun reportedAndDefaultHeights() { + assertEquals(VisionAntennaHeight(12.0, false), visionAntennaHeight("repeater", 12.0)) + for (role in listOf("repeater", "room", "room-server")) { + assertEquals(VisionAntennaHeight(CoverageHeightPreset.ROOFTOP.meters, true), visionAntennaHeight(role, null)) + } + assertEquals(VisionAntennaHeight(CoverageHeightPreset.HANDHELD.meters, true), visionAntennaHeight("companion", 12.0)) + } + + @Test fun placementModeAppliesToEveryMarker() { + val distances = listOf(30.0, 500.0) + for (mode in listOf(visionElevationMode(null, 2.0, distances, 5.0), + visionElevationMode(100.0, 10.0, distances, 5.0))) { + assertEquals(VisionElevationMode.Guide, mode) + assertEquals(mode.offset(30.0, null, 2.0, 0.5), mode.offset(500.0, 150.0, 2.0, 0.5)) + } + val mode = visionElevationMode(100.0, 2.0, listOf(500.0), 5.0) + assertEquals(VisionElevationMode.Elevation(100.0, 2.0), mode) + assertNull(mode.offset(500.0, null, 2.0, 0.5)) + assertTrue(mode.offset(500.0, 150.0, 2.0, 0.5) != null) + } + + @Test fun altitudeDeadbandAccumulatesChanges() { + val stable = stableVisionAltitude(100.0, 100.2, 100.0) + assertEquals(100.0, stable) + assertEquals(100.3, stableVisionAltitude(stable, 100.3, 100.0)) + assertNull(stableVisionAltitude(stable, null, 100.0)) + } + + @Test fun terrainBatchesCacheByNodeAndCoordinateAndKeepSuccessfulBatches() = runBlocking { + val requests = mutableListOf>() + val cache = VisionTerrainCache(LinkTerrainProviding { coordinates -> + requests.add(coordinates) + if (requests.size == 2) throw IOException() + TerrainProfile(coordinates.map { ElevationPoint(0.0, 42.0) }, 0, "network", coordinates) + }) + val points = (0..100).map { VisionTerrainPoint(it.toString().padStart(3, '0'), ProfileCoordinate(it / 100.0, 0.0)) }.toSet() + val first = cache.resolve(points) + assertEquals(100, first.size) + assertEquals(listOf(100, 2), requests.map { it.size }) + cache.resolve(points) + assertEquals(2, requests.size) + val moved = VisionTerrainPoint("000", ProfileCoordinate(2.0, 0.0)) + assertEquals(42.0, cache.resolve(first.keys + moved)[moved]) + assertEquals(listOf(moved.coordinate, moved.coordinate), requests.last()) + } +} diff --git a/android/app/src/test/java/org/nodescope/android/MapEngineTest.kt b/android/app/src/test/java/org/nodescope/android/MapEngineTest.kt index 14850fb4..db9a7e76 100644 --- a/android/app/src/test/java/org/nodescope/android/MapEngineTest.kt +++ b/android/app/src/test/java/org/nodescope/android/MapEngineTest.kt @@ -56,10 +56,15 @@ class MapEngineTest { assertEquals(21.0, fitCamera(CameraTarget.Bounds(30.0, -97.0, 30.0, -97.0), 500, 500, FramingInsets(0, 0, 0, 0), density).zoom, 1e-9) } - @Test fun savedGoogleChoiceFallsBackToCartoWithoutAKey() { - val google = MapProviderChoice(MapProvider.GOOGLE, GoogleMapType.SATELLITE) - assertEquals(MapProvider.CARTO, google.available(false).provider) - assertEquals(google, google.available(true)) + @Test fun googleIsTheDefaultWhenAvailable() { + assertEquals(MapProvider.GOOGLE, resolveMapProvider(null, googleAvailable = true)) + assertEquals(MapProvider.CARTO, resolveMapProvider(null, googleAvailable = false)) + } + + @Test fun savedProviderIsHonoredWhenAvailable() { + assertEquals(MapProvider.CARTO, resolveMapProvider(MapProvider.CARTO, googleAvailable = true)) + assertEquals(MapProvider.GOOGLE, resolveMapProvider(MapProvider.GOOGLE, googleAvailable = true)) + assertEquals(MapProvider.CARTO, resolveMapProvider(MapProvider.GOOGLE, googleAvailable = false)) } @Test fun mapLoadErrorsSayWhyTheMapFailed() {