diff --git a/app/src/main/java/com/bitchat/android/ui/globe/GlobeMath.kt b/app/src/main/java/com/bitchat/android/ui/globe/GlobeMath.kt index 181d383bd..544e87b0a 100644 --- a/app/src/main/java/com/bitchat/android/ui/globe/GlobeMath.kt +++ b/app/src/main/java/com/bitchat/android/ui/globe/GlobeMath.kt @@ -39,6 +39,27 @@ object GlobeMath { } } + /** + * Frame-local projector for arbitrary coordinates in double precision, for geometry such + * as geohash cells that must stay steady at deep zoom. Writes x, y, cosC like + * [PreparedProjector] without allocating. + */ + class PreciseProjector(centerLatDeg: Double, private val centerLonDeg: Double) { + private val sinCenterLat = sin(Math.toRadians(centerLatDeg)) + private val cosCenterLat = cos(Math.toRadians(centerLatDeg)) + + fun project(latDeg: Double, lonDeg: Double, out: FloatArray, outOffset: Int) { + val phi = Math.toRadians(latDeg) + val dLambda = Math.toRadians(normalizeLon(lonDeg - centerLonDeg)) + val sinPhi = sin(phi) + val cosPhi = cos(phi) + val cosDLambda = cos(dLambda) + out[outOffset] = (cosPhi * sin(dLambda)).toFloat() + out[outOffset + 1] = (-(cosCenterLat * sinPhi - sinCenterLat * cosPhi * cosDLambda)).toFloat() + out[outOffset + 2] = (sinCenterLat * sinPhi + cosCenterLat * cosPhi * cosDLambda).toFloat() + } + } + /** * Projects (lat, lon) onto the view disc of a globe centered at (centerLat, centerLon). * Returns x/y in units of globe radius (screen y down). [Projection.cosC] is negative diff --git a/app/src/main/java/com/bitchat/android/ui/globe/GlobeRenderer.kt b/app/src/main/java/com/bitchat/android/ui/globe/GlobeRenderer.kt new file mode 100644 index 000000000..50b880942 --- /dev/null +++ b/app/src/main/java/com/bitchat/android/ui/globe/GlobeRenderer.kt @@ -0,0 +1,724 @@ +package com.bitchat.android.ui.globe + +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathFillType +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import com.bitchat.android.geohash.Geohash +import kotlin.math.abs +import kotlin.math.atan2 +import kotlin.math.ceil +import kotlin.math.cos +import kotlin.math.sin +import kotlin.math.sqrt + +/** + * Draws the globe's vector geometry: graticule, land, coastlines, country borders and the + * geohash grid. + * + * Every frame draws the same full detail, moving or not, so nothing flickers in and out while + * dragging. That is affordable because a frame allocates nothing per point: projected points, + * fill polygons and clip buffers are primitive arrays reused across frames, and each layer of + * geometry is batched into a handful of reused paths instead of one path per ring or run. + */ +internal class GlobeRenderer { + private val clip = ClipRect() + private var projected = FloatArray(3 * 256) + private val polygon = PointBuffer(512) + private val clipBufferA = PointBuffer(512) + private val clipBufferB = PointBuffer(512) + private val probes = FillProbes() + + private val graticulePath = SegmentPath() + private val coastPath = SegmentPath() + private val borderPath = SegmentPath() + private val landPath = Path() + private val invertedLandPath = Path() + + private val neighborFillPath = Path() + private val selectedFillPath = Path() + private val neighborStrokePath = SegmentPath() + private val selectedStrokePath = SegmentPath() + + /** + * Skia's edge rasterizer loses precision with path coordinates beyond ~32767px, which + * happens at high globe zoom, so all geometry is clipped to an expanded viewport first. + */ + fun beginFrame(width: Float, height: Float) { + clip.set(-width, -height, width * 2f, height * 2f) + } + + fun DrawScope.drawGraticule( + projector: GlobeMath.PreciseProjector, + cx: Float, + cy: Float, + r: Float, + color: Color + ) { + graticulePath.reset() + for (line in GRATICULE) { + val n = line.size / 2 + ensureProjected(n) + var anyFront = false + for (i in 0 until n) { + projector.project(line[i * 2], line[i * 2 + 1], projected, i * 3) + if (projected[i * 3 + 2] > FRONT_COS) anyFront = true + } + if (anyFront) { + graticulePath.addProjectedLine(projected, n, closed = false, cx, cy, r, clip) + } + } + drawPath(graticulePath.path, color, style = Stroke(width = 1f)) + } + + fun DrawScope.drawLand( + land: List, + projector: GlobeMath.PreparedProjector, + cx: Float, + cy: Float, + r: Float, + centerLat: Double, + centerLon: Double, + fill: Color, + coastline: Color, + coastlineWidth: Float + ) { + landPath.rewind() + coastPath.reset() + probes.invalidate() + for (ring in land) { + val n = ring.size + if (n < 3) continue + ensureProjected(n) + var anyFront = false + var anyBack = false + for (i in 0 until n) { + projector.project(ring.projectionTerms, i * 4, projected, i * 3) + val cosC = projected[i * 3 + 2] + if (cosC > FRONT_COS) anyFront = true + if (cosC < 0f) anyBack = true + } + if (!anyFront) continue + + buildFillPolygon(projected, n, cx, cy, r, polygon) + // Fills of every landmass go into one path wound the same way, so they union into a + // single draw. The rare ring whose horizon closure needs flipping is drawn alone. + val invert = anyBack && projectedFillNeedsInversion( + polygon, ring, cx, cy, r, probes.at(centerLat, centerLon) + ) + val clipped = clipPolygon(polygon, clip, clipBufferA, clipBufferB) + if (clipped.size >= 3) { + if (invert) { + invertedLandPath.rewind() + invertedLandPath.fillType = PathFillType.EvenOdd + invertedLandPath.addOval(Rect(cx - r, cy - r, cx + r, cy + r)) + invertedLandPath.addPolygon(clipped, counterClockwise = null) + drawPath(invertedLandPath, fill) + } else { + landPath.addPolygon(clipped, counterClockwise = true) + } + } + coastPath.addProjectedLine(projected, n, closed = true, cx, cy, r, clip) + } + drawPath(landPath, fill) + // Coastlines go on after every fill, so a continent can never cover an island's outline. + drawPath(coastPath.path, coastline, style = Stroke(width = coastlineWidth)) + } + + fun DrawScope.drawBorders( + borders: List, + projector: GlobeMath.PreparedProjector, + cx: Float, + cy: Float, + r: Float, + color: Color, + width: Float + ) { + borderPath.reset() + for (line in borders) { + val n = line.size + if (n < 2) continue + ensureProjected(n) + var anyFront = false + for (i in 0 until n) { + projector.project(line.projectionTerms, i * 4, projected, i * 3) + if (projected[i * 3 + 2] > FRONT_COS) anyFront = true + } + if (anyFront) borderPath.addProjectedLine(projected, n, closed = false, cx, cy, r, clip) + } + drawPath(borderPath.path, color, style = Stroke(width = width)) + } + + /** The selected cell and its neighbors; the selection is drawn last so it stays on top. */ + fun DrawScope.drawGeohashGrid( + selected: String, + projector: GlobeMath.PreciseProjector, + cx: Float, + cy: Float, + r: Float, + accent: Color, + grid: Color + ) { + neighborFillPath.rewind() + selectedFillPath.rewind() + neighborStrokePath.reset() + selectedStrokePath.reset() + + addCell(selected, projector, cx, cy, r, selectedFillPath, selectedStrokePath) + for (cell in Geohash.neighborsSamePrecision(selected)) { + if (cell != selected) { + addCell(cell, projector, cx, cy, r, neighborFillPath, neighborStrokePath) + } + } + + drawPath(neighborFillPath, grid.copy(alpha = 0.05f)) + drawPath(neighborStrokePath.path, grid, style = Stroke(width = 1.6f)) + drawPath(selectedFillPath, accent.copy(alpha = 0.20f)) + drawPath(selectedStrokePath.path, accent.copy(alpha = 0.35f), style = Stroke(width = 7f)) + drawPath(selectedStrokePath.path, accent, style = Stroke(width = 3.2f)) + } + + private fun addCell( + cell: String, + projector: GlobeMath.PreciseProjector, + cx: Float, + cy: Float, + r: Float, + fillPath: Path, + strokePath: SegmentPath + ) { + val b = Geohash.decodeToBounds(cell) + val spanLat = b.latMax - b.latMin + val spanLon = b.lonMax - b.lonMin + val steps = ceil(spanLat / 1.5).toInt().coerceIn(4, 48) + val n = steps * 4 + ensureProjected(n) + + // Sample the boundary without repeating corners: N edge west to east, E edge north to + // south, S edge east to west, W edge south to north. + var count = 0 + var anyFront = false + fun add(lat: Double, lon: Double) { + projector.project(lat, lon, projected, count * 3) + if (projected[count * 3 + 2] > FRONT_COS) anyFront = true + count++ + } + for (s in 0 until steps) add(b.latMax, b.lonMin + spanLon * s / steps) + for (s in 0 until steps) add(b.latMax - spanLat * s / steps, b.lonMax) + for (s in 0 until steps) add(b.latMin, b.lonMax - spanLon * s / steps) + for (s in 0 until steps) add(b.latMin + spanLat * s / steps, b.lonMin) + if (!anyFront) return + + buildFillPolygon(projected, count, cx, cy, r, polygon) + val clipped = clipPolygon(polygon, clip, clipBufferA, clipBufferB) + if (clipped.size >= 3) fillPath.addPolygon(clipped, counterClockwise = true) + strokePath.addProjectedLine(projected, count, closed = true, cx, cy, r, clip) + } + + private fun ensureProjected(points: Int) { + if (projected.size < points * 3) projected = FloatArray(points * 3) + } +} + +/** A point counts as on the near side once it has turned this far toward the viewer. */ +internal const val FRONT_COS = 0.005f + +/** + * Consecutive visible points further apart than this (squared, in globe radii) are a polygon + * jumping across the view, such as Antarctica's closure along the antimeridian, not an edge. + */ +private const val MAX_EDGE_SQUARED = 1.2f + +private const val GRATICULE_SPACING_DEGREES = 15 +private const val GRATICULE_STEP_DEGREES = 4 + +/** Graticule polylines as flat (lat, lon) degree pairs: parallels to ±75°, then meridians. */ +private val GRATICULE: List = buildList { + for (lat in -75..75 step GRATICULE_SPACING_DEGREES) { + val lons = (-180..180 step GRATICULE_STEP_DEGREES).toList() + add(DoubleArray(lons.size * 2) { if (it % 2 == 0) lat.toDouble() else lons[it / 2].toDouble() }) + } + for (lon in -180 until 180 step GRATICULE_SPACING_DEGREES) { + val lats = (-90..90 step GRATICULE_STEP_DEGREES).toList() + add(DoubleArray(lats.size * 2) { if (it % 2 == 0) lats[it / 2].toDouble() else lon.toDouble() }) + } +} + +internal class ClipRect( + var left: Float = 0f, + var top: Float = 0f, + var right: Float = 0f, + var bottom: Float = 0f +) { + fun set(left: Float, top: Float, right: Float, bottom: Float) { + this.left = left + this.top = top + this.right = right + this.bottom = bottom + } + + fun contains(x: Float, y: Float): Boolean = x >= left && x <= right && y >= top && y <= bottom +} + +/** Interleaved (x, y) points in a growable array that is reused across frames. */ +internal class PointBuffer(initialCapacity: Int = 64) { + var coords = FloatArray(initialCapacity * 2) + private set + var size = 0 + private set + + fun clear() { + size = 0 + } + + fun add(x: Float, y: Float) { + val index = size * 2 + if (index + 2 > coords.size) coords = coords.copyOf(maxOf(coords.size * 2, 16)) + coords[index] = x + coords[index + 1] = y + size++ + } + + fun x(i: Int): Float = coords[i * 2] + fun y(i: Int): Float = coords[i * 2 + 1] +} + +/** Receives the clipped segments of projected lines. */ +internal interface SegmentSink { + /** Adds a segment, continuing the current polyline when it starts where the last one ended. */ + fun segment(x0: Float, y0: Float, x1: Float, y1: Float) + + /** Ends the current polyline. */ + fun lift() +} + +/** + * Walks a projected line (x, y, cosC triples in globe radii) and emits the parts on the near + * hemisphere as screen-space segments. A segment that turns over the horizon is cut where it + * crosses the limb, so outlines run right up to the globe's edge. + */ +internal fun SegmentSink.addProjectedLine( + points: FloatArray, + n: Int, + closed: Boolean, + cx: Float, + cy: Float, + r: Float, + clip: ClipRect +) { + if (n < 2) return + lift() + for (i in (if (closed) 0 else 1) until n) { + val prev = if (i == 0) n - 1 else i - 1 + val prevCos = points[prev * 3 + 2] + val curCos = points[i * 3 + 2] + val prevFront = prevCos > FRONT_COS + val curFront = curCos > FRONT_COS + if (!prevFront && !curFront) { + lift() + continue + } + var ax = points[prev * 3] + var ay = points[prev * 3 + 1] + var bx = points[i * 3] + var by = points[i * 3 + 1] + if (!prevFront) { + val t = limbFraction(curCos, prevCos) + ax = bx + (ax - bx) * t + ay = by + (ay - by) * t + val len = sqrt(ax * ax + ay * ay) + if (len > 1e-6f) { + ax /= len + ay /= len + } + } else if (!curFront) { + val t = limbFraction(prevCos, curCos) + bx = ax + (bx - ax) * t + by = ay + (by - ay) * t + val len = sqrt(bx * bx + by * by) + if (len > 1e-6f) { + bx /= len + by /= len + } + } + val dx = bx - ax + val dy = by - ay + if (dx * dx + dy * dy > MAX_EDGE_SQUARED) { + lift() + continue + } + clipSegment(cx + ax * r, cy + ay * r, cx + bx * r, cy + by * r, clip) + if (!curFront) lift() + } +} + +/** How far from the front point toward the back one the chord crosses the horizon plane. */ +private fun limbFraction(frontCos: Float, backCos: Float): Float { + val denominator = frontCos - backCos + return if (denominator <= 0f) 1f else (frontCos / denominator).coerceIn(0f, 1f) +} + +/** Liang–Barsky clip of a segment to [clip]; emits the visible part, if any. */ +private fun SegmentSink.clipSegment( + x0: Float, + y0: Float, + x1: Float, + y1: Float, + clip: ClipRect +) { + if (clip.contains(x0, y0) && clip.contains(x1, y1)) { + segment(x0, y0, x1, y1) + return + } + val dx = x1 - x0 + val dy = y1 - y0 + var u1 = 0f + var u2 = 1f + // Each edge: p is the direction toward outside, q the distance from the start to the edge. + for (edge in 0 until 4) { + val p: Float + val q: Float + when (edge) { + 0 -> { p = -dx; q = x0 - clip.left } + 1 -> { p = dx; q = clip.right - x0 } + 2 -> { p = -dy; q = y0 - clip.top } + else -> { p = dy; q = clip.bottom - y0 } + } + if (p == 0f) { + if (q < 0f) { + lift() + return + } + continue + } + val ratio = q / p + if (p < 0f) { + if (ratio > u2) { + lift() + return + } + if (ratio > u1) u1 = ratio + } else { + if (ratio < u1) { + lift() + return + } + if (ratio < u2) u2 = ratio + } + } + if (u1 > 0f) lift() + segment(x0 + u1 * dx, y0 + u1 * dy, x0 + u2 * dx, y0 + u2 * dy) + if (u2 < 1f) lift() +} + +/** Builds stroked polylines into one reused [path]. */ +internal class SegmentPath : SegmentSink { + val path = Path() + private var penX = 0f + private var penY = 0f + private var hasPen = false + + fun reset() { + path.rewind() + hasPen = false + } + + override fun segment(x0: Float, y0: Float, x1: Float, y1: Float) { + if (!hasPen || x0 != penX || y0 != penY) path.moveTo(x0, y0) + path.lineTo(x1, y1) + penX = x1 + penY = y1 + hasPen = true + } + + override fun lift() { + hasPen = false + } +} + +/** + * Builds a fill polygon for a projected ring (x, y, cosC triples) by clamping back-facing + * points onto the limb and inserting horizon arc steps between consecutive limb points, so the + * result approximates (polygon ∩ visible disc) without self-intersecting chords. + */ +internal fun buildFillPolygon( + points: FloatArray, + n: Int, + cx: Float, + cy: Float, + r: Float, + out: PointBuffer +) { + out.clear() + var hasPrevLimb = false + var prevLimbAngle = 0f + var hasFirstLimb = false + var firstLimbAngle = 0f + + for (i in 0 until n) { + val x = points[i * 3] + val y = points[i * 3 + 1] + if (points[i * 3 + 2] > FRONT_COS) { + out.add(cx + x * r, cy + y * r) + hasPrevLimb = false + } else { + val len = sqrt(x * x + y * y) + val lx: Float + val ly: Float + if (len > 1e-6f) { + lx = x / len + ly = y / len + } else { + lx = 0f + ly = -1f + } + val angle = atan2(ly, lx) + if (hasPrevLimb) addHorizonArc(out, prevLimbAngle, angle, cx, cy, r) + if (!hasFirstLimb) { + hasFirstLimb = true + firstLimbAngle = angle + } + out.add(cx + lx * r, cy + ly * r) + hasPrevLimb = true + prevLimbAngle = angle + } + } + // Wrap-around arc when the ring both ends and starts on the limb. + if (hasPrevLimb && hasFirstLimb && n > 0 && points[2] <= FRONT_COS) { + addHorizonArc(out, prevLimbAngle, firstLimbAngle, cx, cy, r) + } +} + +private const val TWO_PI = (2 * Math.PI).toFloat() +private const val PI_F = Math.PI.toFloat() + +private fun addHorizonArc(out: PointBuffer, from: Float, to: Float, cx: Float, cy: Float, r: Float) { + var d = to - from + while (d > PI_F) d -= TWO_PI + while (d < -PI_F) d += TWO_PI + val steps = (abs(d) / 0.04f).toInt().coerceIn(1, 64) + for (s in 1 until steps) { + val a = from + d * s / steps + out.add(cx + cos(a) * r, cy + sin(a) * r) + } +} + +/** + * Sutherland–Hodgman clip of [input] to [rect], using [a] and [b] as scratch. Returns the buffer + * holding the result, which is [input] itself when nothing needed clipping. + */ +internal fun clipPolygon(input: PointBuffer, rect: ClipRect, a: PointBuffer, b: PointBuffer): PointBuffer { + var inside = true + for (i in 0 until input.size) { + if (!rect.contains(input.x(i), input.y(i))) { + inside = false + break + } + } + if (inside) return input + clipEdge(input, a, CLIP_LEFT, rect.left) + clipEdge(a, b, CLIP_RIGHT, rect.right) + clipEdge(b, a, CLIP_TOP, rect.top) + clipEdge(a, b, CLIP_BOTTOM, rect.bottom) + return b +} + +private const val CLIP_LEFT = 0 +private const val CLIP_RIGHT = 1 +private const val CLIP_TOP = 2 +private const val CLIP_BOTTOM = 3 + +private fun isInside(edge: Int, bound: Float, x: Float, y: Float): Boolean = when (edge) { + CLIP_LEFT -> x >= bound + CLIP_RIGHT -> x <= bound + CLIP_TOP -> y >= bound + else -> y <= bound +} + +private fun clipEdge(input: PointBuffer, output: PointBuffer, edge: Int, bound: Float) { + output.clear() + val n = input.size + if (n == 0) return + var sx = input.x(n - 1) + var sy = input.y(n - 1) + var sIn = isInside(edge, bound, sx, sy) + for (i in 0 until n) { + val ex = input.x(i) + val ey = input.y(i) + val eIn = isInside(edge, bound, ex, ey) + if (eIn != sIn) { + if (edge == CLIP_LEFT || edge == CLIP_RIGHT) { + val t = (bound - sx) / (ex - sx) + output.add(bound, sy + t * (ey - sy)) + } else { + val t = (bound - sy) / (ey - sy) + output.add(sx + t * (ex - sx), bound) + } + } + if (eIn) output.add(ex, ey) + sx = ex + sy = ey + sIn = eIn + } +} + +/** + * Appends [polygon] as a closed contour. With [counterClockwise] set, the contour is wound + * that way regardless of its source order, so overlapping contours union under non-zero fill. + */ +internal fun Path.addPolygon(polygon: PointBuffer, counterClockwise: Boolean?) { + val n = polygon.size + if (n < 3) return + val reverse = counterClockwise != null && + (signedArea(polygon) > 0f) != counterClockwise + if (reverse) { + moveTo(polygon.x(n - 1), polygon.y(n - 1)) + for (i in n - 2 downTo 0) lineTo(polygon.x(i), polygon.y(i)) + } else { + moveTo(polygon.x(0), polygon.y(0)) + for (i in 1 until n) lineTo(polygon.x(i), polygon.y(i)) + } + close() +} + +/** Shoelace area; positive for counter-clockwise winding in a y-up frame. */ +internal fun signedArea(polygon: PointBuffer): Float { + var sum = 0.0 + val n = polygon.size + var px = polygon.x(n - 1) + var py = polygon.y(n - 1) + for (i in 0 until n) { + val x = polygon.x(i) + val y = polygon.y(i) + sum += px.toDouble() * y - x.toDouble() * py + px = x + py = y + } + return (sum / 2.0).toFloat() +} + +internal fun polygonContains(polygon: PointBuffer, x: Float, y: Float): Boolean { + val n = polygon.size + if (n < 3) return false + var inside = false + var px = polygon.x(n - 1) + var py = polygon.y(n - 1) + for (i in 0 until n) { + val qx = polygon.x(i) + val qy = polygon.y(i) + if ((qy > y) != (py > y)) { + val intersectionX = (px - qx) * (y - qy) / (py - qy) + qx + if (x < intersectionX) inside = !inside + } + px = qx + py = qy + } + return inside +} + +/** + * Points on the visible disc where a land fill's projected and geographic insides are + * compared. They depend only on the view center, so they are unprojected once per frame. + */ +internal class FillProbes { + val count get() = size + val discX = FloatArray(SAMPLES.size) + val discY = FloatArray(SAMPLES.size) + val latitude = DoubleArray(SAMPLES.size) + val longitude = DoubleArray(SAMPLES.size) + private var size = 0 + private var valid = false + + fun invalidate() { + valid = false + } + + fun at(centerLat: Double, centerLon: Double): FillProbes { + if (valid) return this + size = 0 + for ((nx, ny) in SAMPLES) { + val location = GlobeMath.unproject(nx.toDouble(), ny.toDouble(), centerLat, centerLon) ?: continue + discX[size] = nx + discY[size] = ny + latitude[size] = location.first + longitude[size] = location.second + size++ + } + valid = true + return this + } + + private companion object { + val SAMPLES = arrayOf( + 0f to 0f, + -0.5f to 0f, + 0.5f to 0f, + 0f to -0.5f, + 0f to 0.5f, + -0.35f to -0.35f, + 0.35f to -0.35f, + -0.35f to 0.35f, + 0.35f to 0.35f + ) + } +} + +/** + * Orthographic projection can choose the wrong side of the horizon closure for very large rings. + * A single center-point check is ambiguous for a large polygon and caused an occasional + * whole-disc fill, so several visible points are compared with the original geographic ring, + * and the fill is inverted only when the opposite side wins clearly. + */ +internal fun projectedFillNeedsInversion( + polygon: PointBuffer, + ring: LandData.Ring, + cx: Float, + cy: Float, + r: Float, + probes: FillProbes +): Boolean { + var normalErrors = 0 + var invertedErrors = 0 + for (i in 0 until probes.count) { + val geographicInside = ringContainsLocation(ring, probes.latitude[i], probes.longitude[i]) + val projectedInside = polygonContains(polygon, cx + probes.discX[i] * r, cy + probes.discY[i] * r) + if (projectedInside != geographicInside) normalErrors++ + if (!projectedInside != geographicInside) invertedErrors++ + } + return invertedErrors < normalErrors +} + +/** + * Point-in-ring test in geographic space: counts the ring edges that cross the probe's meridian + * north of it. Each edge is followed the short way around, so neither the ±180° seam nor the + * probe's antimeridian creates a false crossing. Casting the ray along a parallel instead wrapped + * edges near the probe's antimeridian from +180° to -180°, so a Pacific probe saw Europe's coast + * as crossings and Eurasia "contained" the Pacific, inverting its fill. Matches the iOS globe. + */ +internal fun ringContainsLocation( + ring: LandData.Ring, + latitude: Double, + longitude: Double +): Boolean { + if (ring.size < 3) return false + var inside = false + var previousIndex = ring.size - 1 + for (index in 0 until ring.size) { + val startLat = ring.coords[previousIndex * 2].toDouble() + val endLat = ring.coords[index * 2].toDouble() + val startLon = ring.coords[previousIndex * 2 + 1].toDouble() + val endLon = ring.coords[index * 2 + 1].toDouble() + val start = GlobeMath.normalizeLon(startLon - longitude) + // Unbounded on purpose: the end changes sign relative to the start only when the + // edge crosses the probe meridian, never when it crosses ±180°. + val end = start + GlobeMath.normalizeLon(endLon - startLon) + if ((start > 0.0) != (end > 0.0)) { + val t = start / (start - end) + if (startLat + (endLat - startLat) * t > latitude) inside = !inside + } + previousIndex = index + } + return inside +} diff --git a/app/src/main/java/com/bitchat/android/ui/globe/GlobeState.kt b/app/src/main/java/com/bitchat/android/ui/globe/GlobeState.kt index 583db2bde..fee8748b4 100644 --- a/app/src/main/java/com/bitchat/android/ui/globe/GlobeState.kt +++ b/app/src/main/java/com/bitchat/android/ui/globe/GlobeState.kt @@ -3,6 +3,7 @@ package com.bitchat.android.ui.globe import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween +import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.Stable import androidx.compose.runtime.mutableDoubleStateOf @@ -209,9 +210,12 @@ class GlobeState( /** * Whether − can widen the view. Level 1 spans a range of zooms (the opening rotation lands * well inside it), so it can still pull back to the whole globe without changing precision. + * Derived so that the picker chrome reading it recomposes when the answer flips, not on + * every frame of a pinch or flight. */ - val canZoomOut: Boolean - get() = precision > 1 || zoom > GlobeMath.MIN_ZOOM * (1f + WHOLE_GLOBE_ZOOM_TOLERANCE) + val canZoomOut: Boolean by derivedStateOf { + precision > 1 || zoom > GlobeMath.MIN_ZOOM * (1f + WHOLE_GLOBE_ZOOM_TOLERANCE) + } /** The − button: one level coarser, or the whole globe when already at level 1. */ fun zoomOut() { diff --git a/app/src/main/java/com/bitchat/android/ui/globe/GlobeView.kt b/app/src/main/java/com/bitchat/android/ui/globe/GlobeView.kt index ac36c165c..892adc187 100644 --- a/app/src/main/java/com/bitchat/android/ui/globe/GlobeView.kt +++ b/app/src/main/java/com/bitchat/android/ui/globe/GlobeView.kt @@ -10,29 +10,23 @@ import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.calculatePan import androidx.compose.foundation.gestures.calculateZoom +import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow -import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.drawscope.DrawScope -import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.positionChanged @@ -46,9 +40,7 @@ import com.bitchat.android.geohash.Geohash import com.bitchat.android.nostr.GeohashChannelActivity import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.first -import kotlin.math.ceil import kotlin.math.min -import kotlin.math.sqrt /** Color palette for the globe, derived from the app theme by the caller. */ data class GlobeColors( @@ -69,154 +61,70 @@ data class GlobeColors( private class Star(val x: Float, val y: Float, val radius: Float, val alpha: Float) /** - * How much of the globe a moving frame draws. The geohash grid (selected cell and its neighbors) - * and the city dots are not part of this: both are cheap next to the land geometry, and making - * them vanish on touch and pop back on release read as flicker. + * The globe's gradients depend only on where the globe sits and how large it is, so they are + * rebuilt when it zooms, not on every frame of a drag. */ -internal data class GlobeFrameDetail( - val graticuleStepDegrees: Double, - val landPointStride: Int, - val showBorders: Boolean, - val showCityLabels: Boolean -) +private class GlobeShading { + private var cx = Float.NaN + private var cy = Float.NaN + private var r = Float.NaN + private var colors: GlobeColors? = null -internal enum class GlobeMotionDetail { - FULL, - BALANCED, - FAST -} + lateinit var atmosphere: Brush + private set + lateinit var ocean: Brush + private set + lateinit var limb: Brush + private set + lateinit var night: Brush + private set -internal fun globeFrameDetail(motionDetail: GlobeMotionDetail): GlobeFrameDetail = - when (motionDetail) { - GlobeMotionDetail.FULL -> GlobeFrameDetail( - graticuleStepDegrees = 4.0, - landPointStride = 1, - showBorders = true, - showCityLabels = true + fun update(cx: Float, cy: Float, r: Float, colors: GlobeColors) { + if (cx == this.cx && cy == this.cy && r == this.r && colors == this.colors) return + this.cx = cx + this.cy = cy + this.r = r + this.colors = colors + atmosphere = Brush.radialGradient( + 0f to colors.atmosphere.copy(alpha = 0.30f), + 0.75f to colors.atmosphere.copy(alpha = 0.12f), + 1f to Color.Transparent, + center = Offset(cx, cy), + radius = r * ATMOSPHERE_SCALE ) - GlobeMotionDetail.BALANCED -> GlobeFrameDetail( - graticuleStepDegrees = 8.0, - landPointStride = 2, - showBorders = true, - showCityLabels = false + ocean = Brush.radialGradient( + 0f to colors.oceanCenter, + 0.7f to colors.oceanCenter, + 1f to colors.oceanEdge, + center = Offset(cx - r * 0.32f, cy - r * 0.38f), + radius = r * 1.5f ) - GlobeMotionDetail.FAST -> GlobeFrameDetail( - graticuleStepDegrees = 10.0, - landPointStride = 2, - showBorders = false, - showCityLabels = false + limb = Brush.radialGradient( + 0f to Color.Transparent, + 0.62f to Color.Transparent, + 0.88f to Color.Black.copy(alpha = 0.34f), + 1f to Color.Black.copy(alpha = 0.72f), + center = Offset(cx - r * 0.25f, cy - r * 0.3f), + radius = r * 1.35f + ) + night = Brush.linearGradient( + 0f to Color.Transparent, + 0.55f to Color.Transparent, + 1f to Color.Black.copy(alpha = 0.42f), + start = Offset(cx - r * 0.7f, cy - r * 0.7f), + end = Offset(cx + r * 0.75f, cy + r * 0.8f) ) - } - -/** - * The level measured frame cadence calls for. Hysteresis alone cannot stop oscillation - * (shedding detail is what makes frames fast again), so [GlobeMotionGovernor] only ever - * applies downgrades while the globe is moving. - */ -internal fun nextGlobeMotionDetail( - current: GlobeMotionDetail, - averageFrameMillis: Float -): GlobeMotionDetail { - if (!averageFrameMillis.isFinite()) return GlobeMotionDetail.FAST - return when (current) { - GlobeMotionDetail.FULL -> when { - averageFrameMillis > SEVERELY_SLOW_FRAME_MILLIS -> GlobeMotionDetail.FAST - averageFrameMillis > SLOW_FRAME_MILLIS -> GlobeMotionDetail.BALANCED - else -> GlobeMotionDetail.FULL - } - GlobeMotionDetail.BALANCED -> when { - averageFrameMillis > VERY_SLOW_FRAME_MILLIS -> GlobeMotionDetail.FAST - averageFrameMillis < SMOOTH_FRAME_MILLIS -> GlobeMotionDetail.FULL - else -> GlobeMotionDetail.BALANCED - } - GlobeMotionDetail.FAST -> { - if (averageFrameMillis < RECOVERING_FRAME_MILLIS) { - GlobeMotionDetail.BALANCED - } else { - GlobeMotionDetail.FAST - } - } } } -private val GlobeMotionDetail.rank: Int - get() = when (this) { - GlobeMotionDetail.FAST -> 0 - GlobeMotionDetail.BALANCED -> 1 - GlobeMotionDetail.FULL -> 2 - } - -private val GlobeMotionDetail.moreDetailed: GlobeMotionDetail - get() = if (this == GlobeMotionDetail.FAST) GlobeMotionDetail.BALANCED else GlobeMotionDetail.FULL - /** - * Picks the detail level for moving frames. A motion session spans everything from touch-down - * through any fling or animation until the globe is at rest. + * The interactive globe. It draws the same full detail whether it is moving or at rest, so + * labels, borders and coastlines never drop out mid-drag. * - * Within a session detail only ever steps down: letting measured cadence step back up made - * neighbor cells, labels and borders flash on and off while dragging, because shedding detail - * is exactly what makes frames fast again. Between sessions, a smooth one lets the next start a - * level higher, until any session has had to shed detail. Matches the iOS globe. + * Each canvas below sits in its own graphics layer. Without one, Compose records every sibling + * canvas into the parent's layer, so the always-running crosshair pulse re-drew the whole globe + * on every frame even when nothing moved. */ -internal class GlobeMotionGovernor { - var detail: GlobeMotionDetail = GlobeMotionDetail.FULL - private set - var isSessionActive: Boolean = false - private set - - private var startDetail = GlobeMotionDetail.BALANCED - private var ceilingFound = false - private var sessionDegraded = false - private var windowMillis = 0f - private var windowCount = 0 - private var sessionMillis = 0f - private var sessionCount = 0 - - fun beginSession() { - if (isSessionActive) return - isSessionActive = true - sessionDegraded = false - windowMillis = 0f - windowCount = 0 - sessionMillis = 0f - sessionCount = 0 - detail = startDetail - } - - fun recordFrame(millis: Float) { - if (!isSessionActive) return - val frameMillis = millis.coerceIn(1f, MAX_SAMPLED_FRAME_MILLIS) - windowMillis += frameMillis - windowCount++ - sessionMillis += frameMillis - sessionCount++ - if (windowCount < FRAME_SAMPLE_COUNT) return - val wanted = nextGlobeMotionDetail(detail, windowMillis / windowCount) - if (wanted.rank < detail.rank) { - detail = wanted - sessionDegraded = true - } - windowMillis = 0f - windowCount = 0 - } - - /** Back to full detail at rest; remembers where the next session should start. */ - fun endSession() { - if (!isSessionActive) return - isSessionActive = false - if (sessionDegraded) { - ceilingFound = true - startDetail = detail - } else if (!ceilingFound && - sessionCount >= FRAME_SAMPLE_COUNT && - sessionMillis / sessionCount < SMOOTH_FRAME_MILLIS - ) { - startDetail = detail.moreDetailed - } - detail = GlobeMotionDetail.FULL - } -} - @Composable fun GlobeView( state: GlobeState, @@ -247,10 +155,8 @@ fun GlobeView( } } - val maxRingPoints = remember(land) { land.maxOfOrNull { it.size } ?: 0 } - val scratch = remember(maxRingPoints) { FloatArray(maxOf(1, maxRingPoints) * 3) } - val maxBorderPoints = remember(borders) { borders.maxOfOrNull { it.size } ?: 0 } - val borderScratch = remember(maxBorderPoints) { FloatArray(maxOf(1, maxBorderPoints) * 3) } + val renderer = remember { GlobeRenderer() } + val shading = remember { GlobeShading() } val labelPaint = remember { Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER } @@ -308,32 +214,12 @@ fun GlobeView( } } - val motionGovernor = remember(state) { GlobeMotionGovernor() } - var motionDetail by remember(state) { mutableStateOf(GlobeMotionDetail.FULL) } - LaunchedEffect(state, state.isInMotion) { - if (!state.isInMotion) { - motionGovernor.endSession() - motionDetail = motionGovernor.detail - return@LaunchedEffect - } - - motionGovernor.beginSession() - motionDetail = motionGovernor.detail - var previousFrameNanos = withFrameNanos { it } - while (state.isInMotion) { - val frameNanos = withFrameNanos { it } - motionGovernor.recordFrame((frameNanos - previousFrameNanos) / 1_000_000f) - previousFrameNanos = frameNanos - motionDetail = motionGovernor.detail - } - } - val labelTextSize = with(density) { 12.5.sp.toPx() } val labelTextSizeSmall = with(density) { 10.sp.toPx() } Box(modifier = modifier) { - // Static background lives in its own layer and is not invalidated by globe movement. - Canvas(modifier = Modifier.matchParentSize()) { + // Static background: its layer is recorded once and only replayed afterwards. + Canvas(modifier = Modifier.matchParentSize().graphicsLayer()) { stars.forEach { star -> drawCircle( color = colors.star.copy(alpha = star.alpha), @@ -345,11 +231,12 @@ fun GlobeView( Canvas( modifier = Modifier - .matchParentSize() - .onSizeChanged { size: IntSize -> - val minDim = min(size.width, size.height).toFloat() - state.setViewport(minDim * 0.44f, minDim) - } + .matchParentSize() + .graphicsLayer() + .onSizeChanged { size: IntSize -> + val minDim = min(size.width, size.height).toFloat() + state.setViewport(minDim * 0.44f, minDim) + } .pointerInput(state) { var lastTapTime = 0L var lastTapPos = Offset.Zero @@ -443,133 +330,63 @@ fun GlobeView( } } ) { - val cx = size.width / 2f - val cy = size.height / 2f - val baseR = state.baseRadiusPx - if (baseR <= 0f) return@Canvas - val r = state.globeRadiusPx - val cLat = state.centerLat - val cLon = state.centerLon - val preparedProjector = GlobeMath.PreparedProjector(cLat, cLon) + val cx = size.width / 2f + val cy = size.height / 2f + if (state.baseRadiusPx <= 0f) return@Canvas + val r = state.globeRadiusPx + val cLat = state.centerLat + val cLon = state.centerLon + val center = Offset(cx, cy) + val projector = GlobeMath.PreparedProjector(cLat, cLon) + val preciseProjector = GlobeMath.PreciseProjector(cLat, cLon) - // Atmosphere glow - drawCircle( - brush = Brush.radialGradient( - 0f to colors.atmosphere.copy(alpha = 0.30f), - 0.75f to colors.atmosphere.copy(alpha = 0.12f), - 1f to Color.Transparent, - center = Offset(cx, cy), - radius = r * 1.22f - ), - radius = r * 1.22f, - center = Offset(cx, cy) - ) + shading.update(cx, cy, r, colors) + drawCircle(brush = shading.atmosphere, radius = r * ATMOSPHERE_SCALE, center = center) + drawCircle(brush = shading.ocean, radius = r, center = center) - // Ocean sphere - drawCircle( - brush = Brush.radialGradient( - 0f to colors.oceanCenter, - 0.7f to colors.oceanCenter, - 1f to colors.oceanEdge, - center = Offset(cx - r * 0.32f, cy - r * 0.38f), - radius = r * 1.5f - ), - radius = r, - center = Offset(cx, cy) - ) + with(renderer) { + beginFrame(size.width, size.height) + drawGraticule(preciseProjector, cx, cy, r, colors.graticule) + drawLand( + land = land, + projector = projector, + cx = cx, + cy = cy, + r = r, + centerLat = cLat, + centerLon = cLon, + fill = colors.land, + coastline = colors.coastline, + coastlineWidth = COASTLINE_WIDTH_PX + ) + drawBorders(borders, projector, cx, cy, r, colors.border, BORDER_WIDTH_PX) + } - val clip = ClipRect(-size.width, -size.height, size.width * 2f, size.height * 2f) + // Sphere shading: dark limb + night side for 3D depth + drawCircle(brush = shading.limb, radius = r + 1, center = center) + drawCircle(brush = shading.night, radius = r + 1, center = center) - val frameDetail = globeFrameDetail( - if (state.isInMotion) motionDetail else GlobeMotionDetail.FULL - ) - - // Graticule - drawGraticule( - cx, cy, r, cLat, cLon, colors.graticule, clip, - step = frameDetail.graticuleStepDegrees - ) - - // Fill every landmass first. Coastlines are drawn in a separate final pass so a - // large continent fill can never cover an island outline drawn earlier. - val coastlineRuns = ArrayList>>>(land.size) - for (ring in land) { - val runs = drawLandFill( - ring = ring, - scratch = scratch, - projector = preparedProjector, - cx = cx, - cy = cy, - r = r, - colors = colors, - clip = clip, - pointStride = if (ring.size >= 64) frameDetail.landPointStride else 1, - centerLat = cLat, - centerLon = cLon + drawCities( + cities, state, projector, cx, cy, r, colors, + labelPaint, haloPaint, labelTypeface, labelTextSizeSmall, density.density ) - if (runs != null) coastlineRuns.add(runs) - } - for (runs in coastlineRuns) { - strokeRuns(runs, cx, cy, r, colors.coastline, 1.4f, clip) - } - // Country borders are restored when interaction settles. - if (frameDetail.showBorders) { - for (line in borders) { - drawBorderLine(line, borderScratch, preparedProjector, cx, cy, r, colors, clip) + val selected = state.selectedGeohash + if (selected.isNotEmpty()) { + with(renderer) { + drawGeohashGrid(selected, preciseProjector, cx, cy, r, colors.accent, colors.grid) + } + drawGeohashLabels( + state, cx, cy, r, cLat, cLon, colors, + labelPaint, haloPaint, labelTypeface, labelTypefaceBold, + labelTextSize, labelTextSizeSmall, + includeNeighbors = true + ) } } - // Sphere shading: dark limb + night side for 3D depth - drawCircle( - brush = Brush.radialGradient( - 0f to Color.Transparent, - 0.62f to Color.Transparent, - 0.88f to Color.Black.copy(alpha = 0.34f), - 1f to Color.Black.copy(alpha = 0.72f), - center = Offset(cx - r * 0.25f, cy - r * 0.3f), - radius = r * 1.35f - ), - radius = r + 1, - center = Offset(cx, cy) - ) - drawCircle( - brush = Brush.linearGradient( - 0f to Color.Transparent, - 0.55f to Color.Transparent, - 1f to Color.Black.copy(alpha = 0.42f), - start = Offset(cx - r * 0.7f, cy - r * 0.7f), - end = Offset(cx + r * 0.75f, cy + r * 0.8f) - ), - radius = r + 1, - center = Offset(cx, cy) - ) - - // City dots and the geohash grid draw at every detail level; only city labels are - // dropped while moving. - drawCities( - cities, state, preparedProjector, cx, cy, r, colors, - labelPaint, haloPaint, labelTypeface, labelTextSizeSmall, density.density, - showLabels = frameDetail.showCityLabels - ) - - if (state.selectedGeohash.isNotEmpty()) { - drawGeohashGrid( - state, cx, cy, r, cLat, cLon, colors, clip, - includeNeighbors = true - ) - drawGeohashLabels( - state, cx, cy, r, cLat, cLon, colors, - labelPaint, haloPaint, labelTypeface, labelTypefaceBold, - labelTextSize, labelTextSizeSmall, - includeNeighbors = true - ) - } - - } - - // Keep this animation isolated so its pulse does not redraw the globe geometry. - Canvas(modifier = Modifier.matchParentSize()) { + // The crosshair pulses forever; its own layer keeps that from re-drawing the globe. + Canvas(modifier = Modifier.matchParentSize().graphicsLayer()) { val cx = size.width / 2f val cy = size.height / 2f val crossAlpha = if (state.isInMotion) 0.9f else pulse @@ -586,7 +403,7 @@ fun GlobeView( // Activity markers get their own layer, above the crosshair so a centered marker's // count stays readable; their pulse never redraws the globe geometry. if (activityColors != null) { - Canvas(modifier = Modifier.matchParentSize()) { + Canvas(modifier = Modifier.matchParentSize().graphicsLayer()) { val markers = if (state.baseRadiusPx <= 0f || activity.isEmpty()) { emptyList() } else { @@ -629,432 +446,9 @@ fun GlobeView( } private const val MARKER_TAP_SLOP_DP = 12f -private const val FRAME_SAMPLE_COUNT = 8 -private const val MAX_SAMPLED_FRAME_MILLIS = 50f -private const val SMOOTH_FRAME_MILLIS = 18.5f -private const val SLOW_FRAME_MILLIS = 22f -private const val RECOVERING_FRAME_MILLIS = 22f -private const val VERY_SLOW_FRAME_MILLIS = 29f -private const val SEVERELY_SLOW_FRAME_MILLIS = 34f - -private fun DrawScope.drawGraticule( - cx: Float, - cy: Float, - r: Float, - cLat: Double, - cLon: Double, - color: Color, - clip: ClipRect, - step: Double -) { - val path = Path() - fun strokeSegment(x0: Float, y0: Float, x1: Float, y1: Float) { - val seg = clipSegment(x0, y0, x1, y1, clip) ?: return - path.moveTo(seg.first.first, seg.first.second) - path.lineTo(seg.second.first, seg.second.second) - } - // latitude lines - var lat = -75.0 - while (lat <= 75.0) { - var prev: GlobeMath.Projection? = null - var lon = -180.0 - while (lon <= 180.0) { - val p = GlobeMath.project(lat, lon, cLat, cLon) - if (p != null && p.cosC > 0.02f) { - val pp = prev - if (pp != null) strokeSegment(cx + pp.x * r, cy + pp.y * r, cx + p.x * r, cy + p.y * r) - prev = p - } else prev = null - lon += step - } - lat += 15.0 - } - // longitude lines - var lon = -180.0 - while (lon < 180.0) { - var prev: GlobeMath.Projection? = null - var la = -90.0 - while (la <= 90.0) { - val p = GlobeMath.project(la, lon, cLat, cLon) - if (p != null && p.cosC > 0.02f) { - val pp = prev - if (pp != null) strokeSegment(cx + pp.x * r, cy + pp.y * r, cx + p.x * r, cy + p.y * r) - prev = p - } else prev = null - la += step - } - lon += 15.0 - } - drawPath(path, color, style = Stroke(width = 1f)) -} - -internal data class DiscPt(val x: Float, val y: Float, val front: Boolean) - -private fun limbPoint(behind: DiscPt, front: DiscPt): Pair { - var lo = 0f; var hi = 1f - repeat(14) { - val t = (lo + hi) / 2f - val x = behind.x + (front.x - behind.x) * t - val y = behind.y + (front.y - behind.y) * t - if (x * x + y * y < 1f) lo = t else hi = t - } - val t = (lo + hi) / 2f - return (behind.x + (front.x - behind.x) * t) to (behind.y + (front.y - behind.y) * t) -} - -/** - * Splits a projected polygon into front-facing runs. Runs that touch the limb are - * padded with the horizon intersection point so they can be closed along the horizon. - * Pass [closed] = false for open polylines (border lines). - */ -internal fun buildFrontRuns( - pts: List, - closed: Boolean = true -): List>> { - if (pts.isEmpty()) return emptyList() - val n = pts.size - val runs = mutableListOf>>() - var run = mutableListOf>() - var prev: DiscPt? = if (closed) pts[n - 1] else null - for (i in 0 until n) { - val cur = pts[i] - val p = prev - if (cur.front) { - if (run.isEmpty() && p != null && !p.front) run.add(limbPoint(p, cur)) - // Antimeridian wrap: consecutive front points can jump across the whole - // disc when a polygon crosses ±180° — break the run instead of drawing - // a chord through the view. - if (run.isNotEmpty()) { - val last = run.last() - val dx = cur.x - last.first - val dy = cur.y - last.second - if (dx * dx + dy * dy > 1.2f) { - runs.add(run) - run = mutableListOf() - } - } - run.add(cur.x to cur.y) - } else { - if (run.isNotEmpty() && p != null) { - run.add(limbPoint(p, cur)) - runs.add(run) - run = mutableListOf() - } - } - prev = cur - } - if (run.isNotEmpty()) { - if (closed && runs.isNotEmpty() && pts[0].front && pts[n - 1].front) { - runs[0] = (run + runs[0]).toMutableList() - } else { - // A fully front-facing ring has no limb transition to terminate its run. - // Close it explicitly; cell boundary sampling intentionally omits the - // duplicated final corner. - if (closed && runs.isEmpty() && pts[0].front && pts[n - 1].front) { - run.add(run.first()) - } - runs.add(run) - } - } - return runs -} - -// Skia's edge rasterizer loses precision with path coordinates beyond ~32767px, -// which happens at high globe zoom. All geometry is clipped to an expanded -// viewport rect in screen space before being handed to a Path. -private class ClipRect(val left: Float, val top: Float, val right: Float, val bottom: Float) - -private fun clipPolygon(pts: List>, rect: ClipRect): List> { - fun clipEdge( - input: List>, - inside: (Pair) -> Boolean, - intersect: (Pair, Pair) -> Pair - ): List> { - if (input.isEmpty()) return input - val result = mutableListOf>() - var s = input.last() - for (e in input) { - val eIn = inside(e) - val sIn = inside(s) - if (eIn) { - if (!sIn) result.add(intersect(s, e)) - result.add(e) - } else if (sIn) { - result.add(intersect(s, e)) - } - s = e - } - return result - } - var out = pts - out = clipEdge(out, { it.first >= rect.left }) { a, b -> - val t = (rect.left - a.first) / (b.first - a.first) - rect.left to (a.second + t * (b.second - a.second)) - } - out = clipEdge(out, { it.first <= rect.right }) { a, b -> - val t = (rect.right - a.first) / (b.first - a.first) - rect.right to (a.second + t * (b.second - a.second)) - } - out = clipEdge(out, { it.second >= rect.top }) { a, b -> - val t = (rect.top - a.second) / (b.second - a.second) - (a.first + t * (b.first - a.first)) to rect.top - } - out = clipEdge(out, { it.second <= rect.bottom }) { a, b -> - val t = (rect.bottom - a.second) / (b.second - a.second) - (a.first + t * (b.first - a.first)) to rect.bottom - } - return out -} - -/** Liang–Barsky clip of a segment to the rect; returns clipped endpoints or null. */ -private fun clipSegment( - x0: Float, y0: Float, x1: Float, y1: Float, rect: ClipRect -): Pair, Pair>? { - val dx = x1 - x0 - val dy = y1 - y0 - var u1 = 0f - var u2 = 1f - fun test(p: Float, q: Float): Boolean { - if (p == 0f) return q >= 0f - val r = q / p - if (p < 0f) { - if (r > u2) return false - if (r > u1) u1 = r - } else { - if (r < u1) return false - if (r < u2) u2 = r - } - return true - } - if (!test(-dx, x0 - rect.left)) return null - if (!test(dx, rect.right - x0)) return null - if (!test(-dy, y0 - rect.top)) return null - if (!test(dy, rect.bottom - y0)) return null - return ((x0 + u1 * dx) to (y0 + u1 * dy)) to ((x0 + u2 * dx) to (y0 + u2 * dy)) -} - -/** - * Builds a fill polygon for a projected ring by clamping back-facing points onto the - * limb and inserting horizon arc steps between consecutive limb points, so the result - * approximates (polygon ∩ visible disc) without self-intersecting chords. - */ -private fun buildFillPolygon( - pts: List, - cx: Float, cy: Float, r: Float -): List> { - val out = ArrayList>(pts.size + 128) - var prevLimbAngle: Float? = null - var firstLimbAngle: Float? = null - - fun addArc(from: Float, to: Float) { - var d = to - from - while (d > Math.PI) d -= (2 * Math.PI).toFloat() - while (d < -Math.PI) d += (2 * Math.PI).toFloat() - val steps = (kotlin.math.abs(d) / 0.04f).toInt().coerceIn(1, 64) - for (s in 1 until steps) { - val a = from + d * s / steps - out.add((cx + kotlin.math.cos(a) * r) to (cy + kotlin.math.sin(a) * r)) - } - } - - for (p in pts) { - if (p.front) { - out.add((cx + p.x * r) to (cy + p.y * r)) - prevLimbAngle = null - } else { - val len = kotlin.math.sqrt(p.x * p.x + p.y * p.y) - val lx: Float; val ly: Float - if (len > 1e-6f) { lx = p.x / len; ly = p.y / len } else { lx = 0f; ly = -1f } - val ang = kotlin.math.atan2(ly, lx) - prevLimbAngle?.let { addArc(it, ang) } - if (firstLimbAngle == null) firstLimbAngle = ang - out.add((cx + lx * r) to (cy + ly * r)) - prevLimbAngle = ang - } - } - // wrap-around arc if the ring ends and starts on the limb - val lastAng = prevLimbAngle - val firstAng = firstLimbAngle - if (lastAng != null && firstAng != null && pts.isNotEmpty() && !pts[0].front) { - addArc(lastAng, firstAng) - } - return out -} - -private fun DrawScope.fillPolygonClipped( - pts: List, - cx: Float, cy: Float, r: Float, - color: Color, - clip: ClipRect, - invertFill: Boolean = false, - preparedPolygon: List>? = null -) { - if (pts.none { it.front }) return - val poly = preparedPolygon ?: buildFillPolygon(pts, cx, cy, r) - if (poly.size < 3) return - val clipped = clipPolygon(poly, clip) - if (clipped.size < 3) return - val path = Path() - if (invertFill) { - // Orthographic projection can choose the wrong side of the horizon closure for - // very large rings. Even-odd filling with the globe disc flips that one ring. - path.fillType = PathFillType.EvenOdd - path.addOval(Rect(cx - r, cy - r, cx + r, cy + r)) - } - path.moveTo(clipped[0].first, clipped[0].second) - for (k in 1 until clipped.size) { - path.lineTo(clipped[k].first, clipped[k].second) - } - path.close() - drawPath(path, color) -} - -internal fun projectedFillNeedsInversion( - polygon: List>, - ring: LandData.Ring, - cx: Float, - cy: Float, - r: Float, - centerLat: Double, - centerLon: Double -): Boolean { - // A single center-point check is ambiguous for a large polygon and caused an - // occasional whole-disc fill. Compare several visible points with the original - // geographic ring, and invert only when the opposite fill wins clearly. - val samples = arrayOf( - 0f to 0f, - -0.5f to 0f, - 0.5f to 0f, - 0f to -0.5f, - 0f to 0.5f, - -0.35f to -0.35f, - 0.35f to -0.35f, - -0.35f to 0.35f, - 0.35f to 0.35f - ) - var normalErrors = 0 - var invertedErrors = 0 - for ((nx, ny) in samples) { - val location = GlobeMath.unproject( - x = nx.toDouble(), - y = ny.toDouble(), - centerLatDeg = centerLat, - centerLonDeg = centerLon - ) ?: continue - val geographicInside = ringContainsLocation(ring, location.first, location.second) - val projectedInside = polygonContains(polygon, cx + nx * r, cy + ny * r) - if (projectedInside != geographicInside) normalErrors++ - if (!projectedInside != geographicInside) invertedErrors++ - } - return invertedErrors < normalErrors -} - -internal fun polygonContains( - polygon: List>, - x: Float, - y: Float -): Boolean { - if (polygon.size < 3) return false - var inside = false - var previous = polygon.last() - for (current in polygon) { - val crossesRay = (current.second > y) != (previous.second > y) - if (crossesRay) { - val intersectionX = (previous.first - current.first) * - (y - current.second) / (previous.second - current.second) + - current.first - if (x < intersectionX) inside = !inside - } - previous = current - } - return inside -} - -/** - * Point-in-ring test in geographic space: counts the ring edges that cross the probe's meridian - * north of it. Each edge is followed the short way around, so neither the ±180° seam nor the - * probe's antimeridian creates a false crossing. Casting the ray along a parallel instead wrapped - * edges near the probe's antimeridian from +180° to -180°, so a Pacific probe saw Europe's coast - * as crossings and Eurasia "contained" the Pacific, inverting its fill. Matches the iOS globe. - */ -internal fun ringContainsLocation( - ring: LandData.Ring, - latitude: Double, - longitude: Double -): Boolean { - if (ring.size < 3) return false - var inside = false - var previousIndex = ring.size - 1 - for (index in 0 until ring.size) { - val startLat = ring.coords[previousIndex * 2].toDouble() - val endLat = ring.coords[index * 2].toDouble() - val startLon = ring.coords[previousIndex * 2 + 1].toDouble() - val endLon = ring.coords[index * 2 + 1].toDouble() - val start = GlobeMath.normalizeLon(startLon - longitude) - // Unbounded on purpose: the end changes sign relative to the start only when the - // edge crosses the probe meridian, never when it crosses ±180°. - val end = start + GlobeMath.normalizeLon(endLon - startLon) - if ((start > 0.0) != (end > 0.0)) { - val t = start / (start - end) - if (startLat + (endLat - startLat) * t > latitude) inside = !inside - } - previousIndex = index - } - return inside -} - -private fun DrawScope.strokeRuns( - runs: List>>, - cx: Float, cy: Float, r: Float, - color: Color, - width: Float, - clip: ClipRect -) { - for (run in runs) { - if (run.size < 2) continue - val path = Path() - for (k in 1 until run.size) { - val seg = clipSegment( - cx + run[k - 1].first * r, cy + run[k - 1].second * r, - cx + run[k].first * r, cy + run[k].second * r, - clip - ) ?: continue - path.moveTo(seg.first.first, seg.first.second) - path.lineTo(seg.second.first, seg.second.second) - } - drawPath(path, color, style = Stroke(width = width)) - } -} - -private fun DrawScope.drawBorderLine( - line: LandData.Ring, - scratch: FloatArray, - projector: GlobeMath.PreparedProjector, - cx: Float, cy: Float, r: Float, - colors: GlobeColors, - clip: ClipRect -) { - val n = line.size - if (n < 2 || n * 3 > scratch.size) return - - var anyFront = false - val pts = ArrayList(n) - var i = 0 - while (i < n) { - projector.project(line.projectionTerms, i * 4, scratch, i * 3) - val x = scratch[i * 3] - val y = scratch[i * 3 + 1] - val cosC = scratch[i * 3 + 2] - val front = cosC > 0.005f - pts.add(DiscPt(x, y, front)) - if (cosC >= 0f) anyFront = true - i++ - } - if (!anyFront) return - - val runs = buildFrontRuns(pts, closed = false) - strokeRuns(runs, cx, cy, r, colors.border, 1.2f, clip) -} +private const val ATMOSPHERE_SCALE = 1.22f +private const val COASTLINE_WIDTH_PX = 1.4f +private const val BORDER_WIDTH_PX = 1.2f private fun DrawScope.drawCities( cities: List, @@ -1066,8 +460,7 @@ private fun DrawScope.drawCities( haloPaint: Paint, typeface: Typeface?, textSize: Float, - density: Float, - showLabels: Boolean + density: Float ) { if (cities.isEmpty()) return val projection = FloatArray(3) @@ -1095,7 +488,7 @@ private fun DrawScope.drawCities( else colors.label.copy(alpha = alpha * 0.85f) drawCircle(dotColor, radius = dotRadius, center = Offset(sx, sy)) - if (showLabels && (zoom >= 6f || (important && zoom >= 2.5f))) { + if (zoom >= 6f || (important && zoom >= 2.5f)) { labelPaint.textSize = textSize labelPaint.typeface = typeface labelPaint.textAlign = Paint.Align.LEFT @@ -1121,131 +514,6 @@ private fun DrawScope.drawCities( haloPaint.textAlign = Paint.Align.CENTER } -private fun DrawScope.drawLandFill( - ring: LandData.Ring, - scratch: FloatArray, - projector: GlobeMath.PreparedProjector, - cx: Float, cy: Float, r: Float, - colors: GlobeColors, - clip: ClipRect, - pointStride: Int, - centerLat: Double, - centerLon: Double -): List>>? { - val n = ((ring.size - 1) / pointStride) + 1 - if (n < 3 || n * 3 > scratch.size) return null - - var anyFront = false - var anyBack = false - var i = 0 - while (i < n) { - val sourceIndex = (i * pointStride).coerceAtMost(ring.size - 1) - projector.project(ring.projectionTerms, sourceIndex * 4, scratch, i * 3) - if (scratch[i * 3 + 2] >= 0f) { - anyFront = true - } else { - anyBack = true - } - i++ - } - if (!anyFront) return null - - val pts = ArrayList(n) - i = 0 - while (i < n) { - pts.add(DiscPt(scratch[i * 3], scratch[i * 3 + 1], scratch[i * 3 + 2] > 0.005f)) - i++ - } - val runs = buildFrontRuns(pts) - val polygon = buildFillPolygon(pts, cx, cy, r) - fillPolygonClipped( - pts = pts, - cx = cx, - cy = cy, - r = r, - color = colors.land, - clip = clip, - invertFill = anyBack && projectedFillNeedsInversion( - polygon = polygon, - ring = ring, - cx = cx, - cy = cy, - r = r, - centerLat = centerLat, - centerLon = centerLon - ), - preparedPolygon = polygon - ) - return runs -} - -private fun DrawScope.drawGeohashGrid( - state: GlobeState, - cx: Float, cy: Float, r: Float, - cLat: Double, cLon: Double, - colors: GlobeColors, - clip: ClipRect, - includeNeighbors: Boolean -) { - val selected = state.selectedGeohash - val cells = linkedSetOf(selected) - if (includeNeighbors) cells.addAll(Geohash.neighborsSamePrecision(selected)) - - for (cell in cells) { - val isSelected = cell == selected - val b = Geohash.decodeToBounds(cell) - val spanLat = b.latMax - b.latMin - val spanLon = b.lonMax - b.lonMin - val steps = ceil(spanLat / 1.5).toInt().coerceIn(4, 48) - - // Sample the cell boundary: N edge l->r, E edge t->b, S edge r->l, W edge b->t - val pts = ArrayList>(steps * 4 + 4) - fun addPt(lat: Double, lonRaw: Double) { - var lon = lonRaw - // keep boundary continuous across the antimeridian relative to the view - val ref = cLon - while (lon - ref > 180.0) lon -= 360.0 - while (lon - ref < -180.0) lon += 360.0 - val p = GlobeMath.projectRaw(lat, lon, cLat, cLon) - pts.add(Triple(p.x, p.y, p.cosC >= 0.005f)) - } - for (s in 0..steps) { - val t = s.toDouble() / steps - addPt(b.latMax, b.lonMin + spanLon * t) - } - for (s in 1..steps) { - val t = s.toDouble() / steps - addPt(b.latMax - spanLat * t, b.lonMax) - } - for (s in 1..steps) { - val t = s.toDouble() / steps - addPt(b.latMin, b.lonMax - spanLon * t) - } - for (s in 1 until steps) { - val t = s.toDouble() / steps - addPt(b.latMin + spanLat * t, b.lonMin) - } - - if (pts.none { it.third }) continue - - val discPts = pts.map { DiscPt(it.first, it.second, it.third) } - val runs = buildFrontRuns(discPts) - - if (isSelected) { - fillPolygonClipped( - discPts, cx, cy, r, colors.accent.copy(alpha = 0.20f), clip - ) - strokeRuns(runs, cx, cy, r, colors.accent.copy(alpha = 0.35f), 7f, clip) - strokeRuns(runs, cx, cy, r, colors.accent, 3.2f, clip) - } else { - fillPolygonClipped( - discPts, cx, cy, r, colors.grid.copy(alpha = 0.05f), clip - ) - strokeRuns(runs, cx, cy, r, colors.grid, 1.6f, clip) - } - } -} - private fun DrawScope.drawGeohashLabels( state: GlobeState, cx: Float, cy: Float, r: Float, diff --git a/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeGeometryTest.kt b/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeGeometryTest.kt index 122e12350..0491b2cb9 100644 --- a/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeGeometryTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeGeometryTest.kt @@ -2,43 +2,159 @@ package com.bitchat.android.ui.globe import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse -import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Test +import kotlin.math.sqrt class GlobeGeometryTest { - private val square = listOf( - DiscPt(-0.5f, -0.5f, front = true), - DiscPt(0.5f, -0.5f, front = true), - DiscPt(0.5f, 0.5f, front = true), - DiscPt(-0.5f, 0.5f, front = true) - ) + /** Records emitted segments, splitting them into polylines wherever the pen lifts. */ + private class RecordingSink : SegmentSink { + val polylines = mutableListOf>>() + private var open = false + + override fun segment(x0: Float, y0: Float, x1: Float, y1: Float) { + val current = polylines.lastOrNull() + if (!open || current == null || current.last() != (x0 to y0)) { + polylines += mutableListOf(x0 to y0) + } + polylines.last() += x1 to y1 + open = true + } + + override fun lift() { + open = false + } + } + + private val wideClip = ClipRect(-1000f, -1000f, 1000f, 1000f) + + /** Projected (x, y, cosC) triples for points on the near hemisphere. */ + private fun front(vararg xy: Float): FloatArray { + val out = FloatArray(xy.size / 2 * 3) + for (i in 0 until xy.size / 2) { + val x = xy[i * 2] + val y = xy[i * 2 + 1] + out[i * 3] = x + out[i * 3 + 1] = y + out[i * 3 + 2] = sqrt(1f - x * x - y * y) + } + return out + } + + private val square = front(-0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f) @Test - fun closedFullyVisibleRing_connectsLastPointToFirst() { - val run = buildFrontRuns(square, closed = true).single() + fun closedFullyVisibleRing_isOnePolylineEndingWhereItStarts() { + val sink = RecordingSink() + sink.addProjectedLine(square, 4, closed = true, cx = 0f, cy = 0f, r = 1f, clip = wideClip) - assertEquals(square.size + 1, run.size) - assertEquals(run.first(), run.last()) + val line = sink.polylines.single() + assertEquals(5, line.size) + assertEquals(line.first(), line.last()) } @Test fun openFullyVisibleLine_doesNotConnectLastPointToFirst() { - val run = buildFrontRuns(square, closed = false).single() + val sink = RecordingSink() + sink.addProjectedLine(square, 4, closed = false, cx = 0f, cy = 0f, r = 1f, clip = wideClip) - assertEquals(square.size, run.size) - assertNotEquals(run.first(), run.last()) + val line = sink.polylines.single() + assertEquals(4, line.size) + assertEquals(-0.5f to -0.5f, line.first()) + assertEquals(-0.5f to 0.5f, line.last()) + } + + @Test + fun lineTurningOverTheHorizon_isCutAtTheLimb() { + // From the view center out to a point a little way round the far side. + val points = floatArrayOf( + 0f, 0f, 1f, + 0.9f, 0f, -0.2f + ) + val sink = RecordingSink() + sink.addProjectedLine(points, 2, closed = false, cx = 0f, cy = 0f, r = 1f, clip = wideClip) + + val end = sink.polylines.single().last() + assertEquals(1f, end.first, 1e-4f) + assertEquals(0f, end.second, 1e-4f) + } + + @Test + fun lineEntirelyOnTheFarSide_emitsNothing() { + val points = floatArrayOf( + 0.2f, 0f, -0.9f, + 0.4f, 0f, -0.8f + ) + val sink = RecordingSink() + sink.addProjectedLine(points, 2, closed = false, cx = 0f, cy = 0f, r = 1f, clip = wideClip) + + assertTrue(sink.polylines.isEmpty()) + } + + @Test + fun segmentLeavingTheClip_isCutAtTheClipEdge() { + val sink = RecordingSink() + sink.addProjectedLine( + front(0f, 0f, 0.8f, 0f), 2, closed = false, + cx = 0f, cy = 0f, r = 1000f, + clip = ClipRect(-500f, -500f, 500f, 500f) + ) + + assertEquals(listOf(0f to 0f, 500f to 0f), sink.polylines.single()) + } + + @Test + fun polygonInsideTheClip_isReturnedUnchanged() { + val polygon = PointBuffer().apply { + add(-10f, -10f); add(10f, -10f); add(10f, 10f); add(-10f, 10f) + } + val result = clipPolygon(polygon, ClipRect(-100f, -100f, 100f, 100f), PointBuffer(), PointBuffer()) + + assertSame(polygon, result) + } + + @Test + fun polygonCrossingTheClip_isTrimmedToIt() { + val polygon = PointBuffer().apply { + add(-10f, -10f); add(30f, -10f); add(30f, 10f); add(-10f, 10f) + } + val result = clipPolygon(polygon, ClipRect(-100f, -100f, 20f, 100f), PointBuffer(), PointBuffer()) + + assertEquals(4, result.size) + for (i in 0 until result.size) assertTrue(result.x(i) <= 20f) + assertEquals(30f * 20f, kotlin.math.abs(signedArea(result)), 1e-3f) + } + + @Test + fun signedArea_followsWinding() { + val ccw = PointBuffer().apply { add(0f, 0f); add(1f, 0f); add(1f, 1f); add(0f, 1f) } + val cw = PointBuffer().apply { add(0f, 0f); add(0f, 1f); add(1f, 1f); add(1f, 0f) } + + assertEquals(1f, signedArea(ccw), 1e-6f) + assertEquals(-1f, signedArea(cw), 1e-6f) + } + + @Test + fun fillPolygon_clampsFarSidePointsOntoTheLimb() { + val points = floatArrayOf( + 0f, 0f, 1f, + 0.5f, 0f, -0.5f + ) + val out = PointBuffer() + buildFillPolygon(points, 2, cx = 0f, cy = 0f, r = 10f, out = out) + + assertEquals(0f to 0f, out.x(0) to out.y(0)) + assertEquals(10f, out.x(1), 1e-4f) + assertEquals(0f, out.y(1), 1e-4f) } @Test fun polygonContains_distinguishesInsideAndOutsidePoints() { - val polygon = listOf( - -10f to -10f, - 10f to -10f, - 10f to 10f, - -10f to 10f - ) + val polygon = PointBuffer().apply { + add(-10f, -10f); add(10f, -10f); add(10f, 10f); add(-10f, 10f) + } assertTrue(polygonContains(polygon, 0f, 0f)) assertFalse(polygonContains(polygon, 20f, 0f)) diff --git a/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeInteractionPolicyTest.kt b/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeInteractionPolicyTest.kt deleted file mode 100644 index 87c6fb0cc..000000000 --- a/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeInteractionPolicyTest.kt +++ /dev/null @@ -1,102 +0,0 @@ -package com.bitchat.android.ui.globe - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class GlobeInteractionPolicyTest { - - @Test - fun fullDetail_preservesAllGlobeFeatures() { - val detail = globeFrameDetail(GlobeMotionDetail.FULL) - - assertEquals(1, detail.landPointStride) - assertTrue(detail.showBorders) - assertTrue(detail.showCityLabels) - } - - @Test - fun balancedDetail_keepsBordersButDropsLabels() { - val detail = globeFrameDetail(GlobeMotionDetail.BALANCED) - - assertEquals(2, detail.landPointStride) - assertTrue(detail.showBorders) - assertFalse(detail.showCityLabels) - } - - @Test - fun fastDetail_usesMinimumMovingFrameWork() { - val detail = globeFrameDetail(GlobeMotionDetail.FAST) - - assertEquals(2, detail.landPointStride) - assertFalse(detail.showBorders) - assertFalse(detail.showCityLabels) - } - - @Test - fun adaptiveDetail_wantedLevelFollowsCadenceWithHysteresis() { - assertEquals( - GlobeMotionDetail.BALANCED, - nextGlobeMotionDetail(GlobeMotionDetail.FULL, averageFrameMillis = 24f) - ) - assertEquals( - GlobeMotionDetail.FAST, - nextGlobeMotionDetail(GlobeMotionDetail.BALANCED, averageFrameMillis = 32f) - ) - assertEquals( - GlobeMotionDetail.BALANCED, - nextGlobeMotionDetail(GlobeMotionDetail.FAST, averageFrameMillis = 17f) - ) - assertEquals( - GlobeMotionDetail.FULL, - nextGlobeMotionDetail(GlobeMotionDetail.BALANCED, averageFrameMillis = 17f) - ) - } - - private fun GlobeMotionGovernor.frames(count: Int, millis: Float) = - repeat(count) { recordFrame(millis) } - - @Test - fun governor_neverStepsBackUpWithinAGesture() { - val governor = GlobeMotionGovernor() - governor.beginSession() - assertEquals(GlobeMotionDetail.BALANCED, governor.detail) - - governor.frames(8, millis = 32f) - assertEquals(GlobeMotionDetail.FAST, governor.detail) - - // Shedding detail made frames fast again; detail must not flash back up mid-gesture. - governor.frames(32, millis = 12f) - assertEquals(GlobeMotionDetail.FAST, governor.detail) - } - - @Test - fun governor_restoresFullDetailAtRestAndRemembersTheCeiling() { - val governor = GlobeMotionGovernor() - governor.beginSession() - governor.frames(8, millis = 32f) - governor.endSession() - assertEquals(GlobeMotionDetail.FULL, governor.detail) - - governor.beginSession() - assertEquals(GlobeMotionDetail.FAST, governor.detail) - governor.frames(16, millis = 12f) - governor.endSession() - - // A ceiling was found, so a smooth gesture does not promote the next one. - governor.beginSession() - assertEquals(GlobeMotionDetail.FAST, governor.detail) - } - - @Test - fun governor_smoothGesturesLetTheNextStartHigher() { - val governor = GlobeMotionGovernor() - governor.beginSession() - governor.frames(16, millis = 12f) - governor.endSession() - - governor.beginSession() - assertEquals(GlobeMotionDetail.FULL, governor.detail) - } -} diff --git a/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeMathTest.kt b/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeMathTest.kt index 0f39572a7..355b6f1eb 100644 --- a/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeMathTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/ui/globe/GlobeMathTest.kt @@ -57,4 +57,17 @@ class GlobeMathTest { assertTrue(zoom <= GlobeMath.MAX_ZOOM) } } + + @Test + fun preciseProjector_matchesProjectRaw() { + val projector = GlobeMath.PreciseProjector(centerLatDeg = 35.0, centerLonDeg = 170.0) + val out = FloatArray(3) + for ((lat, lon) in listOf(35.0 to 170.0, 10.0 to -175.0, -60.0 to 20.0, 89.0 to 0.0)) { + projector.project(lat, lon, out, 0) + val expected = GlobeMath.projectRaw(lat, lon, 35.0, 170.0) + org.junit.Assert.assertEquals(expected.x, out[0], 1e-6f) + org.junit.Assert.assertEquals(expected.y, out[1], 1e-6f) + org.junit.Assert.assertEquals(expected.cosC, out[2], 1e-6f) + } + } }