diff --git a/api/android-sdk-core.api b/api/android-sdk-core.api index ed427f5..0529e36 100644 --- a/api/android-sdk-core.api +++ b/api/android-sdk-core.api @@ -95,7 +95,7 @@ public interface com.mapconductor.core.circle.CircleCapableInterface { public abstract void setOnCircleClickListener(kotlin.jvm.functions.Function1); public abstract boolean hasCircle(com.mapconductor.core.circle.CircleState); } -public abstract class com.mapconductor.core.circle.CircleController implements com.mapconductor.core.controller.SlottedOverlayController> { +public abstract class com.mapconductor.core.circle.CircleController implements com.mapconductor.core.controller.SlottedOverlayController>, com.mapconductor.core.controller.OnCameraChangeReceiverInterface { public com.mapconductor.core.circle.CircleController(com.mapconductor.core.circle.CircleManagerInterface, com.mapconductor.core.circle.CircleOverlayRendererInterface); public final com.mapconductor.core.circle.CircleManagerInterface getCircleManager(); public com.mapconductor.core.circle.CircleOverlayRendererInterface getRenderer(); @@ -103,11 +103,14 @@ public abstract class com.mapconductor.core.circle.CircleController getClickListener(); public final void setClickListener(kotlin.jvm.functions.Function1); + public final com.mapconductor.core.circle.CircleTiler getTiler(); + public final void setTiler(com.mapconductor.core.circle.CircleTiler); public final void dispatchClick(com.mapconductor.core.circle.CircleEvent); public java.lang.Object add(java.util.List, kotlin.coroutines.Continuation); public java.lang.Object update(com.mapconductor.core.circle.CircleState, kotlin.coroutines.Continuation); public java.lang.Object clear(kotlin.coroutines.Continuation); public com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface); + public java.lang.Object onCameraChanged(com.mapconductor.core.map.MapCameraPosition, kotlin.coroutines.Continuation); public void destroy(); public boolean has(java.lang.String); public com.mapconductor.core.controller.OverlayKind getKind(); @@ -165,14 +168,17 @@ public final class com.mapconductor.core.circle.CircleKt { } public final class com.mapconductor.core.circle.CircleManager implements com.mapconductor.core.circle.CircleManagerInterface { public com.mapconductor.core.circle.CircleManager(); + public boolean setTiledSource(com.mapconductor.core.circle.CircleTiler); public com.mapconductor.core.circle.CircleEntityInterface getEntity(java.lang.String); public boolean hasEntity(java.lang.String); public com.mapconductor.core.circle.CircleEntityInterface removeEntity(java.lang.String); public void registerEntity(com.mapconductor.core.circle.CircleEntityInterface); public final void updateEntity(com.mapconductor.core.circle.CircleEntityInterface); + public java.util.List> nativeEntities(); public java.util.List> allEntities(); public void clear(); public com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface); + public com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.map.MapCameraPosition); } public interface com.mapconductor.core.circle.CircleManagerInterface { public abstract void registerEntity(com.mapconductor.core.circle.CircleEntityInterface); @@ -180,13 +186,23 @@ public interface com.mapconductor.core.circle.CircleManagerInterface getEntity(java.lang.String); public abstract boolean hasEntity(java.lang.String); public abstract java.util.List> allEntities(); + public default java.util.List> nativeEntities(); + public default boolean setTiledSource(com.mapconductor.core.circle.CircleTiler); public abstract void clear(); public abstract com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface); + public default com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.map.MapCameraPosition); +} +public final class com.mapconductor.core.circle.CircleManagerInterface$DefaultImpls { + public static java.util.List> nativeEntities(com.mapconductor.core.circle.CircleManagerInterface); + public static boolean setTiledSource(com.mapconductor.core.circle.CircleManagerInterface, com.mapconductor.core.circle.CircleTiler); + public static com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.circle.CircleManagerInterface, com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.map.MapCameraPosition); } public final class com.mapconductor.core.circle.CircleOverlay implements com.mapconductor.core.map.MapOverlayInterface { - public com.mapconductor.core.circle.CircleOverlay(kotlinx.coroutines.flow.StateFlow>); + public com.mapconductor.core.circle.CircleOverlay(kotlinx.coroutines.flow.StateFlow>, kotlinx.coroutines.flow.StateFlow); + public com.mapconductor.core.circle.CircleOverlay(kotlinx.coroutines.flow.StateFlow, kotlinx.coroutines.flow.StateFlow, int, kotlin.jvm.internal.DefaultConstructorMarker); public kotlinx.coroutines.flow.StateFlow> getFlow(); public java.lang.Object render(java.util.Map, com.mapconductor.core.controller.MapViewControllerInterface, kotlin.coroutines.Continuation); + public com.mapconductor.core.circle.CircleOverlay(kotlinx.coroutines.flow.StateFlow>); } public interface com.mapconductor.core.circle.CircleOverlayRendererInterface { public abstract java.lang.Object onAdd(java.util.List, kotlin.coroutines.Continuation>); @@ -236,6 +252,95 @@ public final class com.mapconductor.core.circle.CircleState implements com.mapco public com.mapconductor.core.circle.CircleState(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.internal.DefaultConstructorMarker); public com.mapconductor.core.circle.CircleState(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.internal.DefaultConstructorMarker); } +final class com.mapconductor.core.circle.CircleState$Values { + public final com.mapconductor.core.features.GeoPointInterface getCenter(); + public final boolean getClickable(); + public final double getRadiusMeters(); + public final boolean getGeodesic(); + public final long getStrokeColor-0d7_KjU(); + public final float getStrokeWidth-D9Ej5fM(); + public final long getFillColor-0d7_KjU(); + public final java.io.Serializable getExtra(); + public final java.lang.Integer getZIndex(); + public final kotlin.jvm.functions.Function1 getOnClick(); + public final long getRevision(); + public final int getChangedFields(); + public final int difference(com.mapconductor.core.circle.CircleState$Values); + public final com.mapconductor.core.features.GeoPointInterface component1(); + public final boolean component2(); + public final double component3(); + public final boolean component4(); + public final long component5-0d7_KjU(); + public final float component6-D9Ej5fM(); + public final long component7-0d7_KjU(); + public final java.io.Serializable component8(); + public final java.lang.Integer component9(); + public final kotlin.jvm.functions.Function1 component10(); + public final long component11(); + public final int component12(); + public final com.mapconductor.core.circle.CircleState$Values copy-Zc45R8w(com.mapconductor.core.features.GeoPointInterface, boolean, double, boolean, long, float, long, java.io.Serializable, java.lang.Integer, kotlin.jvm.functions.Function1, long, int); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.core.circle.CircleTileSet { + public static final com.mapconductor.core.circle.CircleTileSet$Companion Companion; + public com.mapconductor.core.circle.CircleTileSet(com.mapconductor.core.tileserver.LocalTileServer, kotlinx.coroutines.CoroutineScope); + public com.mapconductor.core.circle.CircleTileSet(com.mapconductor.core.tileserver.LocalTileServer, kotlinx.coroutines.CoroutineScope, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final java.lang.String getRouteId(); + public final kotlin.jvm.functions.Function2, java.lang.Object> getOnTemplateChanged(); + public final void setOnTemplateChanged(kotlin.jvm.functions.Function2, ? extends java.lang.Object>); + public final int getTileSize(); + public final java.lang.Object setCircles(java.util.List, kotlin.coroutines.Continuation); + public final boolean has(java.lang.String); + public final void update(com.mapconductor.core.circle.CircleState); + public final void remove(java.lang.String); + public final java.lang.String template(); + public final void dispose(); + public com.mapconductor.core.circle.CircleTileSet(); +} +public final class com.mapconductor.core.circle.CircleTileSet$Companion { + public final boolean canTile(com.mapconductor.core.circle.CircleState); +} +public final class com.mapconductor.core.circle.CircleTiler { + public com.mapconductor.core.circle.CircleTiler(com.mapconductor.core.circle.CircleTilingOptions); + public com.mapconductor.core.circle.CircleTiler(com.mapconductor.core.circle.CircleTilingOptions, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final com.mapconductor.core.circle.CircleTilingOptions getOptions(); + public final void setOptions(com.mapconductor.core.circle.CircleTilingOptions); + public final kotlin.jvm.functions.Function3, java.lang.Object> getOnTemplate(); + public final void setOnTemplate(kotlin.jvm.functions.Function3, ? extends java.lang.Object>); + public final java.lang.Object route(java.util.List, kotlin.coroutines.Continuation>); + public final java.util.List tiledStates(); + public final boolean isTiled(java.lang.String); + public final void update(com.mapconductor.core.circle.CircleState); + public final void remove(java.lang.String); + public final void dispose(); + public final java.lang.Object clear(kotlin.coroutines.Continuation); + public com.mapconductor.core.circle.CircleTiler(); +} +public final class com.mapconductor.core.circle.CircleTilerKt { + public static final java.lang.String CIRCLE_TILE_LAYER_ID; + public static final com.mapconductor.core.raster.RasterLayerState circleTileRasterLayerState(java.lang.String, int); +} +public final class com.mapconductor.core.circle.CircleTilingOptions { + public static final com.mapconductor.core.circle.CircleTilingOptions$Companion Companion; + public com.mapconductor.core.circle.CircleTilingOptions(boolean, int); + public com.mapconductor.core.circle.CircleTilingOptions(boolean, int, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final boolean getEnabled(); + public final int getMinCircleCount(); + public final boolean shouldUseTiles(int); + public final boolean component1(); + public final int component2(); + public final com.mapconductor.core.circle.CircleTilingOptions copy(boolean, int); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public com.mapconductor.core.circle.CircleTilingOptions(); +} +public final class com.mapconductor.core.circle.CircleTilingOptions$Companion { + public final com.mapconductor.core.circle.CircleTilingOptions getDefault(); + public final com.mapconductor.core.circle.CircleTilingOptions getDisabled(); +} public abstract class com.mapconductor.core.controller.BaseMapViewController implements com.mapconductor.core.controller.MapViewControllerInterface,com.mapconductor.core.marker.MarkerCapableInterface,com.mapconductor.core.polyline.PolylineCapableInterface,com.mapconductor.core.polygon.PolygonCapableInterface,com.mapconductor.core.circle.CircleCapableInterface,com.mapconductor.core.groundimage.GroundImageCapableInterface,com.mapconductor.core.raster.RasterLayerCapableInterface { public static final double ZOOM_EPS; public static final double COORD_EPS; @@ -3035,6 +3140,12 @@ public final class com.mapconductor.core.raster.TileScheme extends java.lang.Enu public static com.mapconductor.core.raster.TileScheme valueOf(java.lang.String); public static kotlin.enums.EnumEntries getEntries(); } +public final class com.mapconductor.core.shapetile.ShapeTileRenderer$Painter$DefaultImpls { + public static boolean getCacheSimplifiedShapes(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter); + public static boolean getThinSubpixelOverlaps(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter); + public static boolean isVisible(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter, T); + public static int subpixelSlot(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter, T, double, double, double, int); +} public final class com.mapconductor.core.spherical.CalculateMetersPerPixelKt { public static final double calculateMetersPerPixel(double, double, double); } diff --git a/build.gradle.kts b/build.gradle.kts index 6b45752..791f81c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -69,6 +69,7 @@ kotlin { } dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-collections-immutable:0.5.2") // Make Compose dependencies implementation instead of compileOnly for proper runtime support implementation(platform(libs.androidx.compose.bom)) implementation(libs.androidx.ui) diff --git a/src/androidTest/AndroidManifest.xml b/src/androidTest/AndroidManifest.xml index 802ac4d..4ead9cf 100644 --- a/src/androidTest/AndroidManifest.xml +++ b/src/androidTest/AndroidManifest.xml @@ -8,4 +8,6 @@ + + diff --git a/src/androidTest/assets/antennas/README.md b/src/androidTest/assets/antennas/README.md new file mode 100644 index 0000000..0fe98cb --- /dev/null +++ b/src/androidTest/assets/antennas/README.md @@ -0,0 +1,12 @@ +# US antenna horizons + +Source: FCC ASR weekly complete registration export, downloaded 2026-11-10. +https://data.fcc.gov/download/pub/uls/complete/r_tower.zip + +This is a snapshot of registered antenna structures, not a cellular base station database. FCC registration does not establish that a transmitter is operating. Only current, constructed registrations with coordinates and a positive overall height above ground are retained. Owner names, addresses and contacts are discarded. Data provenance, filtering, SHA-256 and binary layout are in public/antennas/us-antennas.json. + +The radius is a **geometric horizon model**, not measured or predicted radio coverage. It assumes a spherical Earth with R=6378137 m and a receiver 1.5 m above the ground. Radius in metres is R*(acos(R/(R+h))+acos(R/(R+1.5))). It ignores terrain, antenna elevation within the structure, radiation pattern, obstructions, frequency and atmospheric refraction. geodesic=true traces that surface distance on the sphere. The false toggle is a local-plane comparison. + +Low (<60 m), medium (60–150 m) and tall (>=150 m) structures are colored blue, green and orange. Alaska and US overview camera presets demonstrate latitude-dependent projection. Each platform bundles the same ~2.27 MB file; no network or token is needed to load the sample data. Source is factual FCC public-access data, with source credit shown on the sample. + +Rebuild: download r_tower.zip, then `python3 pack.py r_tower.zip us-antennas.bin`. Copy the .bin and .json to each example's antennas asset directory. MCCA header and count are little-endian; each 16-byte record stores float32 latitude, float32 longitude, float32 height_m and uint32 registration. diff --git a/src/androidTest/assets/antennas/us-antennas.bin b/src/androidTest/assets/antennas/us-antennas.bin new file mode 100644 index 0000000..26804c3 Binary files /dev/null and b/src/androidTest/assets/antennas/us-antennas.bin differ diff --git a/src/androidTest/assets/antennas/us-antennas.json b/src/androidTest/assets/antennas/us-antennas.json new file mode 100644 index 0000000..c629681 --- /dev/null +++ b/src/androidTest/assets/antennas/us-antennas.json @@ -0,0 +1,16 @@ +{ + "source": "https://data.fcc.gov/download/pub/uls/complete/r_tower.zip", + "source_sha256": "fe21a1ac2ac9b168172a17dd8bf21560727c1b833305092aec8bfc7598cc4ab5", + "file_sha256": "73790a6249002a52083e7cfb359092f71d05b4e91ea1667ee840bcd83f636185", + "count": 141979, + "bytes": 2271672, + "receiver_height_m": 1.5, + "earth_radius_m": 6378137, + "min_radius_m": 11693.874125711327, + "max_radius_m": 93860.22110994058, + "excluded": { + "registration": 4 + }, + "filter": "RA archive_flag_code=C, status_code=C, empty date_dismantled; CO coordinate_type=T; unique registration number; 0 < overall_height_above_ground <= 1000 m", + "format": "MCCA + u32 count + count*(f32 latitude, f32 longitude, f32 height_m, u32 registration); little endian" +} diff --git a/src/androidTest/java/com/mapconductor/core/circle/CircleNationwidePerformanceTest.kt b/src/androidTest/java/com/mapconductor/core/circle/CircleNationwidePerformanceTest.kt new file mode 100644 index 0000000..2f4767d --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/circle/CircleNationwidePerformanceTest.kt @@ -0,0 +1,68 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.shapetile.ShapeGridIndex +import com.mapconductor.core.shapetile.ShapeTileRenderer +import org.junit.Assert.assertTrue +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.acos +import kotlin.math.ln +import kotlin.math.sin +import android.util.Log + +class CircleNationwidePerformanceTest { + @Test fun nationwideZoomTiles() { + val bytes = + InstrumentationRegistry + .getInstrumentation() + .context.assets + .open("antennas/us-antennas.bin") + .use { it.readBytes() } + val b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + b.position(4) + val count = b.int + val circles = + List(count) { + val lat = b.float.toDouble() + val lon = b.float.toDouble() + val height = b.float.toDouble() + val id = b.int + val radius = 6378137.0 * (acos(6378137.0 / (6378137.0 + height)) + acos(6378137.0 / 6378138.5)) + TileCircle.from( + CircleState( + center = GeoPoint(lat, lon), radiusMeters = radius, id = "$id", geodesic = true, + fillColor = Color.Blue.copy(alpha = 0.035f), strokeColor = Color.Blue.copy(alpha = 0.35f), + strokeWidth = 0.5.dp, + ), + )!! + } + val start = System.nanoTime() + val index = ShapeGridIndex.build(count) { circles[it].bbox } + Log.i("CirclePerf", "indexMs=${(System.nanoTime() - start) / 1e6} large=${index.large.size}") + val renderer = ShapeTileRenderer(pixelScale = { 2f }, painter = CircleTilePainter) + renderer.setItems(circles) + for (z in listOf(4, 6, 8, 10, 12, 14)) { + val n = 1 shl z + val x = ((-98.0 + 180) / 360 * n).toInt() + val latitude = 39.0 * Math.PI / 180 + val y = ((0.5 - ln((1 + sin(latitude)) / (1 - sin(latitude))) / (4 * Math.PI)) * n).toInt() + val q = System.nanoTime() + val candidates = + index + .query({ circles[it].bbox }, x.toDouble() / n, y.toDouble() / n, (x + 1.0) / n, (y + 1.0) / n) + val queryMs = (System.nanoTime() - q) / 1e6 + val t = System.nanoTime() + val bitmap = renderer.renderBitmap(x, y, z) + val renderMs = (System.nanoTime() - t) / 1e6 + assertTrue(candidates.isNotEmpty()) + assertTrue(bitmap != null) + bitmap?.recycle() + Log.i("CirclePerf", "z=$z candidates=${candidates.size} queryMs=$queryMs renderMs=$renderMs") + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/circle/CircleTileFileDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/circle/CircleTileFileDeviceTest.kt new file mode 100644 index 0000000..3590c36 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/circle/CircleTileFileDeviceTest.kt @@ -0,0 +1,167 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import java.io.File +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import kotlin.concurrent.thread +import kotlinx.coroutines.runBlocking + +@RunWith(AndroidJUnit4::class) +class CircleTileFileDeviceTest { + @get:Rule val temporary = TemporaryFolder() + + private fun renderer() = ShapeTileRenderer(pixelScale = { 1f }, painter = CircleTilePainter) + + private fun state( + lat: Double, + lng: Double, + geodesic: Boolean, + id: String? = null, + ) = CircleState( + id = id, center = GeoPoint(lat, lng), radiusMeters = 250000.0, geodesic = geodesic, + fillColor = Color(0x802563EB), strokeColor = Color.Red, strokeWidth = 1.dp, + ) + + @Test fun fileAndMemoryProduceIdenticalPixelsAndUpdates() { + for (geodesic in listOf(false, true)) { + val data = + listOf(state(0.0, 0.0, geodesic), state(69.0, -150.0, geodesic), state(42.0, -71.0, geodesic)) + .map { TileCircle.from(it)!! } + val memory = renderer().apply { setItems(data) } + val disk = + renderer().apply { + setStorage( + CircleTileFileStorage + .create(temporary.root, data.size, { data[it] }), + ) + } + try { + for ((z, x, y) in listOf(Triple(0, 0, 0), Triple(4, 1, 3), Triple(4, 4, 5))) { + fun compare() { + val a = memory.renderBitmap(x, y, z) + val b = disk.renderBitmap(x, y, z) + if (a == null) { + assertNull(b) + } else { + assertNotNull(b) + assertTrue("Pixel mismatch at $z/$x/$y geodesic=$geodesic", a.sameAs(b)) + a.recycle() + b!!.recycle() + } + } + compare() + val changed = TileCircle.from(state(60.0, -130.0, !geodesic).apply { fillColor = Color.Green })!! + memory.update(listOf(1 to changed, 2 to null)) + disk.update(listOf(1 to changed, 2 to null)) + compare() + } + } finally { + memory.clear() + disk.clear() + } + } + assertTrue(temporary.root.listFiles()!!.isEmpty()) + } + + @Test fun retiringModelWaitsForItsInFlightTileReader() { + val item = TileCircle.from(state(0.0, 0.0, true))!! + val storage = CircleTileFileStorage.create(temporary.root, 2001, { item }) + val file = storage.cacheFile + val renderer = renderer().apply { setStorage(storage) } + val entered = CountDownLatch(1) + val resume = CountDownLatch(1) + val failure = AtomicReference() + val result = AtomicReference() + val reader = + thread { + try { + result.set( + renderer.renderTile(TileRequest(0, 0, 0)) { + entered.countDown() + check(resume.await(10, TimeUnit.SECONDS)) + false + }, + ) + } catch (error: Throwable) { + failure.set(error) + } + } + try { + assertTrue(entered.await(10, TimeUnit.SECONDS)) + renderer.clear() + assertTrue("Old file must remain readable", file.exists()) + } finally { + resume.countDown() + reader.join(10000) + renderer.clear() + } + assertFalse(reader.isAlive) + assertNull(failure.get()) + assertNotNull(result.get()) + assertFalse("Last reader releases the retired file", file.exists()) + } + + @Test fun cancelledRequestReleasesItsFileLease() { + val storage = CircleTileFileStorage.create(temporary.root, 3, { TileCircle.from(state(0.0, 0.0, true)) }) + val file = storage.cacheFile + val renderer = renderer().apply { setStorage(storage) } + try { + try { + renderer.renderTile(TileRequest(0, 0, 0)) { true } + fail("Expected cancellation") + } catch ( + _: ShapeTileRenderer.TileRenderCancelled, + ) { + } + assertTrue(file.exists()) + } finally { + renderer.clear() + } + assertFalse(file.exists()) + } + + @Test fun automaticallyUsesFilesAbove2000AndDeletesThemOnDispose() = + runBlocking { + ResourceProvider.init( + androidx.test.platform.app.InstrumentationRegistry + .getInstrumentation() + .targetContext, + ) + val directory = File(ResourceProvider.getAppContext().cacheDir, "mapconductor-circle-geometry") + val before = directory.listFiles()?.toSet() ?: emptySet() + val set = CircleTileSet() + var created = emptySet() + try { + val states = List(2001) { state(42.0, -71.0, true, "file-$it").apply { zIndex = it } } + set.setCircles(states.take(2000)) + assertEquals(before, directory.listFiles()?.toSet() ?: emptySet()) + set.setCircles(states) + created = directory.listFiles()!!.toSet() - before + assertEquals(1, created.size) + set.setCircles(states.filterIndexed { index, _ -> index % 2 == 0 }) + assertFalse(set.has(states[1].id)) + assertTrue(set.has(states[0].id)) + } finally { + set.dispose() + } + assertTrue(created.none { it.exists() }) + } +} diff --git a/src/androidTest/java/com/mapconductor/core/circle/CircleTileRendererDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/circle/CircleTileRendererDeviceTest.kt new file mode 100644 index 0000000..6ec4fe8 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/circle/CircleTileRendererDeviceTest.kt @@ -0,0 +1,414 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.geometry.circleToRing +import com.mapconductor.core.polygon.toMercatorRing +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import kotlin.math.PI +import kotlin.math.floor +import kotlin.math.ln +import kotlin.math.sin +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import kotlinx.coroutines.runBlocking + +/** + * 円のタイルの画素。tile-sw.js の「Shape tiles」節の円と同じ描き方であることを固定する。 + * PolylineTileRendererDeviceTest と同じく、1 単位 = 1 画素(pixelScale = 1)で描かせる。 + * + * z0 のタイルは世界全体が 256 画素。js-sdk-core の `CircleTileRendering.test.mjs`、 + * ios-sdk の `CircleTileRendererTests` と 1 対 1。 + */ +@RunWith(AndroidJUnit4::class) +class CircleTileRendererDeviceTest { + @Test + fun filteringSharesGeometryButHidesSourcesAndPixels() = runBlocking { + val left = CircleState(id = "left", center = p(0.0, -60.0), radiusMeters = 500000.0, zIndex = 0) + val right = CircleState(id = "right", center = p(0.0, 60.0), radiusMeters = 500000.0, zIndex = 1) + val set = CircleTileSet() + try { + set.setCircles(listOf(left, right)) + val leftGeometry = set.renderer.itemAt(0) + val rightGeometry = set.renderer.itemAt(1) + val initialIds = set.shapes.ids() + repeat(3) { + set.setCircles(listOf(left)) + assertSame(leftGeometry, set.renderer.itemAt(0)) + assertSame(rightGeometry, set.renderer.itemAt(1)) + assertEquals(setOf("left"), set.shapes.ids()) + assertNull(set.shapes.source("right")) + val sources = mutableListOf() + set.shapes.visitSources { sources.add(it) } + assertEquals(listOf(left), sources) + val bitmap = set.renderer.renderBitmap(0, 0, 0)!! + assertTrue(alpha(bitmap.getPixel(bitmap.width / 3, bitmap.height / 2)) > 0) + assertEquals(0, alpha(bitmap.getPixel(bitmap.width * 2 / 3, bitmap.height / 2))) + bitmap.recycle() + set.setCircles(listOf(left, right)) + assertSame(rightGeometry, set.renderer.itemAt(1)) + assertSame(right, set.shapes.source("right")) + assertEquals(setOf("left", "right"), initialIds) + } + // Same state identity with a changed value must rebuild geometry. + left.radiusMeters = 700000.0 + set.setCircles(listOf(left, right)) + assertNotSame(leftGeometry, set.renderer.itemAt(0)) + } finally { + set.dispose() + } + } + + @Test + fun filteringDoesNotReuseChangedStackingOrder() = runBlocking { + val a = CircleState(id = "a", center = p(0.0, 0.0), radiusMeters = 1000.0, zIndex = 0) + val b = CircleState(id = "b", center = p(0.0, 0.0), radiusMeters = 1000.0, zIndex = 0) + val set = CircleTileSet() + try { + set.setCircles(listOf(a, b)) + val first = set.renderer.itemAt(0) + set.setCircles(listOf(b, a)) + assertNotSame(first, set.renderer.itemAt(0)) + b.zIndex = 2 + set.setCircles(listOf(b, a)) + assertEquals(1000.0, set.renderer.itemAt(0)!!.radiusMeters, 0.0) + assertEquals(listOf("a", "b"), set.shapes.ids().sorted()) + } finally { + set.dispose() + } + } + + private val red = Color(0xFFFF0000) + private val blue = Color(0xFF0000FF) + private val green = Color(0xFF00FF00) + + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + private fun renderer(vararg states: CircleState) = + ShapeTileRenderer(tileSize = 256, pixelScale = { 1f }, painter = CircleTilePainter).apply { + setItems(states.sortedBy(::effectiveZIndex).map(TileCircle::from)) + } + + private fun alpha(pixel: Int) = pixel ushr 24 + + private fun rgb(pixel: Int) = pixel and 0xFFFFFF + + private fun worldX( + lng: Double, + z: Int, + ): Double = (lng + 180) / 360 * 256.0 * (1 shl z) + + private fun worldY( + lat: Double, + z: Int, + ): Double { + val s = sin(lat * PI / 180) + return (0.5 - ln((1 + s) / (1 - s)) / (4 * PI)) * 256.0 * (1 shl z) + } + + /** The columns of row [y] that are painted (alpha over half). */ + private fun paintedColumns( + bitmap: Bitmap, + y: Int, + ): List = (0 until bitmap.width).filter { alpha(bitmap.getPixel(it, y)) > 0x80 } + + /** A circle at the equator, [radiusPx] pixels across at [z] (radius of a z-world pixel = 40075 km / 256 / 2^z). */ + private fun equatorCircle( + lng: Double, + radiusPx: Double, + z: Int, + fill: Color = Color(0x800000FF), + stroke: Color = red, + strokeWidth: Float = 2f, + id: String? = null, + zIndex: Int? = 0, + lat: Double = 0.0, + ): CircleState { + val metersPerPx = 2 * PI * 6378137.0 / (256.0 * (1 shl z)) + return CircleState( + center = p(lat, lng), + radiusMeters = radiusPx * metersPerPx, + fillColor = fill, + strokeColor = stroke, + strokeWidth = strokeWidth.dp, + id = id, + zIndex = zIndex, + ) + } + + /** 中心は塗りの色、半径の所に縁の色 */ + @Test + fun tiledManagerSharesSourceStatesWithoutPersistentEntities() = kotlinx.coroutines.runBlocking { + val states = List(2001) { i -> CircleState(center = GeoPoint(0.001 * i, 0.0), radiusMeters = 5.0, id = "shared-$i") } + val tiler = CircleTiler() + val manager = CircleManager() + try { + tiler.route(states) + assertTrue(manager.setTiledSource(tiler)) + assertTrue(manager.nativeEntities().isEmpty()) + assertTrue(manager.hasEntity("shared-123")) + org.junit.Assert.assertSame(states[123], manager.getEntity("shared-123")!!.state) + org.junit.Assert.assertSame(states[123], manager.find(states[123].center)!!.state) + assertTrue(manager.nativeEntities().isEmpty()) + val replacement = states[25].copy(radiusMeters = 8.0) + tiler.update(replacement) + org.junit.Assert.assertSame(replacement, manager.getEntity(replacement.id)!!.state) + tiler.remove("shared-123") + org.junit.Assert.assertFalse(manager.hasEntity("shared-123")) + assertNull(manager.getEntity("shared-123")) + manager.clear() + org.junit.Assert.assertFalse(manager.hasEntity("shared-25")) + } finally { tiler.dispose() } + } + + @Test + fun subpixelOverlapKeepsOnlyTopCircle_andZoomRestoresBoth() { + val lower = equatorCircle(0.0, 0.2, 0, fill = Color(0x800000FF), id = "lower") + val upper = equatorCircle(0.0, 0.2, 0, fill = Color(0x80FF0000), id = "upper") + val r = renderer(lower, upper) + val small = r.renderBitmap(0, 0, 0)!! + assertEquals(0, rgb(small.getPixel(128, 128)) and 0xFF) + assertEquals(128, alpha(small.getPixel(128, 128))) + val large = r.renderBitmap(8, 8, 4)!! + assertTrue("both translucent circles return", (large.getPixel(0, 0) and 0xFF) > 0) + assertTrue(alpha(large.getPixel(0, 0)) > 128) + } + + @Test + fun centreIsFilled_andTheEdgeIsStroked() { + // z4: 世界 4096 px。経度 -168.75 度 = x 128(タイル 0 の真ん中)、北緯 10 度 = y 1933.6(タイル 7) + val lat = 10.0 + val z = 4 + val state = equatorCircle(lng = -168.75, radiusPx = 40.0, z = z, fill = Color(0xFF0000FF), lat = lat) + val bitmap = renderer(state).renderBitmap(0, 7, z)!! + val cx = worldX(-168.75, z) - 0 + val cy = worldY(lat, z) - 7 * 256 + assertEquals("中心は塗り", 0x0000FF, rgb(bitmap.getPixel(cx.toInt(), cy.toInt()))) + // 赤道の 40 px は緯度 10 度で 40 / cos(10°) ≒ 40.6 px(メルカトルで地上の大きさ) + val radius = 40.0 / kotlin.math.cos(lat * PI / 180) + val row = cy.toInt() + val painted = paintedColumns(bitmap, row) + assertEquals("左端", cx - radius - 1, painted.first().toDouble(), 1.5) + assertEquals("右端", cx + radius + 1, painted.last().toDouble() + 1, 1.5) + assertEquals("縁は赤", 0xFF0000, rgb(bitmap.getPixel((cx + radius).toInt(), row))) + assertEquals("外は透明", 0, alpha(bitmap.getPixel((cx + radius + 4).toInt(), row))) + } + + /** タイルの境目にかかる円は、両側のタイルに同じ位置・大きさで欠けずに出る */ + @Test + fun circleOnATileEdgeIsDrawnOnBothSides() { + // z1: 経度 0 度は x 方向のタイルの境目。中心をそこに置く + val z = 1 + val state = equatorCircle(lng = 0.0, radiusPx = 30.0, z = z, fill = Color(0xFF00FF00), stroke = green, lat = 30.0) + val r = renderer(state) + val west = r.renderBitmap(0, 0, z)!! + val east = r.renderBitmap(1, 0, z)!! + val row = worldY(30.0, z).toInt() + val westCols = paintedColumns(west, row) + val eastCols = paintedColumns(east, row) + // 西のタイルは右端まで、東のタイルは左端から塗る。幅は左右で同じ + assertEquals(255, westCols.last()) + assertEquals(0, eastCols.first()) + assertEquals((256 - westCols.first()).toDouble(), (eastCols.last() + 1).toDouble(), 1.0) + // 中心の行で切れ目が無い(境目の両側の画素が塗られている) + assertTrue(alpha(west.getPixel(255, row)) > 0x80 && alpha(east.getPixel(0, row)) > 0x80) + } + + /** ズームを 1 段上げると半径の画素数は 2 倍(地上の大きさが保たれる)、縁幅は同じ */ + @Test + fun radiusDoublesPerZoom_strokeStaysTheSame() { + // ボストンの、z17 でタイルの 1/3 の所: z18 で 2/3、z19 で 1/3。どのズームでも円がタイルに収まる + val scale17 = 256.0 * (1 shl 17) + val wx17 = (floor(worldX(-71.0605, 17) / 256) + 1.0 / 3) * 256 + val wy17 = (floor(worldY(42.3555, 17) / 256) + 1.0 / 3) * 256 + val lng = wx17 / scale17 * 360 - 180 + val lat = kotlin.math.atan(kotlin.math.sinh(PI * (1 - 2 * wy17 / scale17))) * 180 / PI + val state = + CircleState( + center = p(lat, lng), + radiusMeters = 15.0, + fillColor = Color.Transparent, + strokeColor = blue, + strokeWidth = 2.dp, + ) + val r = renderer(state) + val widths = mutableListOf() + val strokes = mutableListOf() + for (z in 17..19) { + val wx = worldX(lng, z) + val wy = worldY(lat, z) + val tx = (wx / 256).toInt() + val ty = (wy / 256).toInt() + val bitmap = r.renderBitmap(tx, ty, z) + assertNotNull("z$z", bitmap) + val row = (wy - ty * 256).toInt() + val cols = paintedColumns(bitmap!!, row) + widths += cols.last() - cols.first() + // 縁幅: 左の縁の塗られた列の数 + var n = 0 + var c = cols.first() + while (c < 256 && alpha(bitmap.getPixel(c, row)) > 0x80) { + n++ + c++ + } + strokes += n + } + assertEquals("$widths", widths[0] * 2.0, widths[1].toDouble(), 2.5) + assertEquals("$widths", widths[1] * 2.0, widths[2].toDouble(), 2.5) + assertTrue("$strokes", strokes.all { it in 1..3 }) + } + + /** 直径 1 px 未満は 1 px の点(アンチエイリアスなし、塗りの色) */ + @Test + fun subPixelCircleIsOnePixel() { + val state = CircleState(center = p(0.0, 0.0), radiusMeters = 100.0, fillColor = Color(0xFF00FF00), strokeColor = red) + val bitmap = renderer(state).renderBitmap(0, 0, 0)!! + var painted = 0 + for (py in 120..136) { + for (px in 120..136) { + val pixel = bitmap.getPixel(px, py) + if (alpha(pixel) > 0) { + painted++ + assertEquals(0x00FF00, rgb(pixel)) + assertEquals(0xFF, alpha(pixel)) + } + } + } + assertEquals(1, painted) + assertTrue(alpha(bitmap.getPixel(128, 128)) == 0xFF) + } + + /** 直径 4 px 未満は縁を描かない(塗りだけ) */ + @Test + fun underFourPixelsAcrossHasNoOutline() { + val state = equatorCircle(lng = 0.0, radiusPx = 1.5, z = 0, fill = Color(0xFF00FF00), stroke = red, strokeWidth = 2f) + val bitmap = renderer(state).renderBitmap(0, 0, 0)!! + for (py in 120..136) { + for (px in 120..136) { + val pixel = bitmap.getPixel(px, py) + if (alpha(pixel) > 0) assertTrue("($px, $py) ${Integer.toHexString(pixel)}", (pixel and 0xFF0000) ushr 16 < 0x40) + } + } + } + + /** 高緯度(70 度、200 km)は 128 角形で、circleToRing の点が通る画素に縁がある */ + @Test + fun highLatitudeCircleIsTheNativeRing() { + val state = + CircleState( + center = p(70.0, 20.0), + radiusMeters = 200_000.0, + fillColor = Color.Transparent, + strokeColor = red, + strokeWidth = 3.dp, + ) + val z = 5 + val r = renderer(state) + val ring = toMercatorRing(circleToRing(state.center, 200_000.0, true, 128)) + val scale = 256.0 * (1 shl z) + var checked = 0 + for (i in ring.indices step 2 * 8) { + val wx = ring[i] * scale + val wy = ring[i + 1] * scale + val tx = (wx / 256).toInt() + val ty = (wy / 256).toInt() + val bitmap = r.renderBitmap(tx, ty, z) ?: continue + val px = (wx - tx * 256).toInt().coerceIn(0, 255) + val py = (wy - ty * 256).toInt().coerceIn(0, 255) + // 点のまわり 1 画素に縁 + val near = + (-1..1).any { dy -> + (-1..1).any { dx -> + val x = (px + dx).coerceIn(0, 255) + val y = (py + dy).coerceIn(0, 255) + alpha(bitmap.getPixel(x, y)) > 0x80 && rgb(bitmap.getPixel(x, y)) == 0xFF0000 + } + } + assertTrue("点 $i ($wx, $wy)", near) + checked++ + } + assertEquals(16, checked) + } + + /** zIndex の大きい円が上、未指定は中心からの自動値(南が上) */ + @Test + fun higherZIndexIsOnTop_andUnsetIsTheAutomaticOne() = + runBlocking { + val set = CircleTileSet() + try { + val over = equatorCircle(lng = 0.0, radiusPx = 20.0, z = 0, fill = red, stroke = red, zIndex = 1) + val under = equatorCircle(lng = 0.0, radiusPx = 20.0, z = 0, fill = blue, stroke = blue, zIndex = 0) + set.setCircles(listOf(over, under)) + val bitmap = set.renderer.renderBitmap(0, 0, 0)!! + assertEquals("zIndex 1 が上", 0xFF0000, rgb(bitmap.getPixel(bitmap.width / 2, bitmap.height / 2))) + + // 未指定: 南の円(自動値が大きい)が北の円の上 + val south = equatorCircle(lng = 0.0, radiusPx = 20.0, z = 0, fill = green, stroke = green, zIndex = null, lat = -1.0) + val north = equatorCircle(lng = 0.0, radiusPx = 20.0, z = 0, fill = red, stroke = red, zIndex = null, lat = 1.0) + set.setCircles(listOf(south, north)) + val auto = set.renderer.renderBitmap(0, 0, 0)!! + assertEquals("南が上", 0x00FF00, rgb(auto.getPixel(auto.width / 2, auto.height / 2))) + } finally { + set.dispose() + } + } + + /** 透明な円は描かない。何も無いタイルは null(空) */ + @Test + fun invisibleCirclesDrawNothing_andEmptyTilesAreNull() { + val r = + renderer( + CircleState(center = p(40.0, 90.0), radiusMeters = 500_000.0, fillColor = Color.Transparent, strokeColor = Color.Transparent), + CircleState(center = p(40.0, 90.0), radiusMeters = 500_000.0, fillColor = Color.Transparent, strokeWidth = 0.dp), + ) + assertNull(r.renderTile(TileRequest(x = 1, y = 0, z = 1))) + assertNull(r.renderTile(TileRequest(x = 0, y = 0, z = 1))) + } + + /** 色を変えたら、その円のタイルだけ描き直す(他はキャッシュ) */ + @Test + fun inPlaceChangeRedrawsOnlyTheTilesItTouches() { + val west = CircleState(center = p(30.0, -90.0), radiusMeters = 300_000.0, fillColor = blue, strokeColor = blue, id = "west") + val east = CircleState(center = p(30.0, 90.0), radiusMeters = 300_000.0, fillColor = blue, strokeColor = blue, id = "east") + val r = renderer(west, east) + val westTile = TileRequest(x = 0, y = 0, z = 1) + val eastTile = TileRequest(x = 1, y = 0, z = 1) + val westBefore = r.renderTile(westTile)!! + val eastBefore = r.renderTile(eastTile)!! + + // renderer() は実効 zIndex で並べる: 自動値は同じ緯度なら西が上(大きい)→ west は後ろ + val westIndex = listOf(west, east).sortedBy(::effectiveZIndex).indexOf(west) + west.fillColor = green + west.strokeColor = green + r.update(listOf(westIndex to TileCircle.from(west))) + + val westAfter = r.renderTile(westTile)!! + assertNotSame("変えた円のタイルは描き直す", westBefore, westAfter) + assertSame("触れていないタイルはキャッシュから返す", eastBefore, r.renderTile(eastTile)) + val decoded = BitmapFactory.decodeByteArray(westAfter, 0, westAfter.size) + assertEquals(0x00FF00, rgb(decoded.getPixel(worldX(-90.0, 1).toInt(), worldY(30.0, 1).toInt()))) + } + + /** 取りやめられたタイルは空ではなく失敗にする */ + @Test + fun cancelledTileFailsInsteadOfComingBackEmpty() { + val r = renderer(CircleState(center = p(0.0, 0.0), radiusMeters = 1_000_000.0, fillColor = blue)) + val thrown = runCatching { r.renderTile(TileRequest(x = 0, y = 0, z = 0)) { true } }.exceptionOrNull() + assertTrue(thrown is ShapeTileRenderer.TileRenderCancelled) + } +} diff --git a/src/androidTest/java/com/mapconductor/core/circle/CircleTilerDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/circle/CircleTilerDeviceTest.kt new file mode 100644 index 0000000..e94bb3b --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/circle/CircleTilerDeviceTest.kt @@ -0,0 +1,346 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.controller.BaseMapViewController +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.tileserver.TileServerRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.net.HttpURLConnection +import java.net.URL +import kotlin.math.ln +import kotlin.math.sin +import android.graphics.BitmapFactory +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout + +/** + * CircleController と CircleTiler の振り分け。PolylineTilerDeviceTest と同じ規則: + * タイルにした円は CircleManager に残し(タップ用、元の円のまま)、レンダラには渡さない。 + * js-sdk-core の CircleController(tiler)、ios-sdk-core の CircleTilerTests と同じ内容。 + * + * CircleTileSet が本物のタイルサーバーに経路を作るので、端末で動かす。 + */ +@RunWith(AndroidJUnit4::class) +class CircleTilerDeviceTest { + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + private val events = mutableListOf() + + /** 半径 20 m の木を n 本、ボストンに 0.0012 度(東西 ≒ 99 m、南北 ≒ 133 m)おきに並べる。 */ + private fun trees( + n: Int, + color: Color = Color(0xFF12B886), + ): List = + List(n) { i -> + val lat = 42.30 + (i / 100) * 0.0012 + val lng = -71.10 + (i % 100) * 0.0012 + CircleState( + center = p(lat, lng), + radiusMeters = 20.0, + id = "tree-$i", + fillColor = color, + strokeColor = color, + strokeWidth = 2.dp, + zIndex = 0, + onAdded = { events += "onAdded:${it.id}" }, + ) + } + + private inner class Renderer : CircleOverlayRendererInterface { + val onMap = mutableSetOf() + val added = mutableListOf() + val removed = mutableListOf() + + override suspend fun onAdd(data: List): List = + data.map { params -> + events += "native:${params.state.id}" + params.state.id.also { + onMap.add(it) + added.add(it) + } + } + + override suspend fun onChange(data: List>): List = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) { + data.forEach { + onMap.remove(it.state.id) + removed.add(it.state.id) + } + } + + override suspend fun onPostProcess() {} + } + + private class Controller( + renderer: CircleOverlayRendererInterface, + ) : CircleController(CircleManager(), renderer) + + private class Templates { + val seen = mutableListOf() + + fun last() = synchronized(this) { seen.lastOrNull() } + } + + private fun controller(options: CircleTilingOptions = CircleTilingOptions.Default): Triple { + val renderer = Renderer() + val controller = Controller(renderer) + val templates = Templates() + controller.tiler = + CircleTiler(options).apply { + onTemplate = { template, _ -> synchronized(templates) { templates.seen.add(template) } } + } + return Triple(controller, renderer, templates) + } + + /** しきい値を超えたらネイティブには何も渡さず、タップ用にマネージャへ残す */ + @Test + fun pastThresholdNothingGoesNative_andTapsStillHit() = + runBlocking { + val (controller, renderer, templates) = controller() + controller.onCameraChanged(MapCameraPosition(position = p(42.30, -71.10), zoom = 16.0)) + controller.add(trees(2001)) + assertTrue(renderer.onMap.isEmpty()) + assertEquals(2001, controller.circleManager.allEntities().size) + assertNotNull(templates.last()) + // tree-101: 北緯 42.3012、経度 -71.0988。中心から 15 m 東は当たる + assertEquals("tree-101", controller.find(p(42.3012, -71.09862))?.state?.id) + // 木と木の間は外れ + assertNull(controller.find(p(42.3018, -71.0982))) + } + + /** しきい値を下回ったらネイティブに戻し、上回ったらネイティブから外す */ + @Test + fun crossingThresholdMovesCirclesBetweenNativeAndTiles() = + runBlocking { + val (controller, renderer, templates) = controller() + controller.add(trees(2000)) + assertEquals(2000, renderer.onMap.size) + assertNull(templates.last()) + + controller.add(trees(2001)) + assertTrue("タイルへ移ったらネイティブから消す", renderer.onMap.isEmpty()) + assertEquals(2001, controller.circleManager.allEntities().size) + assertNotNull(templates.last()) + + controller.add(trees(10)) + assertEquals(10, renderer.onMap.size) + assertEquals("リストから消えたものは忘れる", 10, controller.circleManager.allEntities().size) + assertNull(templates.last()) + } + + /** タイルの円のその場の変更は、版を上げたテンプレートで知らせる */ + @Test + fun inPlaceChangeOfTiledCircleAnnouncesNewTemplate() = + runBlocking { + val (controller, renderer, templates) = controller() + val states = trees(2001) + controller.add(states) + val before = templates.last()!! + states[5].fillColor = Color(0xFFE64980) + controller.update(states[5]) + assertTrue(renderer.onMap.isEmpty()) + withTimeout(2000) { + while (templates.last() == before) delay(5) + } + assertTrue(templates.last()!! != before) + assertEquals(Color(0xFFE64980), controller.circleManager.getEntity("tree-5")?.state?.fillColor) + } + + /** タイルはタイルサーバーから PNG で届き、何も無い場所は透明の 200。URL に版が入る */ + @Test + fun tilesAreServedAsPng_andEmptyPlacesAsTransparent200() = + runBlocking { + val (controller, _, templates) = controller() + controller.add(trees(2001)) + val template = templates.last()!! + assertTrue("版が入る: $template", Regex("""/circles-\w+/256/\d+/\{z\}""").containsMatchIn(template)) + assertTrue(alphaAt(template, 42.3012, -71.0988, 17) > 0) + assertEquals("木と木の間", 0, alphaAt(template, 42.3018, -71.0982, 17)) + assertEquals(200, get(template, 14, 100, 12000).first) + } + + /** clear でテンプレートを外し、タイル側の円も忘れる */ + @Test + fun clearRemovesTemplateAndForgetsTiledCircles() = + runBlocking { + val (controller, _, templates) = controller() + controller.add(trees(2001)) + controller.clear() + assertNull(templates.last()) + assertTrue(controller.circleManager.allEntities().isEmpty()) + assertTrue(TileServerRegistry.get().isRunning()) + } + + /** 混在リストでは日付変更線の円だけネイティブ、タイルには描かれない */ + @Test + fun inAMixedListOnlyTheAntimeridianOneGoesNative() = + runBlocking { + val (controller, renderer, templates) = controller() + val dateline = CircleState(center = p(0.0, 179.999), radiusMeters = 5_000.0, id = "dateline") + controller.add(trees(2001) + dateline) + assertEquals(setOf("dateline"), renderer.onMap) + assertTrue(alphaAt(templates.last()!!, 42.3012, -71.0988, 17) > 0) + } + + /** その場で日付変更線へ動かしたらネイティブへ移り(add ではない、onAdded は呼ばない)、タイルから消える */ + @Test + fun movingOntoTheAntimeridianInPlaceMovesItToNative() = + runBlocking { + val (controller, renderer, templates) = controller() + // One becomes native; the remaining 2,001 must still exceed 2,000. + val states = trees(2002) + controller.add(states) + val before = templates.last()!! + assertTrue(alphaAt(before, 42.3012, -71.0988, 17) > 0) + events.clear() + + states[101].center = p(0.0, 179.999) + states[101].radiusMeters = 5_000.0 + controller.update(states[101]) + withTimeout(2000) { + while (templates.last() == before) delay(5) + } + assertEquals(listOf("tree-101"), renderer.added) + assertEquals("tree-101", controller.circleManager.getEntity("tree-101")?.circle) + assertEquals(listOf("native:tree-101"), events) + val after = templates.last()!! + assertEquals("タイルから消える", 0, alphaAt(after, 42.3012, -71.0988, 17)) + assertTrue("隣はタイルに残る", alphaAt(after, 42.3012, -71.0976, 17) > 0) + + // 同じリストを渡し直しても、ネイティブのまま(足しも消しもしない) + controller.add(states) + assertEquals(listOf("tree-101"), renderer.added) + assertTrue(renderer.removed.isEmpty()) + } + + // ── onAdded と地図ごとの指定(CircleOverlay 経由、本物の BaseMapViewController) ────── + + private class Driver( + val circles: Controller, + ) : BaseMapViewController() { + override val holder get() = throw UnsupportedOperationException() + override val defaultCoroutine = CoroutineScope(Dispatchers.Unconfined) + override val mainCoroutine = defaultCoroutine + + init { + registerOverlayController(circles) + } + + override fun moveCamera(position: MapCameraPosition) = Unit + + override fun animateCamera( + position: MapCameraPosition, + duration: Long, + ) = Unit + + override fun fitBounds( + bounds: GeoRectBounds, + padding: Int, + ) = Unit + + override suspend fun clearOverlays() = circles.clear() + } + + private fun CircleOverlay.show( + map: Driver, + states: List, + ) = runBlocking { render(states.associateBy { it.id }.toMutableMap(), map) } + + /** タイルで地図に載った円にも onAdded。その場の変更とネイティブへの移動では呼ばない */ + @Test + fun onAddedOnTheTilePath() { + val (controller, renderer, _) = controller(CircleTilingOptions(minCircleCount = 3)) + val map = Driver(controller) + val overlay = CircleOverlay(MutableStateFlow(mutableMapOf())) + val states = trees(4) + overlay.show(map, states) + assertEquals(listOf("onAdded:tree-0", "onAdded:tree-1", "onAdded:tree-2", "onAdded:tree-3"), events) + assertTrue(renderer.onMap.isEmpty()) + events.clear() + + states[0].fillColor = Color.Red + runBlocking { map.updateCircle(states[0]) } + states[1].radiusMeters = 0.0 + runBlocking { map.updateCircle(states[1]) } + overlay.show(map, states) + assertEquals(listOf("native:tree-1"), events) + controller.destroy() + } + + /** 地図ごとの指定(CircleOverlay の tilingOptions)は、次に円を渡すときに効く */ + @Test + fun perMapOptionsApplyOnTheNextHandOver() { + val (controller, renderer, templates) = controller() + val map = Driver(controller) + val options = MutableStateFlow(CircleTilingOptions.Disabled) + val overlay = CircleOverlay(MutableStateFlow(mutableMapOf()), options) + val states = trees(2001) + + overlay.show(map, states) + assertEquals("Disabled: 全部ネイティブ", 2001, renderer.onMap.size) + assertNull(templates.last()) + + options.value = CircleTilingOptions.Default + overlay.show(map, states) + assertTrue("Default: 全部タイル", renderer.onMap.isEmpty()) + assertNotNull(templates.last()) + assertEquals(CircleTilingOptions.Default, controller.tiler?.options) + controller.destroy() + } + + private fun alphaAt( + template: String, + lat: Double, + lng: Double, + z: Int, + ): Int { + val n = 1 shl z + val s = sin(Math.toRadians(lat)) + val my = 0.5 - ln((1 + s) / (1 - s)) / (4 * Math.PI) + val x = ((lng + 180) / 360 * n).toInt() + val y = (my * n).toInt() + val (code, bytes) = get(template, z, x, y) + assertEquals(200, code) + val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return 0 + val scale = 256.0 * n + val px = (lng + 180) / 360 * scale - x * 256 + val py = my * scale - y * 256 + val k = bitmap.width / 256.0 + return bitmap.getPixel((px * k).toInt(), (py * k).toInt()) ushr 24 + } + + private fun get( + template: String, + z: Int, + x: Int, + y: Int, + ): Pair { + val url = template.replace("{z}", "$z").replace("{x}", "$x").replace("{y}", "$y") + val connection = URL(url).openConnection() as HttpURLConnection + connection.useCaches = false + return try { + connection.responseCode to connection.inputStream.use { it.readBytes() } + } finally { + connection.disconnect() + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/polygon/PolygonAuditDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/polygon/PolygonAuditDeviceTest.kt new file mode 100644 index 0000000..bfccc43 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/polygon/PolygonAuditDeviceTest.kt @@ -0,0 +1,67 @@ +package com.mapconductor.core.polygon + +import android.graphics.BitmapFactory +import androidx.compose.ui.graphics.Color +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import java.net.URL + +@RunWith(AndroidJUnit4::class) +/** Regression coverage for draw order and interrupted native-to-tile transitions. */ +class PolygonAuditDeviceTest { + private fun state(id: String, color: Color = Color.Red, z: Int = 0) = PolygonState( + id = id, points = listOf(GeoPoint(-20.0,-20.0), GeoPoint(-20.0,20.0), GeoPoint(20.0,20.0), GeoPoint(20.0,-20.0)), + fillColor = color, zIndex = z, + ) + private fun pixel(template: String): Int { + val bytes = URL(template.replace("{z}","0").replace("{x}","0").replace("{y}","0")).readBytes() + val b = BitmapFactory.decodeByteArray(bytes,0,bytes.size) + return b.getPixel(b.width/2,b.height/2).also { b.recycle() } + } + @Test fun changingZIndexMustReorderTiles() = runBlocking { + val controller = object : PolygonController(PolygonManager(),Renderer()) {} + var template = "" + controller.tiler = PolygonTiler(PolygonTilingOptions(minPolygonCount=2)).apply { + onTemplate = { value, _ -> template = value.orEmpty() } + } + try { + val red = state("red",Color.Red,0) + val blue = state("blue",Color.Blue,1) + controller.add(listOf(red,blue)) + assertEquals(android.graphics.Color.BLUE,pixel(template)) + red.zIndex = 2 + controller.update(red) + assertEquals("red should now cover blue",android.graphics.Color.RED,pixel(template)) + } finally { controller.destroy() } + } + private class Renderer : PolygonOverlayRendererInterface { + val onMap = mutableSetOf() + var cancelRemoval = false + override suspend fun onAdd(data: List) = data.map { it.state.id.also(onMap::add) } + override suspend fun onChange(data: List>) = data.map { it.current.state.id } + override suspend fun onRemove(data: List>) { + if (cancelRemoval) { cancelRemoval = false; throw CancellationException("simulated resync cancellation") } + data.forEach { onMap.remove(it.state.id) } + } + override suspend fun onPostProcess() {} + } + @Test fun cancelledTransitionMustRetryNativeRemoval() = runBlocking { + val renderer = Renderer() + val controller = object : PolygonController(PolygonManager(),renderer) {} + controller.tiler = PolygonTiler(PolygonTilingOptions(minPolygonCount=2)) + try { + val first = state("first") + controller.add(listOf(first)) + renderer.cancelRemoval = true + val many = listOf(first,state("second")) + try { controller.add(many); fail("expected cancellation") } catch (_: CancellationException) {} + controller.add(many) + assertTrue("native polygon must be removed after retry: ${renderer.onMap}",renderer.onMap.isEmpty()) + } finally { controller.destroy() } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerCancellationTest.kt b/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerCancellationTest.kt index eb8dcde..869a1af 100644 --- a/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerCancellationTest.kt +++ b/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerCancellationTest.kt @@ -199,4 +199,43 @@ class LocalTileServerCancellationTest { } } } + + @Test + fun frequentCancellationChecksDoNotBecomeSocketTimeoutWaits() { + val elapsed = java.util.concurrent.atomic.AtomicLong() + server.register(routeId, object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray = png + override fun renderTile(request: TileRequest, isCancelled: () -> Boolean): ByteArray { + val began = System.nanoTime() + repeat(10_000) { assertTrue("live client was cancelled", !isCancelled()) } + elapsed.set((System.nanoTime() - began) / 1_000_000) + return png + } + }) + assertTrue(statusOf(tileUrl(10)).contains("200")) + assertTrue("10k checks took ${elapsed.get()}ms", elapsed.get() < 1500) + } + + @Test + fun idleKeepAliveConnectionsDoNotStarveNewTiles() { + server.register(routeId, object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray = png + }) + val url = tileUrl(10) + val idle = mutableListOf() + try { + repeat(8) { + val socket = Socket(url.host, url.port) + idle.add(socket) + socket.soTimeout = 10_000 + socket.getOutputStream().write("GET ${url.path} HTTP/1.1\r\nHost: ${url.host}\r\n\r\n".toByteArray()) + socket.getOutputStream().flush() + assertTrue(readResponse(socket.getInputStream())!!.status.contains("200")) + } + val began = System.nanoTime() + assertTrue(statusOf(url).contains("200")) + val elapsed = (System.nanoTime() - began) / 1_000_000 + assertTrue("new tile waited ${elapsed}ms behind idle connections", elapsed < 1500) + } finally { idle.forEach { it.close() } } + } } diff --git a/src/androidTest/res/xml/test_network_security_config.xml b/src/androidTest/res/xml/test_network_security_config.xml new file mode 100644 index 0000000..a7b17d9 --- /dev/null +++ b/src/androidTest/res/xml/test_network_security_config.xml @@ -0,0 +1,8 @@ + + + + + 127.0.0.1 + localhost + + diff --git a/src/main/java/com/mapconductor/core/OverlayAddedTracker.kt b/src/main/java/com/mapconductor/core/OverlayAddedTracker.kt index 4090a60..75a6365 100644 --- a/src/main/java/com/mapconductor/core/OverlayAddedTracker.kt +++ b/src/main/java/com/mapconductor/core/OverlayAddedTracker.kt @@ -49,28 +49,34 @@ internal class OverlayAddedTracker( controller: Any, data: Collection, isOnMap: (T) -> Boolean, + sourceIds: Set? = null, ) { if (controller !== this.controller) { this.controller = controller onMap = emptySet() } val previous = onMap - val next = HashSet(data.size * 2) + // A completed bulk composition can share its immutable generation's + // source-map keys. Allocate a new ID set only for partial admission. + val next = if (sourceIds == null) HashSet(data.size * 2) else null + var missing: MutableSet? = null var added: MutableList? = null var checked = 0 for (state in data) { if (++checked % CHECKS_PER_YIELD == 0) yield() val id = state.id if (id in previous) { - next.add(id) + next?.add(id) } else if (isOnMap(state)) { - next.add(id) - (added ?: ArrayList().also { added = it }).add(state) + next?.add(id) + if (onAddedOf(state) != null) (added ?: ArrayList().also { added = it }).add(state) + } else if (sourceIds != null) { + (missing ?: HashSet().also { missing = it }).add(id) } } // Recorded and called without suspending, so a cancellation cannot // leave some of them called and the rest forgotten. - onMap = next + onMap = next ?: if (missing == null) sourceIds!! else sourceIds!!.filterTo(HashSet()) { it !in missing!! } added?.let(::notify) } diff --git a/src/main/java/com/mapconductor/core/OverlayCollector.kt b/src/main/java/com/mapconductor/core/OverlayCollector.kt index de63ddc..3ad897a 100644 --- a/src/main/java/com/mapconductor/core/OverlayCollector.kt +++ b/src/main/java/com/mapconductor/core/OverlayCollector.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull @@ -107,27 +108,27 @@ class OverlayCollector( */ private val listening = ConcurrentHashMap() - /** Ids this collector started listening to because they appeared in [flow], not through [add]. */ - private val listenedFromFlow = ConcurrentHashMap.newKeySet() + /** Only direct adds waiting for their debounced membership publication. */ + private val pendingAdds = ConcurrentHashMap.newKeySet() init { scope.launch { addSharedFlow.debounceBatch(5.milliseconds, 100).collect { states -> - val newMap = flow.value.toMutableMap() - states.forEach { state -> - newMap[state.id] = state + flow.update { current -> + copyOverlayStates(current).apply { + states.forEach { state -> this[state.id] = state } + } } - flow.value = newMap } } scope.launch { removeSharedFlow.debounceBatch(5.milliseconds, 300).collect { ids -> - val newMap = flow.value.toMutableMap() - ids.forEach { id -> - newMap.remove(id) + flow.update { current -> + copyOverlayStates(current).apply { + ids.forEach { id -> remove(id) } + } } - flow.value = newMap } } @@ -146,27 +147,29 @@ class OverlayCollector( for ((id, state) in states) { if (listening[id] !== state) { listen(state) - listenedFromFlow.add(id) } + pendingAdds.remove(id) } // Only stop what this path started: a state added through [add] may not // have reached [flow] yet (membership is debounced). - val iterator = listenedFromFlow.iterator() - while (iterator.hasNext()) { - val id = iterator.next() - if (id !in states) { + // The listener map already identifies every registered state. Keep a + // small exception set for pending direct adds rather than duplicating + // the IDs of an entire bulk collection in another concurrent hash set. + for (id in listening.keys) { + if (id !in states && id !in pendingAdds) { unlisten(id) - iterator.remove() } } } override suspend fun add(state: T) { + pendingAdds.add(state.id) listen(state) addSharedFlow.emit(state) } override fun remove(id: String) { + pendingAdds.remove(id) unlisten(id) removeSharedFlow.tryEmit(id) } @@ -194,7 +197,8 @@ class OverlayCollector( } override fun replaceAll(states: List) { - val next = states.associateBy { it.id }.toMutableMap() + val next = copyOverlayStates(emptyMap()) + for (state in states) next[state.id] = state for (id in listening.keys.toList()) { if (next[id] !== listening[id]) unlisten(id) } diff --git a/src/main/java/com/mapconductor/core/OverlayStateMaps.kt b/src/main/java/com/mapconductor/core/OverlayStateMaps.kt new file mode 100644 index 0000000..c38e4bb --- /dev/null +++ b/src/main/java/com/mapconductor/core/OverlayStateMaps.kt @@ -0,0 +1,20 @@ +package com.mapconductor.core + +import kotlinx.collections.immutable.toPersistentMap +import kotlinx.collections.immutable.persistentHashSetOf + +/** + * A new writable generation, sharing unchanged entries with the published map. + * Finish writing before publishing; never mutate a published generation. + * Keeps the collector's MutableMap contract and insertion order. + */ +@InternalMapConductorApi +fun copyOverlayStates(current: Map): MutableMap = + synchronized(current) { current.toPersistentMap().builder() } + +/** Compact membership snapshot without a linked hash entry for every state. */ +@InternalMapConductorApi +fun overlayStateIds(states: Iterable): Set = + persistentHashSetOf().builder().apply { + for (state in states) add(state.id) + }.build() diff --git a/src/main/java/com/mapconductor/core/circle/Circle.kt b/src/main/java/com/mapconductor/core/circle/Circle.kt index 7bcb354..5abb449 100644 --- a/src/main/java/com/mapconductor/core/circle/Circle.kt +++ b/src/main/java/com/mapconductor/core/circle/Circle.kt @@ -36,16 +36,82 @@ class CircleState( */ override val mutations = StateMutationSignal() - var center by mutations.notifying(center) - var clickable by mutations.notifying(clickable) - var radiusMeters by mutations.notifying(radiusMeters) - var geodesic by mutations.notifying(geodesic) - var strokeColor by mutations.notifying(strokeColor) - var strokeWidth by mutations.notifying(strokeWidth) - var fillColor by mutations.notifying(fillColor) - var extra by mutations.notifying(extra) - var zIndex by mutations.notifying(zIndex) - var onClick by mutations.notifying(onClick) + // One Compose snapshot record per circle, rather than one per attribute. + private data class Values( + val center: GeoPointInterface, + val clickable: Boolean, + val radiusMeters: Double, + val geodesic: Boolean, + val strokeColor: Color, + val strokeWidth: Dp, + val fillColor: Color, + val extra: Serializable?, + val zIndex: Int?, + val onClick: OnCircleEventHandler?, + val revision: Long = 0, + val changedFields: Int = 0, + ) { + fun difference(other: Values): Int { + var mask = 0 + if (center != other.center) mask = mask or (1 shl 0) + if (clickable != other.clickable) mask = mask or (1 shl 3) + if (radiusMeters != other.radiusMeters) mask = mask or (1 shl 1) + if (geodesic != other.geodesic) mask = mask or (1 shl 2) + if (strokeColor != other.strokeColor) mask = mask or (1 shl 4) + if (strokeWidth != other.strokeWidth) mask = mask or (1 shl 5) + if (fillColor != other.fillColor) mask = mask or (1 shl 6) + if (extra != other.extra) mask = mask or (1 shl 7) + if (zIndex != other.zIndex) mask = mask or (1 shl 8) + return mask + } + } + internal fun captureValues(): Any = values + internal fun changeMaskSince(snapshot: Any, sameState: Boolean): Int { + val applied = snapshot as Values + val current = values + if (current === applied) return 0 + return if (sameState && current.revision != applied.revision) current.changedFields + else applied.difference(current) + } + internal fun snapshotFingerPrint(snapshot: Any): CircleFingerPrint = fingerPrint(snapshot as Values) + private var values by androidx.compose.runtime.mutableStateOf(Values(center, clickable, radiusMeters, geodesic, strokeColor, strokeWidth, fillColor, extra, zIndex, onClick)) + + private fun update(next: Values) { + if (values == next) return + values = next.copy(revision = values.revision + 1, changedFields = values.changedFields or values.difference(next)) + mutations.notifyMutated() + } + + var center: GeoPointInterface + get() = values.center + set(value) { update(values.copy(center = value)) } + var clickable: Boolean + get() = values.clickable + set(value) { update(values.copy(clickable = value)) } + var radiusMeters: Double + get() = values.radiusMeters + set(value) { update(values.copy(radiusMeters = value)) } + var geodesic: Boolean + get() = values.geodesic + set(value) { update(values.copy(geodesic = value)) } + var strokeColor: Color + get() = values.strokeColor + set(value) { update(values.copy(strokeColor = value)) } + var strokeWidth: Dp + get() = values.strokeWidth + set(value) { update(values.copy(strokeWidth = value)) } + var fillColor: Color + get() = values.fillColor + set(value) { update(values.copy(fillColor = value)) } + var extra: Serializable? + get() = values.extra + set(value) { update(values.copy(extra = value)) } + var zIndex: Int? + get() = values.zIndex + set(value) { update(values.copy(zIndex = value)) } + var onClick: OnCircleEventHandler? + get() = values.onClick + set(value) { update(values.copy(onClick = value)) } /** * Called once each time this circle goes from not being on the map to being on it: @@ -120,18 +186,20 @@ class CircleState( 31 * result + hashCode } - fun fingerPrint(): CircleFingerPrint = + fun fingerPrint(): CircleFingerPrint = fingerPrint(values) + + private fun fingerPrint(snapshot: Values): CircleFingerPrint = CircleFingerPrint( id = this.id.hashCode(), - center = center.hashCode(), - radiusMeters = radiusMeters.hashCode(), - clickable = clickable.hashCode(), - geodesic = geodesic.hashCode(), - strokeColor = strokeColor.hashCode(), - strokeWidth = strokeWidth.hashCode(), - fillColor = fillColor.hashCode(), - zIndex = zIndex.hashCode(), - extra = extra?.hashCode() ?: 0, + center = snapshot.center.hashCode(), + radiusMeters = snapshot.radiusMeters.hashCode(), + clickable = snapshot.clickable.hashCode(), + geodesic = snapshot.geodesic.hashCode(), + strokeColor = snapshot.strokeColor.hashCode(), + strokeWidth = snapshot.strokeWidth.hashCode(), + fillColor = snapshot.fillColor.hashCode(), + zIndex = snapshot.zIndex.hashCode(), + extra = snapshot.extra?.hashCode() ?: 0, ) fun copy( diff --git a/src/main/java/com/mapconductor/core/circle/CircleController.kt b/src/main/java/com/mapconductor/core/circle/CircleController.kt index 2d7b963..3e8c992 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleController.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleController.kt @@ -1,11 +1,15 @@ package com.mapconductor.core.circle +import com.mapconductor.core.controller.OnCameraChangeReceiverInterface import com.mapconductor.core.controller.OverlayHit import com.mapconductor.core.controller.OverlayKind import com.mapconductor.core.controller.SlottedOverlayController import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.map.MapCameraPosition +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit +import kotlinx.coroutines.withContext abstract class CircleController( val circleManager: CircleManagerInterface, @@ -13,12 +17,23 @@ abstract class CircleController( ) : SlottedOverlayController< CircleState, CircleEntityInterface, - > { + >, + OnCameraChangeReceiverInterface { override val zIndex: Int = 4 val semaphore = Semaphore(1) + private var currentCameraPosition: MapCameraPosition? = null var clickListener: OnCircleEventHandler? = null + /** + * Set by a provider that can show circle tiles (see [CircleTiler]). + * Circles it tiles stay in [circleManager], for taps, with no native + * overlay: their entity's `circle` is null and the renderer never sees + * them. A renderer that redraws from the manager must skip those. + */ + var tiler: CircleTiler? = null + private var tiledIds: Set = emptySet() + fun dispatchClick(event: CircleEvent) { // 配送座標の wrap は CircleEvent の生成時に一元化済み。 event.state.onClick?.invoke(event) @@ -27,17 +42,27 @@ abstract class CircleController( override suspend fun add(data: List) { semaphore.withPermit { + val wasTiled = tiledIds + val tiled = tiler?.route(data) ?: emptySet() + val sharedTiles = circleManager.setTiledSource(tiler) + tiledIds = tiled + val native = if (tiled.isEmpty()) data else data.filter { it.id !in tiled } val modifiedEntities = mutableListOf>() - val previous = circleManager.allEntities().map { it.state.id }.toMutableSet() + // Only natively drawn circles are diffed against the renderer. + val previous = + circleManager + .nativeEntities() + .map { it.state.id } + .filterTo(mutableSetOf()) { it !in wasTiled } val added = mutableListOf() val updated = mutableListOf>() val removed = mutableListOf>() - data.forEach { state -> + native.forEach { state -> if (previous.contains(state.id)) { // Gone only if destroy() cleared the manager meanwhile; nothing left to update. val prevEntity = circleManager.getEntity(state.id) ?: return@withPermit - if (state.fingerPrint() == prevEntity.fingerPrint) { + if (unchanged(state, prevEntity)) { // 描画結果が不変なら renderer を呼ばず最新の state だけ採用する // (react-sdk と同じ。composition ごとに全オーバーレイへ onChange を // 再実行する無駄・チラつきを避ける)。 @@ -109,16 +134,69 @@ abstract class CircleController( } } + // Tiled circles: kept for taps, nothing native. Those that left + // the tiles and the list are forgotten; those that left the tiles + // for native drawing were added above. + if (wasTiled.isNotEmpty()) { + val nativeIds = native.mapTo(HashSet()) { it.id } + for (id in wasTiled) { + if (id !in tiled && id !in nativeIds) circleManager.removeEntity(id) + } + } + if (tiled.isNotEmpty() && !sharedTiles) { + val tiledStates = tiler!!.tiledStates() + withContext(Dispatchers.Default) { + for (state in tiledStates) { + circleManager.registerEntity(CircleEntity(circle = inTiles(), state = state)) + } + } + } + renderer.onPostProcess() } } + /** What a tiled circle's entity holds instead of a native circle. */ + private fun unchanged(state: CircleState, previous: CircleEntityInterface): Boolean = + (previous as? CircleEntity)?.let { it.changeMask(state) == 0 } + ?: (state.fingerPrint() == previous.fingerPrint) + + @Suppress("UNCHECKED_CAST") + private fun inTiles(): ActualCircle = null as ActualCircle + override suspend fun update(state: CircleState) { semaphore.withPermit { val prevEntity = circleManager.getEntity(state.id) ?: return - val currentFinger = state.fingerPrint() - val prevFinger = prevEntity.fingerPrint - if (currentFinger == prevFinger) { + if (state.id in tiledIds) { + if (CircleTileSet.canTile(state)) { + circleManager.registerEntity(CircleEntity(circle = prevEntity.circle, state = state)) + tiler?.update(state) + return + } + // No longer drawable in a tile (no radius, or over a pole or the + // antimeridian): the map SDK draws it from now on. Still on the + // map, so this is not an add. Whether the rest stay in tiles is + // left to the next add(), which decides tiling for the whole list. + tiledIds = tiledIds - state.id + tiler?.remove(state.id) + val circles = + renderer.onAdd( + listOf( + object : CircleOverlayRendererInterface.AddParamsInterface { + override val state: CircleState = state + }, + ), + ) + val circle = circles.firstOrNull() + if (circle != null) { + circleManager.registerEntity(CircleEntity(circle = circle, state = state)) + } else { + circleManager.removeEntity(state.id) + } + renderer.onPostProcess() + return + } + if (unchanged(state, prevEntity)) { return } @@ -149,7 +227,11 @@ abstract class CircleController( override suspend fun clear() { semaphore.withPermit { - val entities: List> = circleManager.allEntities() + val tiled = tiledIds + tiledIds = emptySet() + tiler?.clear() + val entities: List> = + circleManager.nativeEntities().filter { it.state.id !in tiled } renderer.onRemove(entities) // manager を空にしてから onPostProcess を呼ぶ。GL 系の描画担当は remove では何もせず、 // onPostProcess で manager の全部を描き直すので、逆の順だと clear() 後も地図に残る。 @@ -158,9 +240,22 @@ abstract class CircleController( } } - override fun find(position: GeoPointInterface): CircleEntityInterface? = circleManager.find(position) + /** + * The circle a tap at [position] is on: within its radius, or within half + * its stroke past the edge at the camera's zoom. The same whether the + * circle is drawn natively or in tiles. + */ + override fun find(position: GeoPointInterface): CircleEntityInterface? = + circleManager.find(position, currentCameraPosition) + + override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { + currentCameraPosition = mapCameraPosition + } override fun destroy() { + // The tile server outlives the map; without this its route keeps every + // tiled circle (and the renderer's copies of them) alive. + tiler?.dispose() // A destroyed controller can still be referenced (by its map controller, // or a state that has not let go yet); without this it keeps every entity. circleManager.clear() diff --git a/src/main/java/com/mapconductor/core/circle/CircleEntity.kt b/src/main/java/com/mapconductor/core/circle/CircleEntity.kt index a940208..0bbb32e 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleEntity.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleEntity.kt @@ -10,5 +10,13 @@ class CircleEntity( override var circle: ActualCircle, override val state: CircleState, ) : CircleEntityInterface { - override val fingerPrint: CircleFingerPrint = state.fingerPrint() + private val applied = state.captureValues() + + // Legacy provider API: create a fingerprint only when a native renderer + // requests it. No fingerprint object is retained per circle. + override val fingerPrint: CircleFingerPrint get() = state.snapshotFingerPrint(applied) + + internal fun changeMask(next: CircleState): Int { + return next.changeMaskSince(applied, next === state) + } } diff --git a/src/main/java/com/mapconductor/core/circle/CircleManager.kt b/src/main/java/com/mapconductor/core/circle/CircleManager.kt index 531b08f..5e742e0 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleManager.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleManager.kt @@ -1,9 +1,11 @@ package com.mapconductor.core.circle -import com.mapconductor.core.calculateZIndex import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.spherical.Spherical +import com.mapconductor.core.spherical.calculateMetersPerPixel import java.util.concurrent.ConcurrentHashMap +import kotlin.math.abs interface CircleManagerInterface { fun registerEntity(entity: CircleEntityInterface) @@ -16,60 +18,120 @@ interface CircleManagerInterface { fun allEntities(): List> + fun nativeEntities(): List> = allEntities().filter { it.circle != null } + + fun setTiledSource(source: CircleTiler?): Boolean = false + fun clear() fun find(position: GeoPointInterface): CircleEntityInterface? + + /** + * The circle a tap at [position] is on, with [cameraPosition]'s zoom to + * measure half the stroke past the edge. Without a camera, or for a + * manager that does not measure the stroke, the same as [find]. + */ + fun find( + position: GeoPointInterface, + cameraPosition: MapCameraPosition?, + ): CircleEntityInterface? = find(position) } class CircleManager : CircleManagerInterface { private val entities: ConcurrentHashMap> = ConcurrentHashMap() + @Volatile private var tiledSource: CircleTiler? = null + + override fun setTiledSource(source: CircleTiler?): Boolean { + tiledSource = source + return true + } + + @Suppress("UNCHECKED_CAST") + private fun tiledEntity(state: CircleState): CircleEntityInterface = CircleEntity(null as ActualCircle, state) - override fun getEntity(id: String): CircleEntityInterface? = entities.get(id) + override fun getEntity(id: String): CircleEntityInterface? = entities[id] ?: tiledSource?.state(id)?.let(::tiledEntity) - override fun hasEntity(id: String): Boolean = entities.containsKey(id) + override fun hasEntity(id: String): Boolean = entities.containsKey(id) || tiledSource?.isTiled(id) == true override fun removeEntity(id: String): CircleEntityInterface? { val removed = entities.remove(id) - return removed + if (removed != null) return removed + val source = tiledSource ?: return null + val state = source.state(id) ?: return null + source.remove(id) + return tiledEntity(state) } override fun registerEntity(entity: CircleEntityInterface) { + if (entity.circle == null && tiledSource?.isTiled(entity.state.id) == true) { + entities.remove(entity.state.id) + return + } entities[entity.state.id] = entity } fun updateEntity(entity: CircleEntityInterface) { - entities[entity.state.id] = entity + registerEntity(entity) } // ArrayList(values) avoids the size==1 race in Kotlin's toList() on concurrent maps. - override fun allEntities(): List> = ArrayList(entities.values) + override fun nativeEntities(): List> = ArrayList(entities.values) + + override fun allEntities(): List> = nativeEntities().toMutableList().also { result -> + tiledSource?.visitStates { state -> if (!entities.containsKey(state.id)) result.add(tiledEntity(state)) } + } override fun clear() { entities.clear() + tiledSource = null } - override fun find(position: GeoPointInterface): CircleEntityInterface? { - val filtered = - allEntities().filter { entity -> - val centerPos = entity.state.center - val distance = Spherical.computeDistanceBetween(centerPos, position) - return@filter (distance <= entity.state.radiusMeters) && entity.state.clickable - } - - if (filtered.isEmpty()) { - return null - } - - var maxZIndex = Int.MIN_VALUE - var maxEntity = filtered[0] - - filtered.forEach { - val zIndex = it.state.zIndex ?: calculateZIndex(it.state.center) - if (maxZIndex < zIndex) { - maxZIndex = zIndex - maxEntity = it + override fun find(position: GeoPointInterface): CircleEntityInterface? = find(position, null) + + /** + * The circle a tap at [position] is on (the same on all three platforms, + * and whether the circle is drawn natively or in tiles): + * + * - on it when the tap is within its radius plus half its stroke past the + * edge, the stroke measured on screen at [cameraPosition]'s zoom (no + * camera: the radius alone). The finger's size is not added: a circle is + * an area, as a polygon is, and among a street of small trees the finger + * would pick up the neighbours. + * - clickable = false circles let the tap through. + * - of several, the one on top: the highest zIndex (an unset one is the + * automatic one from the centre), then the nearest centre. + */ + override fun find( + position: GeoPointInterface, + cameraPosition: MapCameraPosition?, + ): CircleEntityInterface? { + val metersPerPixel = cameraPosition?.let { calculateMetersPerPixel(position.latitude, it.zoom) } ?: 0.0 + // Meters per degree of latitude, rounded down: the latitude check may only ever let more through. + val metersPerDegree = 110_000.0 + var best: CircleEntityInterface? = null + var bestState: CircleState? = null + var bestZ = Int.MIN_VALUE + var bestDistance = Double.POSITIVE_INFINITY + fun consider(state: CircleState, entity: CircleEntityInterface?) { + if (!state.clickable) return + val reach = state.radiusMeters + metersPerPixel * state.strokeWidth.value / 2.0 + if (!(reach >= 0.0)) return + // A degree of latitude is never under metersPerDegree: one further + // north or south than the reach cannot be on it. Skips the distance + // for nearly every circle of a city. + if (abs(state.center.latitude - position.latitude) > reach / metersPerDegree) return + val distance = Spherical.computeDistanceBetween(state.center, position) + if (distance > reach) return + val z = effectiveZIndex(state) + if (bestState == null || z > bestZ || (z == bestZ && distance < bestDistance)) { + best = entity + bestState = state + bestZ = z + bestDistance = distance } } - return maxEntity + for (entity in entities.values) consider(entity.state, entity) + tiledSource?.visitStates { state -> if (!entities.containsKey(state.id)) consider(state, null) } + return best ?: bestState?.let(::tiledEntity) } } diff --git a/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt b/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt index 53d736f..d76fb87 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt @@ -1,23 +1,36 @@ package com.mapconductor.core.circle import com.mapconductor.core.OverlayAddedTracker +import com.mapconductor.core.controller.BaseMapViewController import com.mapconductor.core.controller.MapViewControllerInterface import com.mapconductor.core.map.MapOverlayInterface import kotlinx.coroutines.flow.StateFlow -class CircleOverlay( - override val flow: StateFlow>, -) : MapOverlayInterface { - /** Calls [CircleState.onAdded] once the map has the state. See [OverlayAddedTracker]. */ - private val added = OverlayAddedTracker { it.onAdded } +class CircleOverlay + @JvmOverloads + constructor( + override val flow: StateFlow>, + /** + * This map's circle tiling, when the app sets one (null keeps the + * provider's [CircleTilingOptions.Default]). Applied to the map's + * [CircleTiler] before every hand-over, so a change takes effect the + * next time the circles are handed over. + */ + private val tilingOptions: StateFlow? = null, + ) : MapOverlayInterface { + /** Calls [CircleState.onAdded] once the map has the state. See [OverlayAddedTracker]. */ + private val added = OverlayAddedTracker { it.onAdded } - override suspend fun render( - data: MutableMap, - controller: MapViewControllerInterface, - ) { - val capable = controller as? CircleCapableInterface ?: return - val states = data.values.toList() - capable.compositionCircles(states) - added.synced(controller, states, capable::hasCircle) + override suspend fun render( + data: MutableMap, + controller: MapViewControllerInterface, + ) { + val capable = controller as? CircleCapableInterface ?: return + tilingOptions?.value?.let { options -> + (controller as? BaseMapViewController)?.circleTilers()?.forEach { it.options = options } + } + val states = data.values.toList() + capable.compositionCircles(states) + added.synced(controller, states, capable::hasCircle, sourceIds = data.keys) + } } -} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTileFileStorage.kt b/src/main/java/com/mapconductor/core/circle/CircleTileFileStorage.kt new file mode 100644 index 0000000..4744a43 --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTileFileStorage.kt @@ -0,0 +1,306 @@ +package com.mapconductor.core.circle + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.shapetile.ShapeTileStorage +import java.io.EOFException +import java.io.File +import java.io.RandomAccessFile +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.max + +/** + * Packed immutable circle geometry, read through a bounded block cache. + * No nationwide TileCircle or bounding-box object arrays are retained. + * Small updates share the file; a bounded override map is compacted when full. + */ +@InternalMapConductorApi +internal class CircleTileFileStorage private constructor( + private val file: SharedFile, + override val size: Int, + override val maxStroke: Float, + private val overrides: Map = emptyMap(), +) : ShapeTileStorage() { + init { + file.retain() + } + + internal val cacheFile: File get() = file.path + internal val cachedBytes: Int get() = file.cachedBytes + internal val allocatedReadBuffers: Int get() = file.allocatedReadBuffers + + override fun get(index: Int): TileCircle? = + when { + index !in 0 until size -> null + overrides.isNotEmpty() && overrides.containsKey(index) -> overrides[index] + else -> file.read(index) { bytes, offset -> decode(bytes, offset) } + } + + override fun bbox(index: Int): DoubleArray? = + when { + index !in 0 until size -> null + overrides.isNotEmpty() && overrides.containsKey(index) -> overrides[index]?.bbox + else -> + file.read(index) { bytes, p -> + if (bytes.getInt(p + 76) and 1 == 0) { + null + } else { + val x = bytes.getDouble(p + 24) + val half = bytes.getDouble(p + 40) + doubleArrayOf(x - half, bytes.getDouble(p + 48), x + half, bytes.getDouble(p + 56)) + } + } + } + + override fun updated(updates: List>): ShapeTileStorage { + var widest = maxStroke + for ((index, item) in updates) { + if (index in 0 until size && item != null) { + widest = max(widest, CircleTilePainter.strokeWidth(item)) + } + } + val changed = HashMap(overrides) + var compact = false + for ((index, item) in updates) if (index in 0 until size) { + if (index !in changed && changed.size == MAX_OVERRIDES) { + compact = true + break + } + changed[index] = item + } + if (!compact) return CircleTileFileStorage(file, size, widest, changed) + // Compact by streaming, never by materialising every decoded circle. + val next = create(file.path.parentFile!!, size, { get(it) }) + try { + next.file.patch(updates, size) + val result = CircleTileFileStorage(next.file, size, widest) + next.release() + return result + } catch (error: Throwable) { + next.release() + throw error + } + } + + override fun close() = file.release() + + @InternalMapConductorApi + private class SharedFile( + val path: File, + ) { + private val handle = RandomAccessFile(path, "rw") + private val channel = handle.channel + private var references = 0 + private val blocks = LinkedHashMap(MAX_BLOCKS, 0.75f, true) + var allocatedReadBuffers = 0 + private set + val cachedBytes: Int get() = synchronized(this) { blocks.values.sumOf { it.capacity() } } + + @Synchronized fun retain() { + references++ + } + + @Synchronized fun release() { + check(--references >= 0) + if (references == 0) dispose() + } + + @Synchronized fun dispose() { + try { + handle.close() + } finally { + blocks.clear() + synchronized(liveFiles) { + liveFiles.remove(path.absolutePath) + path.delete() + } + } + } + + @Synchronized fun read( + index: Int, + action: (ByteBuffer, Int) -> R, + ): R { + val block = index / RECORDS_PER_BLOCK + val bytes = + blocks[block] ?: run { + val buffer = if (blocks.size < MAX_BLOCKS) { + allocatedReadBuffers++ + ByteBuffer.allocate(BLOCK_BYTES).order(ByteOrder.LITTLE_ENDIAN) + } else { + // Reuse the eldest block's bytes. Allocating another + // 40 KiB array at every miss churns Android's large-object heap. + val iterator = blocks.entries.iterator() + val reusable = iterator.next().value + iterator.remove() + reusable.clear() + reusable + } + val start = HEADER_BYTES + block.toLong() * BLOCK_BYTES + val count = minOf(BLOCK_BYTES.toLong(), channel.size() - start).toInt() + if (count < RECORD_BYTES) throw EOFException("Truncated circle cache") + buffer.limit(count) + var at = start + while (buffer.hasRemaining()) { + val n = channel.read(buffer, at) + if (n <= 0) throw EOFException("Truncated circle cache") + at += n + } + buffer.flip() + blocks[block] = buffer + buffer + } + return action(bytes, index % RECORDS_PER_BLOCK * RECORD_BYTES) + } + + fun write( + size: Int, + itemAt: (Int) -> TileCircle?, + checkCancelled: () -> Unit, + ): Float { + val header = + ByteBuffer + .allocate(HEADER_BYTES) + .order(ByteOrder.LITTLE_ENDIAN) + .putInt(MAGIC) + .putInt(1) + .putInt(size) + .putInt(RECORD_BYTES) + header.flip() + while (header.hasRemaining()) channel.write(header) + val bytes = ByteBuffer.allocate(BLOCK_BYTES).order(ByteOrder.LITTLE_ENDIAN) + var widest = 0f + for (index in 0 until size) { + if (index % 4096 == 0) checkCancelled() + val item = itemAt(index) + encode(bytes, bytes.position(), item) + bytes.position(bytes.position() + RECORD_BYTES) + if (item != null) widest = max(widest, CircleTilePainter.strokeWidth(item)) + if (!bytes.hasRemaining()) { + bytes.flip() + while (bytes.hasRemaining()) channel.write(bytes) + bytes.clear() + } + } + bytes.flip() + while (bytes.hasRemaining()) channel.write(bytes) + return widest + } + + @Synchronized fun patch( + updates: List>, + size: Int, + ) { + check(references == 1) // Only an unpublished freshly compacted file may be written. + val bytes = ByteBuffer.allocate(RECORD_BYTES).order(ByteOrder.LITTLE_ENDIAN) + for ((index, item) in updates) { + if (index in 0 until size) { + bytes.clear() + encode(bytes, 0, item) + var at = HEADER_BYTES + index.toLong() * RECORD_BYTES + while (bytes.hasRemaining()) { + val n = channel.write(bytes, at) + check(n > 0) + at += n + } + } + } + blocks.clear() + } + } + + @InternalMapConductorApi + companion object { + private const val MAGIC = 0x5243434d // MCCR, little endian + private const val HEADER_BYTES = 16 + private const val RECORD_BYTES = 80 + private const val RECORDS_PER_BLOCK = 512 + private const val BLOCK_BYTES = RECORD_BYTES * RECORDS_PER_BLOCK + internal const val MAX_BLOCKS = 48 // At most 1.875 MiB per open geometry file. + private const val MAX_OVERRIDES = 2048 + private val liveFiles = HashSet() + + fun create( + directory: File, + size: Int, + itemAt: (Int) -> TileCircle?, + checkCancelled: () -> Unit = { + }, + ): CircleTileFileStorage { + require(size >= 0) + val path = + synchronized(liveFiles) { + check(directory.isDirectory || directory.mkdirs()) { "Cannot create circle cache directory" } + // These are disposable private cache files, not user data. Open + // files from this process stay registered until their last reader exits. + directory + .listFiles() + ?.filter { + it.name.startsWith("circle-geometry-") && + it.name.endsWith(".bin") && + it.absolutePath !in liveFiles + }?.forEach { it.delete() } + File.createTempFile("circle-geometry-", ".bin", directory).also { liveFiles.add(it.absolutePath) } + } + var file: SharedFile? = null + try { + file = SharedFile(path) + val widest = file.write(size, itemAt, checkCancelled) + return CircleTileFileStorage(file, size, widest) + } catch (error: Throwable) { + if (file != + null + ) { + file.dispose() + } else { + synchronized(liveFiles) { + liveFiles.remove(path.absolutePath) + path.delete() + } + } + throw error + } + } + + private fun encode( + bytes: ByteBuffer, + p: Int, + item: TileCircle?, + ) { + if (item == null) { + bytes.putInt(p + 76, 0) + return + } + bytes + .putDouble(p, item.latitude) + .putDouble(p + 8, item.longitude) + .putDouble(p + 16, item.radiusMeters) + .putDouble(p + 24, item.x) + .putDouble(p + 32, item.y) + .putDouble(p + 40, item.halfWidth) + .putDouble(p + 48, item.northY) + .putDouble(p + 56, item.southY) + .putInt(p + 64, item.fill) + .putInt(p + 68, item.stroke) + .putFloat(p + 72, item.strokeWidth) + .putInt(p + 76, if (item.geodesic) 3 else 1) + } + + private fun decode( + bytes: ByteBuffer, + p: Int, + ): TileCircle? { + val flags = bytes.getInt(p + 76) + if (flags and 1 == 0) return null + val x = bytes.getDouble(p + 24) + val half = bytes.getDouble(p + 40) + val north = bytes.getDouble(p + 48) + val south = bytes.getDouble(p + 56) + return TileCircle( + bytes.getDouble(p), bytes.getDouble(p + 8), bytes.getDouble(p + 16), flags and 2 != 0, + x, bytes.getDouble(p + 32), half, north, south, doubleArrayOf(x - half, north, x + half, south), + bytes.getInt(p + 64), bytes.getInt(p + 68), bytes.getFloat(p + 72), + ) + } + } +} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTileGeometry.kt b/src/main/java/com/mapconductor/core/circle/CircleTileGeometry.kt new file mode 100644 index 0000000..4769904 --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTileGeometry.kt @@ -0,0 +1,323 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.toArgb +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.calculateZIndex +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.geometry.DEFAULT_CIRCLE_SEGMENTS +import com.mapconductor.core.geometry.circleToRing +import com.mapconductor.core.normalizeLng +import com.mapconductor.core.polygon.MIN_OUTLINED_PX +import com.mapconductor.core.polygon.isVisibleColor +import com.mapconductor.core.polygon.simplifyRing +import com.mapconductor.core.polygon.toMercatorRing +import com.mapconductor.core.projection.Earth +import com.mapconductor.core.shapetile.ShapeTileRenderer +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.asin +import kotlin.math.cos +import kotlin.math.floor +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sin +import android.graphics.Canvas +import android.graphics.Path + +// The geometry of circle tiles: the same steps as the circle part of the +// "Shape tiles" section of js-sdk-core's tile-sw.js and ios-sdk-core's +// CircleTileGeometry, so the three platforms draw the same pixels from the +// same circles. +// +// A circle's radius is a distance on the ground, so unlike a line's width it +// grows on screen with the zoom: twice as many pixels at z+1. Its stroke is a +// width on screen, as the map SDKs draw it, the same at every zoom. +// +// Its box comes from the same formulas as the native 128-gon (circleToRing): +// the spherical circle for geodesic, the local plane round the centre's +// latitude otherwise. At each zoom it is one of three shapes: +// - Dot: under a pixel across, one whole pixel, as a polygon under a pixel is. +// - Arc: a true circle, when Mercator's stretch (the north half taller than +// the south) is a quarter of a pixel or less -- every city tree at every zoom. +// - Ring: otherwise (kilometres across, or far north) the native 128-gon in +// world pixels, snapped and simplified as a polygon's outline is. +// Taps never see any of this -- they are resolved against the original circle +// in CircleManager. + +private const val MAX_LATITUDE = 85.05112878 + +/** Under this radius on screen (in pixels) a circle is a single pixel. */ +private const val CIRCLE_DOT_RADIUS_PX = 0.5 + +/** Mercator's stretch (in pixels) up to which a circle is drawn as a true circle. */ +private const val CIRCLE_ARC_TOLERANCE_PX = 0.25 + +/** Web Mercator y in [0, 1] of [latitude], clamped as the shape tiles clamp it. */ +private fun mercatorY(latitude: Double): Double { + val lat = latitude.coerceIn(-MAX_LATITUDE, MAX_LATITUDE) + val s = sin(lat * PI / 180.0) + return 0.5 - ln((1 + s) / (1 - s)) / (4 * PI) +} + +/** + * The latitude and longitude extent of a circle, in degrees: what the native + * 128-gon spans. [dLng] is the half-width east and west of the centre. + */ +@InternalMapConductorApi +internal class CircleExtent( + val north: Double, + val south: Double, + val dLng: Double, + /** Whether a geodesic circle reaches over a pole (then [dLng] means nothing). */ + val overPole: Boolean, +) + +@InternalMapConductorApi +internal fun circleExtent( + latitude: Double, + radiusMeters: Double, + geodesic: Boolean, +): CircleExtent { + val phi = latitude * PI / 180.0 + if (geodesic) { + // Spherical.computeOffset: the angular distance on a sphere of Earth.RADIUS_METERS. + val delta = radiusMeters / Earth.RADIUS_METERS + val deltaDeg = delta * 180.0 / PI + val overPole = sin(delta) >= cos(phi) + val dLng = if (overPole) 180.0 else asin(min(1.0, sin(delta) / cos(phi))) * 180.0 / PI + return CircleExtent(latitude + deltaDeg, latitude - deltaDeg, dLng, overPole) + } + // circleToRing's local plane round the centre's latitude. + val metersPerDegree = Earth.CIRCUMFERENCE_METERS / 360.0 + val dLat = radiusMeters / metersPerDegree + val dLng = radiusMeters / (metersPerDegree * max(cos(phi), 1e-6)) + return CircleExtent(latitude + dLat, latitude - dLat, dLng, false) +} + +/** + * One circle as the tiles draw it. + * + * [x], [y] is the centre in Web Mercator [0, 1]; [halfWidth] the east-west + * radius and [northY], [southY] the top and bottom, all in the same units. + * [strokeWidth] is in dp, the unit of [CircleState.strokeWidth], which is also + * the tile unit. + */ +@InternalMapConductorApi +internal class TileCircle( + val latitude: Double, + val longitude: Double, + val radiusMeters: Double, + val geodesic: Boolean, + val x: Double, + val y: Double, + val halfWidth: Double, + val northY: Double, + val southY: Double, + /** minX, minY, maxX, maxY. */ + val bbox: DoubleArray, + val fill: Int, + val stroke: Int, + val strokeWidth: Float, +) { + fun matches(state: CircleState): Boolean = + latitude == state.center.latitude && longitude == normalizeLng(state.center.longitude) && + radiusMeters == state.radiusMeters && geodesic == state.geodesic && + fill == state.fillColor.toArgb() && stroke == state.strokeColor.toArgb() && + strokeWidth == state.strokeWidth.value + + // The spherical 128-gon is independent of zoom. Keep it once per immutable + // circle rather than repeating trig and projection at every new zoom. + val mercatorRing: DoubleArray + get() = synchronized(ringCache) { + ringCache[this] ?: toMercatorRing(circleToRing(GeoPoint.fromLatLong(latitude, longitude), radiusMeters, geodesic, DEFAULT_CIRCLE_SEGMENTS)).also { + ringCache[this] = it + } + } + + val fillVisible: Boolean get() = isVisibleColor(fill) + val strokeVisible: Boolean get() = strokeWidth > 0f && isVisibleColor(stroke) + + @InternalMapConductorApi + companion object { + // Nationwide circles must not retain a 128-vertex ring per station. + private val ringCache = object : LinkedHashMap(4096, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): Boolean = size > 4096 + } + /** Null when the circle cannot be drawn in a tile (see [CircleTileSet.canTile]). */ + fun from(state: CircleState): TileCircle? { + if (!CircleTileSet.canTile(state)) return null + val lat = state.center.latitude + val lng = normalizeLng(state.center.longitude) + val extent = circleExtent(lat, state.radiusMeters, state.geodesic) + val x = (lng + 180.0) / 360.0 + val y = mercatorY(lat) + val halfWidth = extent.dLng / 360.0 + val northY = mercatorY(extent.north) + val southY = mercatorY(extent.south) + return TileCircle( + latitude = lat, + longitude = lng, + radiusMeters = state.radiusMeters, + geodesic = state.geodesic, + x = x, + y = y, + halfWidth = halfWidth, + northY = northY, + southY = southY, + bbox = doubleArrayOf(x - halfWidth, northY, x + halfWidth, southY), + fill = state.fillColor.toArgb(), + stroke = state.strokeColor.toArgb(), + strokeWidth = state.strokeWidth.value, + ) + } + } +} + +/** What one circle looks like at one zoom, in world pixels. */ +@InternalMapConductorApi +internal sealed class CircleTileShape { + /** Under a pixel across: the pixel at [x], [y] (its top-left corner). */ + @InternalMapConductorApi + class Dot( + val x: Double, + val y: Double, + ) : CircleTileShape() + + /** A true circle round [cx], [cy]. */ + @InternalMapConductorApi + class Arc( + val cx: Double, + val cy: Double, + val radius: Double, + val outlined: Boolean, + ) : CircleTileShape() + + /** The native 128-gon, snapped and simplified, `[x0, y0, ...]`. */ + @InternalMapConductorApi + class Ring( + val points: DoubleArray, + val outlined: Boolean, + ) : CircleTileShape() +} + +/** The circle as drawn at a zoom whose world is [scale] pixels wide; never nothing. */ +@InternalMapConductorApi +internal fun simplifyCircle( + c: TileCircle, + scale: Double, +): CircleTileShape { + val cx = c.x * scale + val cy = c.y * scale + val rx = c.halfWidth * scale + val ryN = (c.y - c.northY) * scale + val ryS = (c.southY - c.y) * scale + val maxR = max(rx, max(ryN, ryS)) + if (maxR < CIRCLE_DOT_RADIUS_PX) return CircleTileShape.Dot(floor(cx), floor(cy)) + val outlined = 2 * maxR >= MIN_OUTLINED_PX + if (max(abs(ryN - rx), abs(ryS - rx)) <= CIRCLE_ARC_TOLERANCE_PX) { + return CircleTileShape.Arc(cx, cy, rx, outlined) + } + val simplified = simplifyRing(c.mercatorRing, scale) ?: return CircleTileShape.Arc(cx, cy, rx, outlined) + return CircleTileShape.Ring(simplified, outlined) +} + +/** The order circles are drawn in, as the native renderers stack them: an unset zIndex is the automatic one. */ +@InternalMapConductorApi +internal fun effectiveZIndex(state: CircleState): Int = state.zIndex ?: calculateZIndex(state.center) + +/** + * How a circle is drawn in a shape tile: filled, then outlined with the stroke + * centred on the edge (half of it outside), as the map SDKs draw it. A circle + * under [MIN_OUTLINED_PX] across has no outline; one under a pixel is a pixel. + */ +@InternalMapConductorApi +internal object CircleTilePainter : ShapeTileRenderer.Painter { + override val cacheSimplifiedShapes: Boolean get() = false + override val thinSubpixelOverlaps: Boolean get() = true + override fun isVisible(item: TileCircle): Boolean = item.fillVisible || item.strokeVisible + override fun subpixelSlot(item: TileCircle, scale: Double, originX: Double, originY: Double, tileSize: Int): Int { + val radius = max(item.halfWidth, max(item.y - item.northY, item.southY - item.y)) * scale + if (radius >= CIRCLE_DOT_RADIUS_PX) return -2 + val x = floor(item.x * scale) - originX + val y = floor(item.y * scale) - originY + return if (x >= 0 && x < tileSize && y >= 0 && y < tileSize) y.toInt() * tileSize + x.toInt() else -1 + } + + override fun bbox(item: TileCircle): DoubleArray = item.bbox + + override fun strokeWidth(item: TileCircle): Float = if (item.strokeVisible) item.strokeWidth else 0f + + override fun simplify( + item: TileCircle, + scale: Double, + ): Any = simplifyCircle(item, scale) + + override fun draw( + canvas: Canvas, + item: TileCircle, + shape: Any, + originX: Double, + originY: Double, + r: Float, + paints: ShapeTileRenderer.Paints, + ): Boolean { + val fillVisible = item.fillVisible + val strokeVisible = item.strokeVisible + if (!fillVisible && !strokeVisible) return false + when (shape) { + is CircleTileShape.Dot -> { + paints.dot.color = if (fillVisible) item.fill else item.stroke + val left = ((shape.x - originX) * r).toFloat() + val top = ((shape.y - originY) * r).toFloat() + canvas.drawRect(left, top, left + r, top + r, paints.dot) + return true + } + is CircleTileShape.Arc -> { + val cx = ((shape.cx - originX) * r).toFloat() + val cy = ((shape.cy - originY) * r).toFloat() + val radius = (shape.radius * r).toFloat() + var drew = false + if (fillVisible) { + paints.fill.color = item.fill + canvas.drawCircle(cx, cy, radius, paints.fill) + drew = true + } + if (strokeVisible && shape.outlined) { + paints.stroke.color = item.stroke + paints.stroke.strokeWidth = item.strokeWidth * r + canvas.drawCircle(cx, cy, radius, paints.stroke) + drew = true + } + return drew + } + is CircleTileShape.Ring -> { + val path = paints.path + path.rewind() + path.fillType = Path.FillType.WINDING + val p = shape.points + path.moveTo(((p[0] - originX) * r).toFloat(), ((p[1] - originY) * r).toFloat()) + var i = 2 + while (i < p.size) { + path.lineTo(((p[i] - originX) * r).toFloat(), ((p[i + 1] - originY) * r).toFloat()) + i += 2 + } + path.close() + var drew = false + if (fillVisible) { + paints.fill.color = item.fill + canvas.drawPath(path, paints.fill) + drew = true + } + if (strokeVisible && shape.outlined) { + paints.stroke.color = item.stroke + paints.stroke.strokeWidth = item.strokeWidth * r + canvas.drawPath(path, paints.stroke) + drew = true + } + return drew + } + else -> return false + } + } +} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTileSet.kt b/src/main/java/com/mapconductor/core/circle/CircleTileSet.kt new file mode 100644 index 0000000..13f3bcb --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTileSet.kt @@ -0,0 +1,121 @@ +package com.mapconductor.core.circle + +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.normalizeLng +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.shapetile.ShapeTileSet +import com.mapconductor.core.tileserver.LocalTileServer +import com.mapconductor.core.tileserver.TileServerRegistry +import java.io.File +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive + +/** + * The circles of one map that are drawn as raster tiles, and their route on + * the local tile server. + * + * Provider-independent: a provider decides which circles to tile + * ([CircleTilingOptions.shouldUseTiles], [canTile]), hands them to + * [setCircles], and shows the returned URL template as a raster layer. + * In-place changes go through [update]; each one ends in a new template (the + * version in it is what makes the map ask again), reported to + * [onTemplateChanged]. Tiles the change did not touch are still cached by the + * renderer and come back without being drawn again. + * + * The same as [com.mapconductor.core.polyline.PolylineTileSet] for circles: + * both are [ShapeTileSet]s, with their own route, version and tile cache. + * Same shape as js-sdk-core's and ios-sdk-core's `CircleTileSet`. + */ +class CircleTileSet( + server: LocalTileServer = TileServerRegistry.get(), + scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default), +) { + internal val renderer: ShapeTileRenderer = + ShapeTileRenderer(tileSize = TILE_SIZE, painter = CircleTilePainter) + + internal val shapes: ShapeTileSet = + ShapeTileSet( + routePrefix = "circles", + server = server, + scope = scope, + renderer = renderer, + idOf = { it.id }, + // The native renderers stack an unset zIndex by the automatic one; so do the tiles. + zIndexOf = ::effectiveZIndex, + toTile = TileCircle::from, + canReuse = { state, tile -> tile.matches(state) }, + createStorage = { states -> + if (states.size <= 2000) { + null + } else { + val context = currentCoroutineContext() + val root = + runCatching { ResourceProvider.getAppContext().cacheDir } + .getOrElse { File(System.getProperty("java.io.tmpdir")) } + CircleTileFileStorage.create( + File(root, "mapconductor-circle-geometry"), states.size, + { TileCircle.from(states[it]) }, { context.ensureActive() }, + ) + } + }, + ) + + val routeId: String get() = shapes.routeId + + /** Called with the new template after an [update] or [remove]. */ + var onTemplateChanged: (suspend (String) -> Unit)? + get() = shapes.onTemplateChanged + set(value) { + shapes.onTemplateChanged = value + } + + val tileSize: Int get() = TILE_SIZE + + /** + * Registers [states] (replacing whatever was registered) and returns the + * URL template of their tiles. Draw order is the effective zIndex (an + * unset one is the automatic one from the centre), then the order given. + */ + suspend fun setCircles(states: List): String = shapes.setShapes(states) + + fun has(id: String): Boolean = shapes.has(id) + + /** + * One circle changed in place. A change of zIndex reorders the list and + * needs [setCircles] instead; everything else is applied here. + */ + fun update(state: CircleState) = shapes.update(state) + + /** Takes one circle out of the tiles. Only the tiles it was in are drawn again. */ + fun remove(id: String) = shapes.remove(id) + + fun template(): String = shapes.template() + + fun dispose() = shapes.dispose() + + companion object { + private const val TILE_SIZE = 256 + private const val MAX_LATITUDE = 85.05112878 + + /** + * Whether a circle can be drawn in a tile. One with no radius, or one + * that reaches a pole, the edge of the Mercator world or the + * antimeridian, is drawn by the map SDK. Geodesic or not, the rest can. + */ + fun canTile(state: CircleState): Boolean { + val radius = state.radiusMeters + if (!(radius > 0.0) || !radius.isFinite()) return false + val lat = state.center.latitude + val lngRaw = state.center.longitude + if (!lat.isFinite() || !lngRaw.isFinite()) return false + val extent = circleExtent(lat, radius, state.geodesic) + if (extent.overPole) return false + if (extent.north >= MAX_LATITUDE || extent.south <= -MAX_LATITUDE) return false + val lng = normalizeLng(lngRaw) + return lng - extent.dLng > -180.0 && lng + extent.dLng < 180.0 + } + } +} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTiler.kt b/src/main/java/com/mapconductor/core/circle/CircleTiler.kt new file mode 100644 index 0000000..a2707a4 --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTiler.kt @@ -0,0 +1,95 @@ +package com.mapconductor.core.circle + +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.shapetile.ShapeTiler + +/** The id of the raster layer that shows tiled circles. */ +const val CIRCLE_TILE_LAYER_ID: String = "mc-circle-tiles" + +/** The raster layer state for tiled circles at [template]. */ +fun circleTileRasterLayerState( + template: String, + tileSize: Int = 256, +): RasterLayerState = + RasterLayerState( + id = CIRCLE_TILE_LAYER_ID, + source = RasterLayerSource.UrlTemplate(template = template, tileSize = tileSize), + ) + +/** + * Decides which of a map's circles are drawn as tiles, keeps them registered + * with the local tile server, and tells the provider where the tiles are. + * Used exactly as [com.mapconductor.core.polyline.PolylineTiler]: + * + * 1. [route] with the full list on every composition. It returns the ids now + * in tiles; the controller keeps those in its [CircleManager] (taps are + * resolved there, against the original circles) but gives the map SDK + * nothing for them, and removes any native circle it had drawn for one. + * 2. [update] for an in-place change of a tiled circle, or [remove] when the + * change means it can no longer be tiled (it moved onto the antimeridian, + * say). + * 3. [onTemplate] is how the tiles reach the map: a URL template to show as a + * raster layer, or null to remove it. A provider with a RasterLayer + * controller hands [circleTileRasterLayerState] to its `upsert`, and + * removes it with `removeById(CIRCLE_TILE_LAYER_ID)`. The layer belongs to + * the circle band: over polygons (and their tiles), under native circles, + * polylines (and their tiles) and markers. + * + * [options] is read at every [route]: setting it decides again the next time + * the circles are handed over. + * + * Same as js-sdk-core's and ios-sdk-core's `CircleTiler`. + */ +class CircleTiler( + options: CircleTilingOptions = CircleTilingOptions.Default, +) { + @Volatile + var options: CircleTilingOptions = options + + var onTemplate: (suspend (template: String?, tileSize: Int) -> Unit)? = null + + private val tileSet = CircleTileSet() + + private val tiler = + ShapeTiler( + tileSet = tileSet.shapes, + canTile = CircleTileSet::canTile, + vertexCount = { 0 }, + shouldUseTiles = { count, _ -> this.options.shouldUseTiles(count) }, + idOf = { it.id }, + onTemplate = { template, tileSize -> onTemplate?.invoke(template, tileSize) }, + ) + + /** Re-decides tiling for [data] and returns the ids drawn as tiles. */ + suspend fun route(data: List): Set = tiler.route(data) + + /** The states drawn as tiles, as of the last [route]. */ + fun tiledStates(): List = tiler.tiledStates() + + fun isTiled(id: String): Boolean = tiler.isTiled(id) + + internal fun state(id: String): CircleState? = tileSet.shapes.source(id) + internal fun visitStates(action: (CircleState) -> Unit) = tileSet.shapes.visitSources(action) + + /** An in-place change of a tiled circle; only the tiles it touches are drawn again. */ + fun update(state: CircleState) = tiler.update(state) + + /** + * Takes one circle out of the tiles, for a change that left it no longer + * [CircleTileSet.canTile]; only the tiles it was in are drawn again. The + * controller then hands it to the map SDK. + */ + fun remove(id: String) = tiler.remove(id) + + /** + * Releases the tiles when the map goes away. Unlike [clear], it does not + * call [onTemplate]: there is no map left to remove the layer from. + */ + fun dispose() = tiler.dispose() + + suspend fun clear() = tiler.clear() + + /** The tile set, for tests that look at the pixels. */ + internal val tiles: CircleTileSet get() = tileSet +} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTilingOptions.kt b/src/main/java/com/mapconductor/core/circle/CircleTilingOptions.kt new file mode 100644 index 0000000..492fd95 --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTilingOptions.kt @@ -0,0 +1,28 @@ +package com.mapconductor.core.circle + +/** + * Options for circle tiling. + * + * When enabled and a map holds enough circles, they are drawn into raster + * tiles by the SDK's local tile server instead of being handed to the map SDK + * one by one. Taps are still resolved against the original circles in + * [CircleManager], so tiling changes how circles look, never what a tap hits. + * + * The counterpart of [com.mapconductor.core.polygon.PolygonTilingOptions] and + * [com.mapconductor.core.polyline.PolylineTilingOptions], and the same options + * as js-sdk-core's and ios-sdk-core's `CircleTilingOptions`. A circle has no + * vertices to count, so the threshold is the number of circles alone. + */ +data class CircleTilingOptions( + val enabled: Boolean = true, + /** Tile once a map holds at least this many circles. */ + val minCircleCount: Int = 2001, +) { + /** The one place the threshold is decided; callers must not restate it. */ + fun shouldUseTiles(circleCount: Int): Boolean = enabled && circleCount >= minCircleCount + + companion object { + val Default: CircleTilingOptions = CircleTilingOptions() + val Disabled: CircleTilingOptions = CircleTilingOptions(enabled = false) + } +} diff --git a/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt b/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt index aaa2a7c..2916cdd 100644 --- a/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt +++ b/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt @@ -4,7 +4,9 @@ import com.mapconductor.core.OnCameraMoveHandler import com.mapconductor.core.OnMapEventHandler import com.mapconductor.core.OnMapInitializedHandler import com.mapconductor.core.circle.CircleCapableInterface +import com.mapconductor.core.circle.CircleController import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.circle.CircleTiler import com.mapconductor.core.circle.OnCircleEventHandler import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface @@ -282,6 +284,10 @@ abstract class BaseMapViewController : .filterIsInstance>() .filter { it.kind == kind } + /** The tilers of this map's circle controllers, for [com.mapconductor.core.circle.CircleOverlay]'s per-map options. */ + internal fun circleTilers(): List = + overlayControllersOf(OverlayKind.Circle).mapNotNull { (it as? CircleController<*>)?.tiler } + /** The tilers of this map's polyline controllers, for [com.mapconductor.core.polyline.PolylineOverlay]'s per-map options. */ internal fun polylineTilers(): List = overlayControllersOf(OverlayKind.Polyline).mapNotNull { (it as? PolylineController<*>)?.tiler } diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonController.kt b/src/main/java/com/mapconductor/core/polygon/PolygonController.kt index b5d6c88..dc6edf8 100644 --- a/src/main/java/com/mapconductor/core/polygon/PolygonController.kt +++ b/src/main/java/com/mapconductor/core/polygon/PolygonController.kt @@ -43,12 +43,13 @@ abstract class PolygonController( tiledIds = tiled val native = if (tiled.isEmpty()) data else data.filter { it.id !in tiled } val modifiedEntities = mutableListOf>() - // Only natively drawn polygons are diffed against the renderer. + // Native handles remain authoritative after a cancelled transition: + // route() may already have switched the IDs to tiles before removal finishes. val previous = polygonManager .allEntities() - .map { it.state.id } - .filterTo(mutableSetOf()) { it !in wasTiled } + .filter { it.polygon != null } + .mapTo(mutableSetOf()) { it.state.id } val added = mutableListOf() val updated = mutableListOf>() val removed = mutableListOf>() @@ -162,8 +163,12 @@ abstract class PolygonController( val prevEntity = polygonManager.getEntity(state.id) ?: return if (state.id in tiledIds) { if (PolygonTileSet.canTile(state)) { + if (state.zIndex != prevEntity.fingerPrint.zIndex) { + tiler?.reorder(state) + } else { + tiler?.update(state) + } polygonManager.registerEntity(PolygonEntity(polygon = prevEntity.polygon, state = state)) - tiler?.update(state) return } // No longer drawable in a tile (geodesic, half the world wide, or @@ -223,11 +228,10 @@ abstract class PolygonController( override suspend fun clear() { semaphore.withPermit { - val tiled = tiledIds tiledIds = emptySet() tiler?.clear() val entities: List> = - polygonManager.allEntities().filter { it.state.id !in tiled } + polygonManager.allEntities().filter { it.polygon != null } renderer.onRemove(entities) // manager を空にしてから onPostProcess を呼ぶ。GL 系の描画担当は remove では何もせず、 // onPostProcess で manager の全部を描き直すので、逆の順だと clear() 後も地図に残る。 diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonTileGeometry.kt b/src/main/java/com/mapconductor/core/polygon/PolygonTileGeometry.kt index 8d1b826..c0290a1 100644 --- a/src/main/java/com/mapconductor/core/polygon/PolygonTileGeometry.kt +++ b/src/main/java/com/mapconductor/core/polygon/PolygonTileGeometry.kt @@ -145,7 +145,7 @@ internal class PolygonGridIndex( private val cells: HashMap, private val large: IntArray, ) { - private val grid = ShapeGridIndex(cells, large) + private var grid = ShapeGridIndex(cells, large) /** * The polygons whose bounding box meets the given box, each once, in @@ -162,7 +162,7 @@ internal class PolygonGridIndex( companion object { fun build(polygons: Array): PolygonGridIndex { val grid = ShapeGridIndex.build(polygons.size) { polygons[it]?.bbox } - return PolygonGridIndex(grid.cells, grid.large) + return PolygonGridIndex(grid.cells, grid.large).apply { this.grid = grid } } } } diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt b/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt index 4f6d185..ef060e8 100644 --- a/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt +++ b/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt @@ -63,6 +63,8 @@ class PolygonTiler( /** An in-place change of a tiled polygon; only the tiles it touches are drawn again. */ fun update(state: PolygonState) = tiler.update(state) + internal suspend fun reorder(state: PolygonState) = tiler.reorder(state) + /** * Takes one polygon out of the tiles, for a change that left it no longer * [PolygonTileSet.canTile]; only the tiles it was in are drawn again. The diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeGridIndex.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeGridIndex.kt index c015e46..6e1f328 100644 --- a/src/main/java/com/mapconductor/core/shapetile/ShapeGridIndex.kt +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeGridIndex.kt @@ -1,90 +1,171 @@ -package com.mapconductor.core.shapetile - -import com.mapconductor.core.InternalMapConductorApi -import com.mapconductor.core.polygon.IntList -import com.mapconductor.core.polygon.POLYGON_CELL -import com.mapconductor.core.polygon.POLYGON_MAX_CELLS -import kotlin.math.floor - -/** - * The index the shape tiles (polygons and polylines) draw from: shapes by the - * grid cells their bounding box covers. A cell is one z12 tile - * ([POLYGON_CELL]); a shape covering more than [POLYGON_MAX_CELLS] cells is kept - * in a list every query checks. - * - * A shape is its index in the renderer's list, and [bboxOf] gives its - * Web Mercator `minX, minY, maxX, maxY` (null for an empty slot). - */ -@InternalMapConductorApi -internal class ShapeGridIndex( - val cells: HashMap, - val large: IntArray, -) { - /** - * The shapes whose bounding box meets the given box, each once, in - * ascending index order -- which is draw order. - */ - inline fun query( - bboxOf: (Int) -> DoubleArray?, - minX: Double, - minY: Double, - maxX: Double, - maxY: Double, - ): IntArray { - val out = IntList() - for (i in large) { - val b = bboxOf(i) ?: continue - if (b[0] <= maxX && b[2] >= minX && b[1] <= maxY && b[3] >= minY) out.add(i) - } - val cx0 = floor(minX / POLYGON_CELL).toLong() - val cx1 = floor(maxX / POLYGON_CELL).toLong() - val cy0 = floor(minY / POLYGON_CELL).toLong() - val cy1 = floor(maxY / POLYGON_CELL).toLong() - for (cx in cx0..cx1) { - for (cy in cy0..cy1) { - val inCell = cells[cellKey(cx, cy)] ?: continue - for (i in inCell) { - val b = bboxOf(i) ?: continue - if (b[0] <= maxX && b[2] >= minX && b[1] <= maxY && b[3] >= minY) out.add(i) - } - } - } - // A shape in several cells was taken once per cell. - return out.toSortedDistinctArray() - } - - @InternalMapConductorApi - companion object { - inline fun build( - count: Int, - bboxOf: (Int) -> DoubleArray?, - ): ShapeGridIndex { - val cells = HashMap() - val large = IntList() - for (i in 0 until count) { - val b = bboxOf(i) ?: continue - val cx0 = floor(b[0] / POLYGON_CELL).toLong() - val cx1 = floor(b[2] / POLYGON_CELL).toLong() - val cy0 = floor(b[1] / POLYGON_CELL).toLong() - val cy1 = floor(b[3] / POLYGON_CELL).toLong() - if ((cx1 - cx0 + 1) * (cy1 - cy0 + 1) > POLYGON_MAX_CELLS) { - large.add(i) - continue - } - for (cx in cx0..cx1) { - for (cy in cy0..cy1) { - cells.getOrPut(cellKey(cx, cy)) { IntList() }.add(i) - } - } - } - val packed = HashMap(cells.size * 2) - for ((key, list) in cells) packed[key] = list.toArray() - return ShapeGridIndex(packed, large.toArray()) - } - - fun cellKey( - cx: Long, - cy: Long, - ): Long = cx * 1_048_576L + cy - } -} +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.polygon.IntList +import com.mapconductor.core.polygon.POLYGON_CELL +import com.mapconductor.core.polygon.POLYGON_MAX_CELLS +import java.util.BitSet +import kotlin.math.floor + +/** A multiresolution grid: wide shapes use coarser cells, not a global scan list. */ +@InternalMapConductorApi +internal class ShapeGridIndex private constructor( + val cells: HashMap, + /** Shapes that formerly needed a global scan; retained for diagnostics. */ + val large: IntArray, + private val levels: List, + private val count: Int, + private val legacyLarge: IntArray = IntArray(0), +) { + @InternalMapConductorApi + private class Level( + val size: Double, + val cells: HashMap, + val groups: HashMap>? = null, + ) + + @InternalMapConductorApi + constructor(cells: HashMap, large: IntArray) : this( + cells, large, listOf(Level(POLYGON_CELL, cells)), + maxOf(cells.values.maxOfOrNull { it.maxOrNull() ?: -1 } ?: -1, large.maxOrNull() ?: -1) + 1, + large, + ) + + fun query( + bboxOf: (Int) -> DoubleArray?, + minX: Double, + minY: Double, + maxX: Double, + maxY: Double, + ): IntArray { + val seen = BitSet(count) + val matches = BitSet(count) + + fun take(i: Int) { + seen.set(i) + } + for (i in legacyLarge) take(i) + for (level in levels) { + val cx0 = floor(minX / level.size).toLong() + val cx1 = floor(maxX / level.size).toLong() + val cy0 = floor(minY / level.size).toLong() + val cy1 = floor(maxY / level.size).toLong() + val area = (cx1 - cx0 + 1).toDouble() * (cy1 - cy0 + 1) + val groups = level.groups + if (area > 16_384 && groups != null) { + val gx0 = Math.floorDiv(cx0, 16L) + val gx1 = Math.floorDiv(cx1, 16L) + val gy0 = Math.floorDiv(cy0, 16L) + val gy1 = Math.floorDiv(cy1, 16L) + val groupArea = (gx1 - gx0 + 1).toDouble() * (gy1 - gy0 + 1) + if (groupArea > groups.size) { + for (bucket in level.cells.values) for (i in bucket) take(i) + } else { + for (gx in gx0..gx1) { + for (gy in gy0..gy1) { + val buckets = groups[cellKey(gx, gy)] ?: continue + for (bucket in buckets) for (i in bucket) take(i) + } + } + } + } else if (area > level.cells.size) { + // A zoomed-out tile must not enumerate millions of empty cells. + for (bucket in level.cells.values) for (i in bucket) take(i) + } else { + for (cx in cx0..cx1) { + for (cy in cy0..cy1) { + val bucket = level.cells[cellKey(cx, cy)] ?: continue + for (i in bucket) take(i) + } + } + } + } + // Read boxes in source order. File-backed geometry can then stream + // through its block cache instead of seeking in spatial bucket order. + var candidate = seen.nextSetBit(0) + while (candidate >= 0) { + val b = bboxOf(candidate) + if (b != null && b[0] <= maxX && b[2] >= minX && b[1] <= maxY && b[3] >= minY) matches.set(candidate) + candidate = seen.nextSetBit(candidate + 1) + } + // A bitset removes duplicates before bounding-box checks and produces + // draw order without sorting the same shape once for every cell it spans. + val out = IntArray(matches.cardinality()) + var next = matches.nextSetBit(0) + var at = 0 + while (next >= 0) { + out[at++] = next + next = matches.nextSetBit(next + 1) + } + return out + } + + @InternalMapConductorApi + companion object { + fun build( + count: Int, + bboxOf: (Int) -> DoubleArray?, + ): ShapeGridIndex { + val buckets = Array(7) { HashMap() } + val canGroup = BooleanArray(7) { true } + val large = IntList() + for (i in 0 until count) { + val b = bboxOf(i) ?: continue + var level = 0 + var size = POLYGON_CELL + + fun cellsWide() = + (floor(b[2] / size) - floor(b[0] / size) + 1) * + (floor(b[3] / size) - floor(b[1] / size) + 1) + if (cellsWide() > POLYGON_MAX_CELLS) large.add(i) + while (level < buckets.lastIndex && cellsWide() > 16) { + level++ + size *= 4 + } + val cx0 = floor(b[0] / size).toLong() + val cx1 = floor(b[2] / size).toLong() + val cy0 = floor(b[1] / size).toLong() + val cy1 = floor(b[3] / size).toLong() + // Group keys can be decoded only when Y is in the packed key's + // nonnegative range. Keep the original query for polar overhangs. + if (cy0 < 0 || cy1 >= 1_048_576L) canGroup[level] = false + for (cx in cx0..cx1) { + for (cy in cy0..cy1) { + buckets[level].getOrPut(cellKey(cx, cy)) { IntList() }.add(i) + } + } + } + val levels = + buckets.mapIndexed { level, map -> + val packed = HashMap(map.size * 2) + for ((key, list) in map) packed[key] = list.toArray() + val groups = + if (canGroup[level]) { + val grouped = HashMap>() + for ((key, values) in packed) { + val cx = Math.floorDiv(key, 1_048_576L) + val cy = Math.floorMod(key, 1_048_576L) + grouped + .getOrPut(cellKey(Math.floorDiv(cx, 16L), Math.floorDiv(cy, 16L))) { ArrayList() } + .add(values) + } + HashMap>().also { out -> + for ((key, values) in grouped) { + out[key] = + values.toTypedArray() + } + } + } else { + null + } + Level(POLYGON_CELL * (1 shl (level * 2)), packed, groups) + } + return ShapeGridIndex(levels[0].cells, large.toArray(), levels.filter { it.cells.isNotEmpty() }, count) + } + + fun cellKey( + cx: Long, + cy: Long, + ): Long = cx * 1_048_576L + cy + } +} diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt index 9c99c50..2abe4d0 100644 --- a/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt @@ -1,417 +1,510 @@ -package com.mapconductor.core.shapetile - -import androidx.core.graphics.createBitmap -import com.mapconductor.core.InternalMapConductorApi -import com.mapconductor.core.ResourceProvider -import com.mapconductor.core.tileserver.ScratchPool -import com.mapconductor.core.tileserver.TilePngEncoder -import com.mapconductor.core.tileserver.TileProviderInterface -import com.mapconductor.core.tileserver.TileRequest -import java.io.ByteArrayOutputStream -import java.util.concurrent.atomic.AtomicLong -import java.util.concurrent.atomic.AtomicReferenceArray -import kotlin.math.max -import kotlin.math.roundToInt -import android.graphics.Bitmap -import android.graphics.Canvas -import android.graphics.Color -import android.graphics.Paint -import android.graphics.Path -import android.util.LruCache - -/** - * Draws a list of shapes into raster tiles, served by - * [com.mapconductor.core.tileserver.LocalTileServer]: the part the polygon - * tiles and the polyline tiles share. What a shape is and how it is drawn is - * the [Painter]'s; everything else is here -- the grid index, a simplified copy - * per zoom, the tile cache and its invalidation, the scratch bitmaps, PNG - * encoding and cancellation. The counterpart of the "Shape tiles" section of - * js-sdk-core's tile-sw.js and ios-sdk-core's `ShapeTileRenderer`. - * - * Geometry is in tile units (a tile is [tileSize] wide whatever its pixels); - * a tile is drawn [pixelScale] pixels per unit, so a stroke of 1 dp is one - * unit wide, as on the web where it is one CSS pixel, and stays that wide at - * every zoom. - * - * Tiles are cached here without the version the map sees in their URL. An - * in-place change ([update]) drops only the tiles that overlap what changed, - * widened by the widest stroke; the map asks again for every tile because the - * version moved, and the ones the change did not touch come straight back - * from the cache. - * - * [renderTile] runs concurrently on the tile server's threads. Every change - * replaces the model it reads, so a tile is drawn from one consistent list. - */ -@InternalMapConductorApi -internal class ShapeTileRenderer( - val tileSize: Int = 256, - cacheSizeBytes: Int = DEFAULT_CACHE_BYTES, - private val pixelScale: () -> Float = { ResourceProvider.getDensity() }, - private val painter: Painter, - /** What a cancelled tile throws: a failure the map may retry, never an empty tile. */ - private val cancelled: () -> Exception = { TileRenderCancelled() }, -) : TileProviderInterface { - /** What a kind of shape is to the tiles. */ - @InternalMapConductorApi - interface Painter { - /** Web Mercator `minX, minY, maxX, maxY`. */ - fun bbox(item: T): DoubleArray - - /** - * The widest the shape is drawn past its bounding box, as a stroke - * width in tile units (dp): half of it reaches past each side. 0 when - * nothing is drawn outside the box. - */ - fun strokeWidth(item: T): Float - - /** The shape at a zoom whose world is [scale] units wide. Cached per zoom. */ - fun simplify( - item: T, - scale: Double, - ): Any - - /** - * Draws [shape] (from [simplify]) with its origin at [originX], [originY] - * world units and [r] pixels per unit. True if anything was drawn. - */ - fun draw( - canvas: Canvas, - item: T, - shape: Any, - originX: Double, - originY: Double, - r: Float, - paints: Paints, - ): Boolean - } - - /** Paints and a path, one set per tile drawn. */ - @InternalMapConductorApi - class Paints { - val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } - val stroke = - Paint(Paint.ANTI_ALIAS_FLAG).apply { - style = Paint.Style.STROKE - strokeJoin = Paint.Join.ROUND - strokeCap = Paint.Cap.ROUND - } - - /** Not anti-aliased: a polygon under a pixel is one whole pixel. */ - val dot = Paint().apply { style = Paint.Style.FILL } - val path = Path() - } - - @InternalMapConductorApi - private class Simplified( - val source: Any, - val shape: Any, - ) - - /** - * What tiles are drawn from. [perZoom] is shared by the models an - * [update] derives from one [setItems]: an entry is used only while its - * source is still the item at that index, so a changed item is - * simplified again without clearing anything. - */ - @InternalMapConductorApi - private class Model( - val items: Array, - val bboxes: Array, - val index: ShapeGridIndex, - val maxStroke: Float, - val perZoom: LinkedHashMap>, - ) - - @Volatile - private var model: Model? = null - - /** Bumped by every change, so a tile drawn before it is not cached after it. */ - private val generation = AtomicLong() - - private val tileCache = - object : LruCache(cacheSizeBytes) { - override fun sizeOf( - key: Long, - value: ByteArray, - ): Int = value.size - } - private val cacheLock = Any() - - // Pools, not thread-locals: tiles are drawn on the map SDK's threads, which can - // outlive this renderer (see ScratchPool) and would keep a tile bitmap each. - private val scratchBitmaps = ScratchPool() - private val byteStreams = ScratchPool() - - /** Replaces every shape. Draw order is list order. */ - fun setItems(items: List) { - val array: Array = items.toTypedArray() - val bboxes = Array(array.size) { i -> bboxAt(array, i) } - val index = ShapeGridIndex.build(bboxes.size) { bboxes[it] } - model = Model(array, bboxes, index, maxStrokeOf(array), LinkedHashMap(8, 0.75f, true)) - synchronized(cacheLock) { - generation.incrementAndGet() - tileCache.evictAll() - } - } - - /** - * Replaces the shapes at the given indexes. Only the tiles that - * overlapped one of them, before or after, are drawn again. - */ - fun update(updates: List>) { - val current = model ?: return - val items = current.items.copyOf() - val bboxes = current.bboxes.copyOf() - val touched = ArrayList(updates.size * 2) - var maxStroke = current.maxStroke - var reindex = false - for ((index, after) in updates) { - if (index !in items.indices) continue - val before = bboxes[index] - items[index] = after - val afterBox = after?.let(painter::bbox) - bboxes[index] = afterBox - before?.let(touched::add) - afterBox?.let(touched::add) - if (after != null) maxStroke = max(maxStroke, painter.strokeWidth(after)) - // A shape that moved needs the index rebuilt; a restyle does not. - if (before == null || afterBox == null || !before.contentEquals(afterBox)) reindex = true - } - val index = if (reindex) ShapeGridIndex.build(bboxes.size) { bboxes[it] } else current.index - model = Model(items, bboxes, index, maxStroke, current.perZoom) - synchronized(cacheLock) { - generation.incrementAndGet() - dropTilesIn(touched, maxStroke) - } - } - - fun clear() { - model = null - synchronized(cacheLock) { - generation.incrementAndGet() - tileCache.evictAll() - } - } - - override fun renderTile(request: TileRequest): ByteArray? = renderTile(request) { false } - - override fun renderTile( - request: TileRequest, - isCancelled: () -> Boolean, - ): ByteArray? { - val generationAtStart = generation.get() - val m = model ?: return null - val z = request.z - if (z !in 0..MAX_ZOOM) return null - val n = 1 shl z - val x = ((request.x % n) + n) % n - val y = request.y - if (y !in 0 until n) return null - val ratio = request.pixelRatio.coerceIn(1, 3) - val key = cacheKey(z, x, y, ratio) - synchronized(cacheLock) { tileCache.get(key) }?.let { return it } - - val bitmap = draw(m, x, y, z, ratio, isCancelled) ?: return null - val bytes = - try { - encode(bitmap) - } finally { - releaseScratch(bitmap) - } - synchronized(cacheLock) { - // The shapes may have changed while this tile was drawn. - if (generation.get() == generationAtStart) tileCache.put(key, bytes) - } - return bytes - } - - /** The tile as a bitmap, or null when nothing of any shape is in it. For tests and [renderTile]. */ - fun renderBitmap( - x: Int, - y: Int, - z: Int, - pixelRatio: Int = 1, - ): Bitmap? = - model?.let { draw(it, x, y, z, pixelRatio) { false } }?.let { scratch -> - try { - scratch.copy(Bitmap.Config.ARGB_8888, false) - } finally { - releaseScratch(scratch) - } - } - - private fun draw( - m: Model, - x: Int, - y: Int, - z: Int, - pixelRatio: Int, - isCancelled: () -> Boolean, - ): Bitmap? { - val scale = tileSize.toDouble() * (1L shl z).toDouble() - val originX = x.toDouble() * tileSize - val originY = y.toDouble() * tileSize - // A stroke reaches half its width past the shape: take the shapes that - // close to the tile too, and draw them whole (the canvas cuts them), so - // the tile next door draws the same line at the same place. - val pad = m.maxStroke / 2.0 + 1.0 - val bboxes = m.bboxes - val candidates = - m.index.query( - { bboxes[it] }, - (originX - pad) / scale, - (originY - pad) / scale, - (originX + tileSize + pad) / scale, - (originY + tileSize + pad) / scale, - ) - if (candidates.isEmpty()) return null - - val r = pixelScale() * pixelRatio - val px = (tileSize * r).roundToInt().coerceAtLeast(1) - val bitmap = scratch(px) - try { - return drawInto(bitmap, m, candidates, originX, originY, r, z, scale, isCancelled) - } catch (error: Throwable) { - releaseScratch(bitmap) - throw error - } - } - - /** Draws into [bitmap]; null (and the bitmap back in the pool) when nothing was drawn. */ - @Suppress("UNCHECKED_CAST") - private fun drawInto( - bitmap: Bitmap, - m: Model, - candidates: IntArray, - originX: Double, - originY: Double, - r: Float, - z: Int, - scale: Double, - isCancelled: () -> Boolean, - ): Bitmap? { - val canvas = Canvas(bitmap) - val paints = Paints() - val perZoom = perZoomOf(m, z) - var drew = false - for ((k, index) in candidates.withIndex()) { - if (k % CANCEL_CHECK_EVERY == 0 && isCancelled()) throw cancelled() - val item = (m.items[index] ?: continue) as T - val shape = simplifiedAt(perZoom, index, item, scale) - if (painter.draw(canvas, item, shape, originX, originY, r, paints)) drew = true - } - if (!drew) releaseScratch(bitmap) - return if (drew) bitmap else null - } - - private fun perZoomOf( - m: Model, - z: Int, - ): AtomicReferenceArray = - synchronized(m.perZoom) { - // Access order: a lookup makes the zoom the most recent one. - m.perZoom[z] ?: AtomicReferenceArray(m.items.size).also { created -> - m.perZoom[z] = created - val it = m.perZoom.keys.iterator() - while (m.perZoom.size > ZOOMS_KEPT && it.hasNext()) { - it.next() - it.remove() - } - } - } - - private fun simplifiedAt( - perZoom: AtomicReferenceArray, - index: Int, - item: T, - scale: Double, - ): Any { - val cached = perZoom.get(index) - if (cached != null && cached.source === item) return cached.shape - val shape = painter.simplify(item, scale) - perZoom.set(index, Simplified(item, shape)) - return shape - } - - private fun scratch(px: Int): Bitmap { - val existing = scratchBitmaps.acquire { !it.isRecycled && it.width == px && it.height == px } - if (existing != null) { - existing.eraseColor(Color.TRANSPARENT) - return existing - } - return createBitmap(px, px) - } - - private fun releaseScratch(bitmap: Bitmap) { - scratchBitmaps.release(bitmap) - } - - private fun encode(bitmap: Bitmap): ByteArray { - // Rust first, as for marker tiles: Bitmap.compress is several times slower. - TilePngEncoder.encode(bitmap)?.let { return it } - val out = byteStreams.acquire() ?: ByteArrayOutputStream(16 * 1024) - try { - out.reset() - bitmap.compress(Bitmap.CompressFormat.PNG, 100, out) - return out.toByteArray() - } finally { - byteStreams.release(out) - } - } - - private fun dropTilesIn( - boxes: List, - strokePx: Float, - ) { - if (boxes.isEmpty()) return - for (key in tileCache.snapshot().keys) { - val z = (key ushr 56).toInt() - val x = ((key ushr 27) and COORD_MASK).toInt() - val y = (key and COORD_MASK).toInt() - val scale = tileSize.toDouble() * (1L shl z).toDouble() - val pad = (strokePx + 2.0) / scale - val tx0 = x * tileSize / scale - pad - val tx1 = (x + 1) * tileSize / scale + pad - val ty0 = y * tileSize / scale - pad - val ty1 = (y + 1) * tileSize / scale + pad - if (boxes.any { b -> b[0] <= tx1 && b[2] >= tx0 && b[1] <= ty1 && b[3] >= ty0 }) { - tileCache.remove(key) - } - } - } - - private fun cacheKey( - z: Int, - x: Int, - y: Int, - ratio: Int, - ): Long = (z.toLong() shl 56) or (ratio.toLong() shl 54) or (x.toLong() shl 27) or y.toLong() - - @Suppress("UNCHECKED_CAST") - private fun bboxAt( - items: Array, - i: Int, - ): DoubleArray? = (items[i] as T?)?.let(painter::bbox) - - @Suppress("UNCHECKED_CAST") - private fun maxStrokeOf(items: Array): Float { - var maxStroke = 0f - for (item in items) if (item != null) maxStroke = max(maxStroke, painter.strokeWidth(item as T)) - return maxStroke - } - - /** Thrown when the map stops wanting a tile mid-draw: a failure it may retry, never an empty tile. */ - @InternalMapConductorApi - class TileRenderCancelled : Exception("shape tile no longer wanted") - - @InternalMapConductorApi - companion object { - const val DEFAULT_CACHE_BYTES = 16 * 1024 * 1024 - - /** Simplified copies kept, most recent zooms first. */ - private const val ZOOMS_KEPT = 4 - private const val MAX_ZOOM = 26 - private const val CANCEL_CHECK_EVERY = 256 - private const val COORD_MASK = (1L shl 27) - 1 - } -} +package com.mapconductor.core.shapetile + +import androidx.core.graphics.createBitmap +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.tileserver.ScratchPool +import com.mapconductor.core.tileserver.TilePngEncoder +import com.mapconductor.core.tileserver.TileProviderInterface +import com.mapconductor.core.tileserver.TileRequest +import java.io.ByteArrayOutputStream +import java.util.BitSet +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.AtomicReferenceArray +import kotlin.math.max +import kotlin.math.roundToInt +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.util.LruCache + +/** + * Draws a list of shapes into raster tiles, served by + * [com.mapconductor.core.tileserver.LocalTileServer]: the part the polygon + * tiles and the polyline tiles share. What a shape is and how it is drawn is + * the [Painter]'s; everything else is here -- the grid index, a simplified copy + * per zoom, the tile cache and its invalidation, the scratch bitmaps, PNG + * encoding and cancellation. The counterpart of the "Shape tiles" section of + * js-sdk-core's tile-sw.js and ios-sdk-core's `ShapeTileRenderer`. + * + * Geometry is in tile units (a tile is [tileSize] wide whatever its pixels); + * a tile is drawn [pixelScale] pixels per unit, so a stroke of 1 dp is one + * unit wide, as on the web where it is one CSS pixel, and stays that wide at + * every zoom. + * + * Tiles are cached here without the version the map sees in their URL. An + * in-place change ([update]) drops only the tiles that overlap what changed, + * widened by the widest stroke; the map asks again for every tile because the + * version moved, and the ones the change did not touch come straight back + * from the cache. + * + * [renderTile] runs concurrently on the tile server's threads. Every change + * replaces the model it reads, so a tile is drawn from one consistent list. + */ +@InternalMapConductorApi +internal class ShapeTileRenderer( + val tileSize: Int = 256, + cacheSizeBytes: Int = DEFAULT_CACHE_BYTES, + private val pixelScale: () -> Float = { ResourceProvider.getDensity() }, + private val painter: Painter, + /** What a cancelled tile throws: a failure the map may retry, never an empty tile. */ + private val cancelled: () -> Exception = { TileRenderCancelled() }, +) : TileProviderInterface { + /** What a kind of shape is to the tiles. */ + @InternalMapConductorApi + interface Painter { + /** Web Mercator `minX, minY, maxX, maxY`. */ + fun bbox(item: T): DoubleArray + + /** + * The widest the shape is drawn past its bounding box, as a stroke + * width in tile units (dp): half of it reaches past each side. 0 when + * nothing is drawn outside the box. + */ + fun strokeWidth(item: T): Float + + val cacheSimplifiedShapes: Boolean get() = true + val thinSubpixelOverlaps: Boolean get() = false + + fun isVisible(item: T): Boolean = true + + /** Pixel slot, -1 outside the tile, or -2 when the shape is not subpixel. */ + fun subpixelSlot( + item: T, + scale: Double, + originX: Double, + originY: Double, + tileSize: Int, + ): Int = -2 + + /** The shape at a zoom whose world is [scale] units wide. Cached per zoom. */ + fun simplify( + item: T, + scale: Double, + ): Any + + /** + * Draws [shape] (from [simplify]) with its origin at [originX], [originY] + * world units and [r] pixels per unit. True if anything was drawn. + */ + fun draw( + canvas: Canvas, + item: T, + shape: Any, + originX: Double, + originY: Double, + r: Float, + paints: Paints, + ): Boolean + } + + /** Paints and a path, one set per tile drawn. */ + @InternalMapConductorApi + class Paints { + val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + val stroke = + Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeJoin = Paint.Join.ROUND + strokeCap = Paint.Cap.ROUND + } + + /** Not anti-aliased: a polygon under a pixel is one whole pixel. */ + val dot = Paint().apply { style = Paint.Style.FILL } + val path = Path() + } + + @InternalMapConductorApi + private class Simplified( + val source: Any, + val shape: Any, + ) + + /** + * What tiles are drawn from. [perZoom] is shared by the models an + * [update] derives from one [setItems]: an entry is used only while its + * source is still the item at that index, so a changed item is + * simplified again without clearing anything. + */ + @InternalMapConductorApi + private class Model( + val storage: ShapeTileStorage, + val index: ShapeGridIndex, + val maxStroke: Float, + val perZoom: LinkedHashMap>, + val active: BitSet? = null, + ) + + @Volatile + private var model: Model? = null + private val modelLock = Any() + + private fun acquireModel(): Model? = + synchronized(modelLock) { + model?.also { it.storage.retain() } + } + + /** Takes ownership of the replacement's storage reference. */ + private fun replaceModel(next: Model?) = + synchronized(modelLock) { + val previous = model + model = next + previous?.storage?.release() + } + + fun itemAt(index: Int): T? { + val current = acquireModel() ?: return null + return try { + current.storage[index] + } finally { + current.storage.release() + } + } + + /** Immutable membership snapshot; geometry and its spatial index stay shared. */ + fun setActiveItems(active: BitSet) { + synchronized(modelLock) { + val current = model ?: return + current.storage.retain() + replaceModel(Model(current.storage, current.index, current.maxStroke, current.perZoom, active)) + } + synchronized(cacheLock) { + generation.incrementAndGet() + tileCache.evictAll() + } + } + + /** Bumped by every change, so a tile drawn before it is not cached after it. */ + private val generation = AtomicLong() + + private val tileCache = + object : LruCache(cacheSizeBytes) { + override fun sizeOf( + key: Long, + value: ByteArray, + ): Int = value.size + } + private val cacheLock = Any() + + // Pools, not thread-locals: tiles are drawn on the map SDK's threads, which can + // outlive this renderer (see ScratchPool) and would keep a tile bitmap each. + private val scratchBitmaps = ScratchPool() + private val byteStreams = ScratchPool() + + /** Replaces every shape. Draw order is list order. */ + fun setItems(items: List) { + setStorage(MemoryShapeTileStorage(items, painter)) + } + + /** Builds the shared shape index without materialising file-backed geometry. Consumes [storage]. */ + fun setStorage( + storage: ShapeTileStorage, + checkCancelled: () -> Unit = {}, + ) { + val index = + try { + ShapeGridIndex + .build(storage.size) { + if (it % 4096 == 0) checkCancelled() + storage.bbox(it) + }.also { checkCancelled() } + } catch (error: Throwable) { + storage.release() + throw error + } + replaceModel(Model(storage, index, storage.maxStroke, LinkedHashMap(8, 0.75f, true))) + synchronized(cacheLock) { + generation.incrementAndGet() + tileCache.evictAll() + } + } + + /** + * Replaces the shapes at the given indexes. Only the tiles that + * overlapped one of them, before or after, are drawn again. + */ + fun update(updates: List>) { + val current = acquireModel() ?: return + var next: ShapeTileStorage? = null + try { + val touched = ArrayList(updates.size * 2) + var maxStroke = current.maxStroke + var reindex = false + for ((index, after) in updates) { + if (index !in 0 until current.storage.size) continue + val before = current.storage.bbox(index) + val afterBox = after?.let(painter::bbox) + before?.let(touched::add) + afterBox?.let(touched::add) + if (after != null) maxStroke = max(maxStroke, painter.strokeWidth(after)) + // A shape that moved needs the index rebuilt; a restyle does not. + if (before == null || afterBox == null || !before.contentEquals(afterBox)) reindex = true + } + val replacement = current.storage.updated(updates) + next = replacement + val index = if (reindex) ShapeGridIndex.build(replacement.size, replacement::bbox) else current.index + replaceModel(Model(replacement, index, maxStroke, current.perZoom, current.active)) + next = null + synchronized(cacheLock) { + generation.incrementAndGet() + dropTilesIn(touched, maxStroke) + } + } finally { + next?.release() + current.storage.release() + } + } + + fun clear() { + replaceModel(null) + synchronized(cacheLock) { + generation.incrementAndGet() + tileCache.evictAll() + } + } + + override fun renderTile(request: TileRequest): ByteArray? = renderTile(request) { false } + + override fun renderTile( + request: TileRequest, + isCancelled: () -> Boolean, + ): ByteArray? { + val generationAtStart = generation.get() + val m = acquireModel() ?: return null + try { + val z = request.z + if (z !in 0..MAX_ZOOM) return null + val n = 1 shl z + val x = ((request.x % n) + n) % n + val y = request.y + if (y !in 0 until n) return null + val ratio = request.pixelRatio.coerceIn(1, 3) + val key = cacheKey(z, x, y, ratio) + synchronized(cacheLock) { tileCache.get(key) }?.let { return it } + + val bitmap = draw(m, x, y, z, ratio, isCancelled) ?: return null + val bytes = + try { + encode(bitmap) + } finally { + releaseScratch(bitmap) + } + synchronized(cacheLock) { + // The shapes may have changed while this tile was drawn. + if (generation.get() == generationAtStart) tileCache.put(key, bytes) + } + return bytes + } finally { + m.storage.release() + } + } + + /** The tile as a bitmap, or null when nothing of any shape is in it. For tests and [renderTile]. */ + fun renderBitmap( + x: Int, + y: Int, + z: Int, + pixelRatio: Int = 1, + ): Bitmap? { + val current = acquireModel() ?: return null + return try { + draw(current, x, y, z, pixelRatio) { false }?.let { scratch -> + try { + scratch.copy(Bitmap.Config.ARGB_8888, false) + } finally { + releaseScratch(scratch) + } + } + } finally { + current.storage.release() + } + } + + private fun draw( + m: Model, + x: Int, + y: Int, + z: Int, + pixelRatio: Int, + isCancelled: () -> Boolean, + ): Bitmap? { + val scale = tileSize.toDouble() * (1L shl z).toDouble() + val originX = x.toDouble() * tileSize + val originY = y.toDouble() * tileSize + // A stroke reaches half its width past the shape: take the shapes that + // close to the tile too, and draw them whole (the canvas cuts them), so + // the tile next door draws the same line at the same place. + val pad = m.maxStroke / 2.0 + 1.0 + val candidates = + m.index.query( + { index -> if (m.active?.get(index) == false) null else m.storage.bbox(index) }, + (originX - pad) / scale, + (originY - pad) / scale, + (originX + tileSize + pad) / scale, + (originY + tileSize + pad) / scale, + ) + if (candidates.isEmpty()) return null + + val r = pixelScale() * pixelRatio + val px = (tileSize * r).roundToInt().coerceAtLeast(1) + val bitmap = scratch(px) + try { + return drawInto(bitmap, m, candidates, originX, originY, r, z, scale, isCancelled) + } catch (error: Throwable) { + releaseScratch(bitmap) + throw error + } + } + + /** Draws into [bitmap]; null (and the bitmap back in the pool) when nothing was drawn. */ + @Suppress("UNCHECKED_CAST") + private fun drawInto( + bitmap: Bitmap, + m: Model, + candidates: IntArray, + originX: Double, + originY: Double, + r: Float, + z: Int, + scale: Double, + isCancelled: () -> Boolean, + ): Bitmap? { + val canvas = Canvas(bitmap) + val paints = Paints() + val perZoom = perZoomOf(m, z) + // Subpixel circles are display representatives: keep the last visible + // circle at each world pixel. Never remove states or larger circles. + val lastDot = IntArray(if (painter.thinSubpixelOverlaps) tileSize * tileSize else 0) + if (painter.thinSubpixelOverlaps) { + for ((k, index) in candidates.withIndex()) { + if (k % CANCEL_CHECK_EVERY == 0 && isCancelled()) throw cancelled() + if (m.active != null && !m.active[index]) continue + val item = m.storage[index] ?: continue + if (!painter.isVisible(item)) continue + val slot = painter.subpixelSlot(item, scale, originX, originY, tileSize) + if (slot >= 0) lastDot[slot] = index + 1 + } + } + var drew = false + for ((k, index) in candidates.withIndex()) { + if (k % CANCEL_CHECK_EVERY == 0 && isCancelled()) throw cancelled() + if (m.active != null && !m.active[index]) continue + val item = m.storage[index] ?: continue + if (painter.thinSubpixelOverlaps) { + val slot = painter.subpixelSlot(item, scale, originX, originY, tileSize) + if (slot == -1 || (slot >= 0 && lastDot[slot] != index + 1)) continue + } + val shape = simplifiedAt(perZoom, index, item, scale) + if (painter.draw(canvas, item, shape, originX, originY, r, paints)) drew = true + } + if (!drew) releaseScratch(bitmap) + return if (drew) bitmap else null + } + + private fun perZoomOf( + m: Model, + z: Int, + ): AtomicReferenceArray = + if (!painter.cacheSimplifiedShapes) { + AtomicReferenceArray(0) + } else { + synchronized(m.perZoom) { + // Access order: a lookup makes the zoom the most recent one. + m.perZoom[z] ?: AtomicReferenceArray(m.storage.size).also { created -> + m.perZoom[z] = created + val it = m.perZoom.keys.iterator() + while (m.perZoom.size > ZOOMS_KEPT && it.hasNext()) { + it.next() + it.remove() + } + } + } + } + + private fun simplifiedAt( + perZoom: AtomicReferenceArray, + index: Int, + item: T, + scale: Double, + ): Any { + // Dot and Arc are cheap projections of compact circle data. Caching + // them for every source circle at several zooms defeats raster tiling. + if (!painter.cacheSimplifiedShapes) return painter.simplify(item, scale) + val cached = perZoom.get(index) + if (cached != null && cached.source === item) return cached.shape + val shape = painter.simplify(item, scale) + perZoom.set(index, Simplified(item, shape)) + return shape + } + + private fun scratch(px: Int): Bitmap { + val existing = scratchBitmaps.acquire { !it.isRecycled && it.width == px && it.height == px } + if (existing != null) { + existing.eraseColor(Color.TRANSPARENT) + return existing + } + return createBitmap(px, px) + } + + private fun releaseScratch(bitmap: Bitmap) { + scratchBitmaps.release(bitmap) + } + + private fun encode(bitmap: Bitmap): ByteArray { + // Rust first, as for marker tiles: Bitmap.compress is several times slower. + TilePngEncoder.encode(bitmap)?.let { return it } + val out = byteStreams.acquire() ?: ByteArrayOutputStream(16 * 1024) + try { + out.reset() + bitmap.compress(Bitmap.CompressFormat.PNG, 100, out) + return out.toByteArray() + } finally { + byteStreams.release(out) + } + } + + private fun dropTilesIn( + boxes: List, + strokePx: Float, + ) { + if (boxes.isEmpty()) return + for (key in tileCache.snapshot().keys) { + val z = (key ushr 56).toInt() + val x = ((key ushr 27) and COORD_MASK).toInt() + val y = (key and COORD_MASK).toInt() + val scale = tileSize.toDouble() * (1L shl z).toDouble() + val pad = (strokePx + 2.0) / scale + val tx0 = x * tileSize / scale - pad + val tx1 = (x + 1) * tileSize / scale + pad + val ty0 = y * tileSize / scale - pad + val ty1 = (y + 1) * tileSize / scale + pad + if (boxes.any { b -> b[0] <= tx1 && b[2] >= tx0 && b[1] <= ty1 && b[3] >= ty0 }) { + tileCache.remove(key) + } + } + } + + private fun cacheKey( + z: Int, + x: Int, + y: Int, + ratio: Int, + ): Long = (z.toLong() shl 56) or (ratio.toLong() shl 54) or (x.toLong() shl 27) or y.toLong() + + /** Thrown when the map stops wanting a tile mid-draw: a failure it may retry, never an empty tile. */ + @InternalMapConductorApi + class TileRenderCancelled : Exception("shape tile no longer wanted") + + @InternalMapConductorApi + companion object { + const val DEFAULT_CACHE_BYTES = 16 * 1024 * 1024 + + /** Simplified copies kept, most recent zooms first. */ + private const val ZOOMS_KEPT = 4 + private const val MAX_ZOOM = 26 + private const val CANCEL_CHECK_EVERY = 256 + private const val COORD_MASK = (1L shl 27) - 1 + } +} diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt index 29aa718..2403782 100644 --- a/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt @@ -1,166 +1,286 @@ -package com.mapconductor.core.shapetile - -import com.mapconductor.core.InternalMapConductorApi -import com.mapconductor.core.tileserver.LocalTileServer -import java.util.UUID -import kotlin.time.Duration.Companion.milliseconds -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * The shapes of one map that are drawn as raster tiles, and their route on the - * local tile server: the part `PolygonTileSet` and `PolylineTileSet` share. - * Each of those adds what a state is as a tile ([toTile]) and which states can - * be tiled. - * - * [setShapes] registers the list and returns the URL template of its tiles; - * [update] and [remove] change one shape in place, coalesced over - * [UPDATE_COALESCE], and each batch ends in a new template -- the version in - * it is what makes the map ask again -- reported to [onTemplateChanged]. Tiles - * the change did not touch are still cached by the renderer and come back - * without being drawn again. - * - * The same as js-sdk-core's and ios-sdk-core's `ShapeTileSet`. - */ -@InternalMapConductorApi -internal class ShapeTileSet( - routePrefix: String, - private val server: LocalTileServer, - private val scope: CoroutineScope, - private val renderer: ShapeTileRenderer, - private val idOf: (S) -> String, - private val zIndexOf: (S) -> Int, - private val toTile: (S) -> T?, -) { - val routeId: String = "$routePrefix-${UUID.randomUUID().toString().take(8)}" - - /** Called with the new template after an [update] or [remove]. */ - var onTemplateChanged: (suspend (String) -> Unit)? = null - - val tileSize: Int get() = renderer.tileSize - - private val lock = Any() - private var indexById: Map = emptyMap() - - @Volatile - private var version = 0 - private var registered = false - private val pending = LinkedHashMap() - private val pendingRemovals = ArrayList() - private var flushJob: Job? = null - - /** - * Registers [states] (replacing whatever was registered) and returns the - * URL template of their tiles. - */ - suspend fun setShapes(states: List): String { - cancelPending() - val (shapes, ids) = - withContext(Dispatchers.Default) { - // Draw order is list order: zIndex, then the order given (sortedBy is stable). - val ordered = states.sortedBy(zIndexOf) - val ids = HashMap(ordered.size * 2) - ordered.forEachIndexed { index, state -> ids[idOf(state)] = index } - ordered.map(toTile) to ids - } - synchronized(lock) { - renderer.setItems(shapes) - if (!registered) server.register(routeId, renderer) - indexById = ids - registered = true - version++ - } - return template() - } - - fun has(id: String): Boolean = synchronized(lock) { indexById.containsKey(id) } - - /** - * One shape changed in place. A change of zIndex reorders the list and - * needs [setShapes] instead; everything else is applied here. - */ - fun update(state: S) { - synchronized(lock) { - val id = idOf(state) - if (!indexById.containsKey(id)) return - pending[id] = state - scheduleFlushLocked() - } - } - - /** - * Takes one shape out of the tiles. Its slot in the renderer's list is - * left empty, so the others keep their indices and only the tiles it was - * in are drawn again. - */ - fun remove(id: String) { - synchronized(lock) { - val index = indexById[id] ?: return - indexById = indexById - id - pending.remove(id) - pendingRemovals.add(index) - scheduleFlushLocked() - } - } - - /** Called with [lock] held. */ - private fun scheduleFlushLocked() { - if (flushJob == null) { - flushJob = - scope.launch { - delay(UPDATE_COALESCE) - flush() - } - } - } - - /** The URL template, with the version that changes on every change. */ - fun template(): String = server.urlTemplate(routeId, renderer.tileSize, version.toString()) - - fun dispose() { - cancelPending() - synchronized(lock) { - if (registered) server.unregister(routeId) - registered = false - indexById = emptyMap() - renderer.clear() - } - } - - private suspend fun flush() { - val template = - synchronized(lock) { - flushJob = null - val updates: List> = - pending.values.mapNotNull { state -> - indexById[idOf(state)]?.let { index -> index to toTile(state) } - } + pendingRemovals.map { index -> index to null } - pending.clear() - pendingRemovals.clear() - if (updates.isEmpty() || !registered) return - renderer.update(updates) - version++ - template() - } - onTemplateChanged?.invoke(template) - } - - private fun cancelPending() { - synchronized(lock) { - flushJob?.cancel() - flushJob = null - pending.clear() - pendingRemovals.clear() - } - } - - @InternalMapConductorApi - companion object { - /** In-place changes arriving within this window are drawn as one. */ - val UPDATE_COALESCE = 16.milliseconds - } -} +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.tileserver.LocalTileServer +import java.util.BitSet +import java.util.UUID +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * The shapes of one map that are drawn as raster tiles, and their route on the + * local tile server: the part `PolygonTileSet` and `PolylineTileSet` share. + * Each of those adds what a state is as a tile ([toTile]) and which states can + * be tiled. + * + * [setShapes] registers the list and returns the URL template of its tiles; + * [update] and [remove] change one shape in place, coalesced over + * [UPDATE_COALESCE], and each batch ends in a new template -- the version in + * it is what makes the map ask again -- reported to [onTemplateChanged]. Tiles + * the change did not touch are still cached by the renderer and come back + * without being drawn again. + * + * The same as js-sdk-core's and ios-sdk-core's `ShapeTileSet`. + */ +@InternalMapConductorApi +internal class ShapeTileSet( + routePrefix: String, + private val server: LocalTileServer, + private val scope: CoroutineScope, + private val renderer: ShapeTileRenderer, + private val idOf: (S) -> String, + private val zIndexOf: (S) -> Int, + private val toTile: (S) -> T?, + private val canReuse: ((S, T) -> Boolean)? = null, + private val createStorage: (suspend (List) -> ShapeTileStorage?)? = null, +) { + val routeId: String = "$routePrefix-${UUID.randomUUID().toString().take(8)}" + + /** Called with the new template after an [update] or [remove]. */ + var onTemplateChanged: (suspend (String) -> Unit)? = null + + val tileSize: Int get() = renderer.tileSize + + private val lock = Any() + private var indexById: Map = emptyMap() + private var sourceStates: MutableList = mutableListOf() + private var sourceZ = IntArray(0) + private var active: BitSet? = null + + fun ids(): Set = + synchronized(lock) { + val mask = active ?: return@synchronized indexById.keys + val ids = indexById + object : AbstractSet() { + override val size = mask.cardinality() + + override fun contains(element: String): Boolean = ids[element]?.let { mask[it] } == true + + override fun iterator(): Iterator = + ids.entries + .asSequence() + .filter { mask[it.value] } + .map { it.key } + .iterator() + } + } + + fun source(id: String): S? = + synchronized(lock) { + indexById[id]?.takeIf { active?.get(it) != false }?.let { sourceStates[it] } + } + + fun visitSources(action: (S) -> Unit) = + synchronized(lock) { + for ((index, state) in sourceStates.withIndex()) { + if (state != null && + active?.get(index) != false + ) { + action(state) + } + } + } + + @Volatile + private var version = 0 + private var registered = false + private val pending = LinkedHashMap() + private val pendingRemovals = ArrayList() + private var flushJob: Job? = null + + /** + * Registers [states] (replacing whatever was registered) and returns the + * URL template of their tiles. + */ + suspend fun setShapes(states: List): String { + cancelPending() + val ordered = withContext(Dispatchers.Default) { states.sortedBy(zIndexOf) } + // A filtered collection often refers to the same geometry. Keep the + // original slots, including temporarily hidden shapes, for re-enabling. + val reused = + withContext(Dispatchers.Default) { + val context = currentCoroutineContext() + synchronized(lock) { + val matches = canReuse + if (!registered || matches == null) { + false + } else { + val mask = BitSet(sourceStates.size) + var previous = -1 + var checked = 0 + val reusable = + ordered.all { state -> + if (++checked % 4096 == 0) context.ensureActive() + val index = indexById[idOf(state)] + val item = index?.let(renderer::itemAt) + val ok = + index != null && + index > previous && + item != null && + sourceZ[index] == zIndexOf(state) && + matches(state, item) + if (ok) { + mask.set(index!!) + previous = index + } + ok + } + if (reusable) { + // Cache geometry, not removed application states/handlers. + for (index in sourceStates.indices) if (!mask[index]) sourceStates[index] = null + for (state in ordered) sourceStates[indexById.getValue(idOf(state))] = state + active = mask + renderer.setActiveItems(mask) + version++ + } + reusable + } + } + } + if (reused) return template() + var prepared: ShapeTileStorage? = null + try { + val (shapes, ids, sources) = + withContext(Dispatchers.Default) { + // Draw order is list order: zIndex, then the order given (sortedBy is stable). + val ids = HashMap(ordered.size * 2) + ordered.forEachIndexed { index, state -> ids[idOf(state)] = index } + val sources: MutableList = ordered.toMutableList() + prepared = createStorage?.invoke(ordered) + Triple(if (prepared == null) ordered.map(toTile) else emptyList(), ids, sources) + } + withContext(Dispatchers.Default) { + val context = currentCoroutineContext() + synchronized(lock) { + val storage = prepared + prepared = null + if (storage != + null + ) { + renderer.setStorage(storage) { context.ensureActive() } + } else { + renderer.setItems(shapes) + } + if (!registered) server.register(routeId, renderer) + indexById = ids + sourceStates = sources + sourceZ = IntArray(ordered.size) { zIndexOf(ordered[it]) } + active = null + registered = true + version++ + } + } + return template() + } finally { + prepared?.release() + } + } + + fun has(id: String): Boolean = + synchronized(lock) { + indexById[id]?.let { active?.get(it) != false } == true + } + + /** + * One shape changed in place. A change of zIndex reorders the list and + * needs [setShapes] instead; everything else is applied here. + */ + fun update(state: S) { + synchronized(lock) { + val id = idOf(state) + if (!indexById.containsKey(id)) return + sourceStates[indexById.getValue(id)] = state + pending[id] = state + scheduleFlushLocked() + } + } + + /** + * Takes one shape out of the tiles. Its slot in the renderer's list is + * left empty, so the others keep their indices and only the tiles it was + * in are drawn again. + */ + fun remove(id: String) { + synchronized(lock) { + val index = indexById[id] ?: return + sourceStates[index] = null + indexById = indexById - id + active?.let { previous -> + val next = previous.clone() as BitSet + next.clear(index) + active = next + renderer.setActiveItems(next) + } + pending.remove(id) + pendingRemovals.add(index) + scheduleFlushLocked() + } + } + + /** Called with [lock] held. */ + private fun scheduleFlushLocked() { + if (flushJob == null) { + flushJob = + scope.launch { + delay(UPDATE_COALESCE) + flush() + } + } + } + + /** The URL template, with the version that changes on every change. */ + fun template(): String = server.urlTemplate(routeId, renderer.tileSize, version.toString()) + + fun dispose() { + cancelPending() + synchronized(lock) { + if (registered) server.unregister(routeId) + registered = false + indexById = emptyMap() + sourceStates = mutableListOf() + sourceZ = IntArray(0) + active = null + renderer.clear() + } + } + + private suspend fun flush() { + val template = + synchronized(lock) { + flushJob = null + val updates: List> = + pending.values.mapNotNull { state -> + indexById[idOf(state)]?.let { index -> index to toTile(state) } + } + pendingRemovals.map { index -> index to null } + pending.clear() + pendingRemovals.clear() + if (updates.isEmpty() || !registered) return + renderer.update(updates) + version++ + template() + } + onTemplateChanged?.invoke(template) + } + + private fun cancelPending() { + synchronized(lock) { + flushJob?.cancel() + flushJob = null + pending.clear() + pendingRemovals.clear() + } + } + + @InternalMapConductorApi + companion object { + /** In-place changes arriving within this window are drawn as one. */ + val UPDATE_COALESCE = 16.milliseconds + } +} diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTileStorage.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTileStorage.kt new file mode 100644 index 0000000..9be58af --- /dev/null +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTileStorage.kt @@ -0,0 +1,72 @@ +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import java.util.concurrent.atomic.AtomicInteger +import kotlin.math.max + +/** Immutable geometry snapshot. A renderer owns one reference; each reader leases another. */ +@InternalMapConductorApi +internal abstract class ShapeTileStorage { + private val references = AtomicInteger(1) + abstract val size: Int + abstract val maxStroke: Float + + abstract operator fun get(index: Int): T? + + abstract fun bbox(index: Int): DoubleArray? + + abstract fun updated(updates: List>): ShapeTileStorage + + fun retain() { + while (true) { + val count = references.get() + check(count > 0) { "Geometry storage already closed" } + if (references.compareAndSet(count, count + 1)) return + } + } + + fun release() { + val remaining = references.decrementAndGet() + check(remaining >= 0) + if (remaining == 0) close() + } + + protected open fun close() = Unit +} + +/** Existing polygon/polyline storage, and small circle collections. */ +@InternalMapConductorApi +internal class MemoryShapeTileStorage private constructor( + private val items: Array, + private val boxes: Array, + override val maxStroke: Float, + private val painter: ShapeTileRenderer.Painter, +) : ShapeTileStorage() { + constructor(items: List, painter: ShapeTileRenderer.Painter) : this( + items.toTypedArray(), + Array(items.size) { items[it]?.let(painter::bbox) }, + items.maxOfOrNull { it?.let(painter::strokeWidth) ?: 0f } ?: 0f, + painter, + ) + + override val size: Int get() = items.size + + @Suppress("UNCHECKED_CAST") + override fun get(index: Int): T? = items.getOrNull(index) as T? + + override fun bbox(index: Int): DoubleArray? = boxes.getOrNull(index) + + override fun updated(updates: List>): ShapeTileStorage { + val next = items.copyOf() + val nextBoxes = boxes.copyOf() + var widest = maxStroke + for ((index, item) in updates) { + if (index in next.indices) { + next[index] = item + nextBoxes[index] = item?.let(painter::bbox) + if (item != null) widest = max(widest, painter.strokeWidth(item)) + } + } + return MemoryShapeTileStorage(next, nextBoxes, widest, painter) + } +} diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt index a1d6049..ad3b385 100644 --- a/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt @@ -45,7 +45,8 @@ internal class ShapeTiler( tiled = emptySet() states = emptyList() } else { - tiled = withContext(Dispatchers.Default) { tileable.mapTo(HashSet(tileable.size * 2), idOf) } + // Share the tile set's ID index instead of retaining a second hash set. + tiled = tileSet.ids() states = tileable } onTemplate(template, tileSet.tileSize) @@ -60,6 +61,16 @@ internal class ShapeTiler( tileSet.update(state) } + /** Rebuild draw order without re-evaluating the native/tile threshold. */ + suspend fun reorder(state: S) { + val updated = ArrayList() + tileSet.visitSources { updated.add(if (idOf(it) == idOf(state)) state else it) } + val template = tileSet.setShapes(updated) + states = updated + tiled = tileSet.ids() + onTemplate(template, tileSet.tileSize) + } + fun remove(id: String) { if (id !in tiled) return tiled = tiled - id diff --git a/src/main/java/com/mapconductor/core/tileserver/LocalTileServer.kt b/src/main/java/com/mapconductor/core/tileserver/LocalTileServer.kt index 33ec029..5fdee31 100644 --- a/src/main/java/com/mapconductor/core/tileserver/LocalTileServer.kt +++ b/src/main/java/com/mapconductor/core/tileserver/LocalTileServer.kt @@ -55,6 +55,7 @@ class LocalTileServer private constructor( private val running = AtomicBoolean(false) private val acceptThread = Thread { acceptLoop() } private val shedConnections = AtomicLong(0) + private val renderPermits = java.util.concurrent.Semaphore(MAX_CONCURRENT_RENDERS) // Bounded worker pool: excess connections beyond the queue capacity are // rejected and closed instead of spawning unbounded threads. @@ -65,7 +66,12 @@ class LocalTileServer private constructor( WORKER_KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, ArrayBlockingQueue(MAX_QUEUED_CONNECTIONS), - { runnable -> Thread(runnable).apply { isDaemon = true } }, + { runnable -> + Thread({ + android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND) + runnable.run() + }, "MapConductorTileWorker").apply { isDaemon = true } + }, ).apply { allowCoreThreadTimeOut(true) } @Volatile @@ -265,6 +271,9 @@ class LocalTileServer private constructor( val reader = BufferedReader(InputStreamReader(peek)) var handled = 0 while (handled < MAX_KEEP_ALIVE_REQUESTS) { + // Idle keep-alive clients must not occupy all request + // handlers while newer tiles wait in the connection queue. + client.soTimeout = if (handled == 0) SOCKET_TIMEOUT_MS else KEEP_ALIVE_IDLE_TIMEOUT_MS val request = readRequest(reader) ?: break if (!request.valid) { writeResponse(client, "400 Bad Request", "text/plain", "Bad request".toByteArray()) @@ -338,7 +347,19 @@ class LocalTileServer private constructor( break } - val outcome = resolveTile(path) { clientGone(client, peek) } + // Renderers check cancellation every few hundred shapes. + // A socket read per check turns 72万 circles into seconds + // of timeout waits. Poll the connection by elapsed time. + var lastProbeNs = System.nanoTime() + val cancelled = { + if (Thread.currentThread().isInterrupted || client.isClosed) true + else { + val now = System.nanoTime() + if (now - lastProbeNs < CANCELLATION_POLL_NS) false + else { lastProbeNs = now; clientGone(client, peek) } + } + } + val outcome = resolveTile(path, cancelled) // A tile that was abandoned mid-render comes back from the // provider looking empty, and the difference matters: an // "empty" answer is a picture the map would cache. Nothing @@ -570,10 +591,18 @@ class LocalTileServer private constructor( } val bytes = try { - provider.renderTile( - TileRequest(x = x, y = y, z = z, pixelRatio = key.pixelRatio), - isCancelled, - ) + // Connection handling and idle sockets are separate from the + // memory-intensive bitmap/PNG work. Keep only two renders live. + while (!renderPermits.tryAcquire(16, TimeUnit.MILLISECONDS)) { + if (isCancelled()) return TileOutcome.Failed + } + try { + if (isCancelled()) return TileOutcome.Failed + provider.renderTile( + TileRequest(x = x, y = y, z = z, pixelRatio = key.pixelRatio), + isCancelled, + ) + } finally { renderPermits.release() } } catch (error: Exception) { Log.w(TAG, "Tile render failed route=$routeId z=$z x=$x y=$y", error) return TileOutcome.Failed @@ -767,13 +796,14 @@ class LocalTileServer private constructor( private const val FILES_PREFIX = "files" private const val MAX_KEEP_ALIVE_REQUESTS = 200 private const val SOCKET_TIMEOUT_MS = 5000 + private const val KEEP_ALIVE_IDLE_TIMEOUT_MS = 250 + private const val CANCELLATION_POLL_NS = 50_000_000L + private const val MAX_CONCURRENT_RENDERS = 2 private const val MAX_HEADER_COUNT = 64 private const val MAX_LINE_LENGTH = 8192 - // Tile rendering is CPU-bound (canvas + PNG encode), so more workers than - // cores adds contention, not throughput. The deep queue absorbs request - // bursts (e.g. ArcGIS fetching several LODs during a zoom animation) - // without shedding connections. + // Serve independent connections without letting idle keep-alives block + // the viewport. Bitmap/PNG concurrency is limited separately above. private const val MAX_WORKER_THREADS = 8 private const val MAX_QUEUED_CONNECTIONS = 256 private const val WORKER_KEEP_ALIVE_SECONDS = 60L diff --git a/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt b/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt index fea1b6e..08f4f40 100644 --- a/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt +++ b/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt @@ -11,6 +11,7 @@ import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.runCurrent /** * In-place changes to a collected state have to reach the update handler. @@ -34,6 +35,44 @@ class OverlayCollectorMutationTest { private val window = 5.milliseconds + @Test + fun bulkRemovalStopsListeningAndReinsertionRestoresIt() = runTest { + val collector = collector(StandardTestDispatcher(testScheduler)) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add(it.label) } + val state = Thing("bulk", "before") + collector.flow.value = copyOverlayStates(mapOf(state.id to state)) + advanceUntilIdle() + state.label = "visible" + advanceUntilIdle() + collector.flow.value = copyOverlayStates(emptyMap()) + advanceUntilIdle() + state.label = "hidden" + advanceUntilIdle() + collector.flow.value = copyOverlayStates(mapOf(state.id to state)) + advanceUntilIdle() + state.label = "restored" + advanceUntilIdle() + assertEquals(listOf("visible", "restored"), seen) + } + + @Test + fun bulkPublicationKeepsPendingDirectAddsListening() = runTest { + val collector = collector(StandardTestDispatcher(testScheduler)) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add(it.id) } + val pending = Thing("single", "before") + val bulk = Thing("bulk", "before") + runCurrent() + collector.add(pending) + collector.flow.value = copyOverlayStates(mapOf(bulk.id to bulk)) + runCurrent() // Collect the bulk map before the direct add's debounce expires. + pending.label = "after" + advanceUntilIdle() + assertEquals(listOf("single"), seen) + assertEquals(setOf("single", "bulk"), collector.flow.value.keys) + } + private fun collector(dispatcher: TestDispatcher) = OverlayCollector( updateDebounce = window, diff --git a/src/test/java/com/mapconductor/core/OverlayStateMapsTest.kt b/src/test/java/com/mapconductor/core/OverlayStateMapsTest.kt new file mode 100644 index 0000000..1ea6fa9 --- /dev/null +++ b/src/test/java/com/mapconductor/core/OverlayStateMapsTest.kt @@ -0,0 +1,21 @@ +package com.mapconductor.core + +import org.junit.Assert.* +import org.junit.Test + +class OverlayStateMapsTest { + @Test + fun generationsKeepValuesAndInsertionOrderIndependent() { + val first = copyOverlayStates(mapOf("a" to Any(), "b" to Any(), "c" to Any())) + val second = copyOverlayStates(first) + second.remove("b") + second["d"] = Any() + val third = copyOverlayStates(second) + third["b"] = first.getValue("b") + assertEquals(listOf("a", "b", "c"), first.keys.toList()) + assertEquals(listOf("a", "c", "d"), second.keys.toList()) + assertEquals(listOf("a", "c", "d", "b"), third.keys.toList()) + assertSame(first["a"], second["a"]) + assertSame(second["a"], third["a"]) + } +} diff --git a/src/test/java/com/mapconductor/core/circle/CircleHitTest.kt b/src/test/java/com/mapconductor/core/circle/CircleHitTest.kt new file mode 100644 index 0000000..f957974 --- /dev/null +++ b/src/test/java/com/mapconductor/core/circle/CircleHitTest.kt @@ -0,0 +1,133 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.unit.dp +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.spherical.Spherical +import com.mapconductor.core.spherical.calculateMetersPerPixel +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import kotlin.random.Random + +/** + * 円のタップ判定。タイルで描いていてもネイティブで描いていても同じ(元の円に対して見る)。 + * + * 当たるのは「中心からの距離 ≤ 半径 + 縁幅 / 2(画面上の大きさ、カメラのズームで)」。カメラが + * 無ければ半径だけ。指の大きさは足さない(面はポリゴンと同じく中だけ)。複数当たれば実効 zIndex の + * 大きいもの、同じなら中心の近いもの。clickable = false は素通り。緯度の事前判定で結果は変わらない。 + * + * js-sdk-core の `CircleHit.test.mjs`、ios-sdk の `CircleHitTests` と 1 対 1 で対応する。 + */ +class CircleHitTest { + private val lat = 42.3550 + private val lng = -71.0600 + private val camera = MapCameraPosition(position = GeoPoint.fromLatLong(lat, lng), zoom = 16.0) + private val metersPerPixel = calculateMetersPerPixel(lat, 16.0) + + /** 北へ [meters] m(球面、Spherical.computeOffset と同じ)。 */ + private fun north( + meters: Double, + from: GeoPoint = GeoPoint.fromLatLong(lat, lng), + ) = Spherical.computeOffset(from, meters, 0.0) + + private fun circle( + id: String, + radius: Double = 10.0, + center: GeoPoint = GeoPoint.fromLatLong(lat, lng), + strokeWidth: Float = 1f, + zIndex: Int? = 0, + clickable: Boolean = true, + ) = CircleState( + center = center, + radiusMeters = radius, + id = id, + strokeWidth = strokeWidth.dp, + zIndex = zIndex, + clickable = clickable, + ) + + private fun managerWith(vararg states: CircleState): CircleManager = + CircleManager().apply { states.forEach { registerEntity(CircleEntity(circle = Unit, state = it)) } } + + @Test + fun `半径と縁幅の半分の内なら当たり、外なら外れ`() { + // 縁幅 10 dp: z16 で 5 px ≒ 8.9 m 外まで + val m = managerWith(circle("a", radius = 10.0, strokeWidth = 10f)) + val edge = 10.0 + 5.0 * metersPerPixel + assertEquals("a", m.find(north(edge - 0.2), camera)?.state?.id) + assertNull(m.find(north(edge + 0.2), camera)) + assertEquals("a", m.find(north(0.0), camera)?.state?.id) + } + + @Test + fun `カメラが無ければ半径だけ`() { + val m = managerWith(circle("a", radius = 10.0, strokeWidth = 10f)) + assertEquals("a", m.find(north(9.9))?.state?.id) + assertNull(m.find(north(10.1))) + assertNull(m.find(north(10.1), null)) + } + + @Test + fun `指の大きさは足さない`() { + // 縁幅 0: 半径のすぐ外は外れ(tapTolerance 14 dp ≒ 25 m を足していない) + val m = managerWith(circle("a", radius = 10.0, strokeWidth = 0f)) + assertNull(m.find(north(10.5), camera)) + } + + @Test + fun `同じ zIndex なら中心の近いもの`() { + val a = circle("a", radius = 20.0, center = north(-5.0)) + val b = circle("b", radius = 20.0, center = north(5.0)) + assertEquals("b", managerWith(a, b).find(north(3.0), camera)?.state?.id) + assertEquals("b", managerWith(b, a).find(north(3.0), camera)?.state?.id) + assertEquals("a", managerWith(a, b).find(north(-3.0), camera)?.state?.id) + } + + @Test + fun `zIndex の大きいものが先`() { + val near = circle("near", radius = 20.0, center = north(5.0), zIndex = 0) + val far = circle("far", radius = 20.0, center = north(-5.0), zIndex = 1) + assertEquals("far", managerWith(near, far).find(north(3.0), camera)?.state?.id) + // 未指定は中心からの自動値(南ほど大きい) + val autoNorth = circle("autoNorth", radius = 20.0, center = north(5.0), zIndex = null) + val autoSouth = circle("autoSouth", radius = 20.0, center = north(-5.0), zIndex = null) + assertEquals("autoSouth", managerWith(autoNorth, autoSouth).find(north(3.0), camera)?.state?.id) + } + + @Test + fun `clickable = false は素通りして下の円に当たる`() { + val top = circle("top", radius = 20.0, zIndex = 5, clickable = false) + val under = circle("under", radius = 20.0, zIndex = 0) + assertEquals("under", managerWith(top, under).find(north(1.0), camera)?.state?.id) + assertNull(managerWith(top).find(north(1.0), camera)) + } + + @Test + fun `緯度の事前判定で結果は変わらない`() { + val random = Random(42) + val states = + List(3000) { i -> + circle( + "c$i", + radius = 1.0 + random.nextDouble() * 14.0, + center = GeoPoint.fromLatLong(lat + (random.nextDouble() - 0.5) * 0.01, lng + (random.nextDouble() - 0.5) * 0.01), + strokeWidth = random.nextInt(0, 6).toFloat(), + zIndex = random.nextInt(0, 3), + ) + } + val m = managerWith(*states.toTypedArray()) + repeat(500) { + val tap = GeoPoint.fromLatLong(lat + (random.nextDouble() - 0.5) * 0.01, lng + (random.nextDouble() - 0.5) * 0.01) + val expected = + states + .map { it to Spherical.computeDistanceBetween(it.center, tap) } + .filter { (s, d) -> d <= s.radiusMeters + metersPerPixel * s.strokeWidth.value / 2.0 } + .sortedWith(compareByDescending> { it.first.zIndex!! }.thenBy { it.second }) + .firstOrNull() + ?.first + ?.id + assertEquals(expected, m.find(tap, camera)?.state?.id) + } + } +} diff --git a/src/test/java/com/mapconductor/core/circle/CircleTileFileStorageTest.kt b/src/test/java/com/mapconductor/core/circle/CircleTileFileStorageTest.kt new file mode 100644 index 0000000..8c6e349 --- /dev/null +++ b/src/test/java/com/mapconductor/core/circle/CircleTileFileStorageTest.kt @@ -0,0 +1,140 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.mapconductor.core.features.GeoPoint +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.IOException +import java.util.concurrent.CancellationException + +class CircleTileFileStorageTest { + @get:Rule val temporary = TemporaryFolder() + + private fun state( + index: Int = 0, + geodesic: Boolean = true, + ) = CircleState( + center = GeoPoint(42.0 + index * 0.00001, -71.0), radiusMeters = 500.0 + index, + geodesic = geodesic, fillColor = Color(0x802563EB), strokeColor = Color.Red, strokeWidth = 0.5.dp, + ) + + @Test fun exactGeometryRoundTripAcrossBlockBoundaries() { + val storage = + CircleTileFileStorage.create(temporary.root, 1025, { + if (it == 511) null else TileCircle.from(state(it, it % 2 == 0)) + }) + try { + assertEquals(16L + 80L * 1025, storage.cacheFile.length()) + for (index in listOf(0, 510, 512, 1023, 1024)) { + val source = state(index, index % 2 == 0) + val decoded = storage[index]!! + assertTrue(decoded.matches(source)) + assertArrayEquals(TileCircle.from(source)!!.bbox, storage.bbox(index), 0.0) + } + assertNull(storage[511]) + assertNull(storage.bbox(511)) + assertNull(storage[-1]) + assertNull(storage[1025]) + } finally { + storage.release() + } + assertTrue(temporary.root.listFiles()!!.isEmpty()) + } + + @Test fun blockCacheRemainsBoundedAndEvictedRecordsReload() { + val storage = CircleTileFileStorage.create(temporary.root, 512 * 60, { TileCircle.from(state(it / 512)) }) + try { + for (block in 0 until 60) assertTrue(storage[block * 512]!!.matches(state(block))) + assertTrue(storage.cachedBytes <= 48 * 512 * 80) + assertTrue(storage[0]!!.matches(state())) + assertEquals(48, storage.allocatedReadBuffers) + } finally { + storage.release() + } + } + + @Test fun snapshotsShareFilesWithoutSharingUpdatedValuesOrReaderLifetimes() { + val before = CircleTileFileStorage.create(temporary.root, 3, { TileCircle.from(state(it)) }) + val path = before.cacheFile + before.retain() // A tile request that outlives replacement of the model. + val changed = TileCircle.from(state(40, false))!! + val after = before.updated(listOf(0 to changed, 1 to null)) + before.release() // Retire the old renderer owner. + try { + assertTrue(before[0]!!.matches(state())) + assertTrue(after[0]!!.matches(state(40, false))) + assertNull(after[1]) + assertNotNull(before[1]) + after.release() + assertTrue(path.exists()) + } finally { + before.release() + } + assertFalse(path.exists()) + } + + @Test fun largeUpdateCompactsWithoutModifyingOldSnapshots() { + val before = CircleTileFileStorage.create(temporary.root, 2100, { TileCircle.from(state()) }) + val oldPath = before.cacheFile + val changed = TileCircle.from(state(20, false))!! + val after = before.updated(List(2050) { it to if (it == 10) null else changed }) as CircleTileFileStorage + try { + assertNotEquals(oldPath, after.cacheFile) + assertTrue(before[0]!!.matches(state())) + assertTrue(after[0]!!.matches(state(20, false))) + assertNull(after[10]) + assertTrue(after[2099]!!.matches(state())) + before.release() + assertFalse(oldPath.exists()) + assertNotNull(after[1]) + } finally { + after.release() + } + assertTrue(temporary.root.listFiles()!!.isEmpty()) + } + + @Test fun updatingExistingSlotsAtTheOverrideLimitStillSharesTheFile() { + val before = CircleTileFileStorage.create(temporary.root, 3000, { TileCircle.from(state()) }) + val changed = TileCircle.from(state(30, false))!! + val atLimit = before.updated(List(2048) { it to changed }) as CircleTileFileStorage + val after = atLimit.updated(listOf(0 to null, 1 to changed)) as CircleTileFileStorage + try { + assertEquals(before.cacheFile, after.cacheFile) + assertNull(after[0]) + assertNotNull(atLimit[0]) + assertTrue(after[1]!!.matches(state(30, false))) + } finally { before.release(); atLimit.release(); after.release() } + assertTrue(temporary.root.listFiles()!!.isEmpty()) + } + + @Test fun cancelledOrFailedWritesDeletePartialCacheFiles() { + val active = CircleTileFileStorage.create(temporary.root, 2, { TileCircle.from(state()) }) + try { + for (cancel in listOf(false, true)) { + try { + CircleTileFileStorage.create(temporary.root, 10000, { + if (!cancel && it == 600) throw IOException("simulated write source failure") + TileCircle.from(state()) + }, { if (cancel) throw CancellationException("cancelled") }) + fail("Expected write failure") + } catch (_: IOException) { + } catch (_: CancellationException) { + } + assertEquals(listOf(active.cacheFile), temporary.root.listFiles()!!.toList()) + assertNotNull(active[0]) + } + } finally { + active.release() + } + } +} diff --git a/src/test/java/com/mapconductor/core/circle/CircleTilingTest.kt b/src/test/java/com/mapconductor/core/circle/CircleTilingTest.kt new file mode 100644 index 0000000..ac398e5 --- /dev/null +++ b/src/test/java/com/mapconductor/core/circle/CircleTilingTest.kt @@ -0,0 +1,268 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.mapconductor.core.calculateZIndex +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.geometry.circleToRing +import com.mapconductor.core.polygon.toMercatorRing +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.math.abs +import kotlin.math.max + +/** + * 円のタイル描画を支える部品(画素を見ない部分)。 + * + * js-sdk-core の `CircleTiling.test.mjs`、ios-sdk の `CircleTilingTests` と 1 対 1 で対応する。 + * 画素そのものは端末で見る(androidTest の `CircleTileRendererDeviceTest`)。 + * + * - しきい値: 円の数だけ(頂点が無い)。判定はここ 1 か所。 + * - タイルにできないもの: 半径 0 以下・非有限、極(とメルカトルの外)にかかる、日付変更線をまたぐ。 + * geodesic はどちらでもタイルにできる。 + * - 外接範囲はネイティブの 128 角形(circleToRing)と同じ式。 + * - ズームごとの形: 直径 1 px 未満は点、メルカトルのゆがみが 0.25 px 以内なら真円、それ以外は 128 角形。 + */ +class CircleTilingTest { + private val boston = GeoPoint.fromLatLong(42.3555, -71.0605) + + private fun circle( + center: GeoPoint = boston, + radius: Double = 5.0, + geodesic: Boolean = true, + zIndex: Int? = null, + fill: Color = Color(0x80E8590C), + stroke: Color = Color(0xFFE8590C), + strokeWidth: Float = 1f, + ) = CircleState( + center = center, + radiusMeters = radius, + geodesic = geodesic, + zIndex = zIndex, + fillColor = fill, + strokeColor = stroke, + strokeWidth = strokeWidth.dp, + ) + + @Test + fun `円の数が届けばタイルにする`() { + val o = CircleTilingOptions.Default + assertFalse(o.shouldUseTiles(1999)) + assertFalse(o.shouldUseTiles(2000)) + assertTrue(o.shouldUseTiles(2001)) + assertFalse(CircleTilingOptions.Disabled.shouldUseTiles(1_000_000)) + assertTrue(CircleTilingOptions(minCircleCount = 3).shouldUseTiles(3)) + } + + @Test + fun `compact state preserves snapshot isolation and mutation notifications`() { + val state = circle() + var notifications = 0 + state.mutations.listen { notifications++ } + val before = state.radiusMeters + val snapshot = androidx.compose.runtime.snapshots.Snapshot.takeMutableSnapshot() + try { + snapshot.enter { + state.radiusMeters = before + 1 + state.extra = 42L + assertEquals(before + 1, state.radiusMeters, 0.0) + } + assertEquals(before, state.radiusMeters, 0.0) + snapshot.apply().check() + assertEquals(before + 1, state.radiusMeters, 0.0) + assertEquals(42L, state.extra) + assertEquals(2, notifications) + state.extra = 42L + assertEquals(2, notifications) + } finally { snapshot.dispose() } + } + + @Test + fun `change flags preserve independent readers and replacement states`() { + val state = circle() + val first = CircleEntity(Unit, state) + val original = first.fingerPrint + state.radiusMeters = 6.0 + assertEquals(2, first.changeMask(state)) + val second = CircleEntity(Unit, state) + assertEquals(0, second.changeMask(state)) + assertEquals(2, first.changeMask(state)) + assertEquals("legacy provider snapshot stays stable", original, first.fingerPrint) + assertEquals(0, second.changeMask(state.copy())) + assertTrue(second.changeMask(state.copy(fillColor = Color.Red)) != 0) + state.fillColor = Color.Red + assertTrue(first.changeMask(state) and 64 != 0) + assertTrue(second.changeMask(state) and 64 != 0) + } + + + @Test + fun `半径 0 以下・非有限はタイルにしない`() { + assertTrue(CircleTileSet.canTile(circle(radius = 0.1))) + assertFalse(CircleTileSet.canTile(circle(radius = 0.0))) + assertFalse(CircleTileSet.canTile(circle(radius = -1.0))) + assertFalse(CircleTileSet.canTile(circle(radius = Double.NaN))) + assertFalse(CircleTileSet.canTile(circle(radius = Double.POSITIVE_INFINITY))) + } + + @Test + fun `極・メルカトルの外・日付変更線にかかる円はタイルにしない`() { + // 北緯 85 度、半径 10 km: メルカトルの端(85.0511 度)を越える + assertFalse(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(85.0, 0.0), radius = 10_000.0))) + assertFalse(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(-85.0, 0.0), radius = 10_000.0))) + // 北緯 70 度、半径 200 km: 届かない + assertTrue(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(70.0, 20.0), radius = 200_000.0))) + // 日付変更線: 東経 179.99 度、半径 2 km は東へ 180 度を越える + assertFalse(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, 179.99), radius = 2_000.0))) + assertFalse(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, -179.99), radius = 2_000.0))) + assertTrue(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, 179.9), radius = 2_000.0))) + // 中心の経度は [-180, 180] に正規化して見る: 190 度は -170 度 + assertTrue(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, 190.0), radius = 2_000.0))) + // 局所平面(geodesic = false)でも同じ + assertFalse( + CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, 179.99), radius = 2_000.0, geodesic = false)), + ) + } + + @Test + fun `geodesic で極を含む円はタイルにしない`() { + // 北緯 60 度、半径 3400 km: 極(30 度 ≒ 3340 km 先)を含む + val c = circle(center = GeoPoint.fromLatLong(60.0, 0.0), radius = 3_400_000.0) + assertFalse(CircleTileSet.canTile(c)) + assertNull(TileCircle.from(c)) + } + + @Test + fun `外接範囲はネイティブの 128 角形と同じ`() { + for (geodesic in listOf(true, false)) { + for ((lat, radius) in listOf(42.3555 to 15.0, 42.3555 to 5_000.0, 70.0 to 200_000.0, -33.0 to 50_000.0)) { + val state = circle(center = GeoPoint.fromLatLong(lat, 10.0), radius = radius, geodesic = geodesic) + val tile = TileCircle.from(state)!! + val ring = toMercatorRing(circleToRing(state.center, radius, geodesic, 1024)) + var minX = Double.POSITIVE_INFINITY + var maxX = Double.NEGATIVE_INFINITY + var minY = Double.POSITIVE_INFINITY + var maxY = Double.NEGATIVE_INFINITY + for (i in ring.indices step 2) { + minX = minOf(minX, ring[i]) + maxX = maxOf(maxX, ring[i]) + minY = minOf(minY, ring[i + 1]) + maxY = maxOf(maxY, ring[i + 1]) + } + val width = maxX - minX + // 1024 角形の外接範囲と、幅の 0.1 % 以内で一致する(多角形は円の内側) + val tolerance = width * 1e-3 + val label = "geodesic=$geodesic lat=$lat r=$radius" + assertEquals(label, minX, tile.bbox[0], tolerance) + assertEquals(label, minY, tile.bbox[1], tolerance) + assertEquals(label, maxX, tile.bbox[2], tolerance) + assertEquals(label, maxY, tile.bbox[3], tolerance) + } + } + } + + @Test + fun `直径 1 px 未満は 1 px の点、その位置は中心の画素`() { + val tile = TileCircle.from(circle(radius = 5.0))!! + // z10: 世界 262144 px。ボストンで 1 px ≒ 113 m + val scale = 256.0 * (1 shl 10) + val shape = simplifyCircle(tile, scale) + assertTrue(shape is CircleTileShape.Dot) + shape as CircleTileShape.Dot + assertEquals(kotlin.math.floor(tile.x * scale), shape.x, 0.0) + assertEquals(kotlin.math.floor(tile.y * scale), shape.y, 0.0) + } + + @Test + fun `街路樹はどのズームでも真円で、半径の画素数はズーム 1 段で 2 倍`() { + val tile = TileCircle.from(circle(radius = 15.0))!! + var previous = 0.0 + for (z in 16..22) { + val shape = simplifyCircle(tile, 256.0 * (1 shl z)) + assertTrue("z$z", shape is CircleTileShape.Arc) + shape as CircleTileShape.Arc + if (previous > 0) assertEquals("z$z", previous * 2, shape.radius, 1e-9) + previous = shape.radius + } + // z22 で 15 m は 1 m ≒ 0.028 m/px … 半径 500 px 前後(ボストンの緯度で) + assertTrue("radius=$previous", previous in 400.0..800.0) + } + + @Test + fun `直径 4 px 未満は縁を描かない`() { + val tile = TileCircle.from(circle(radius = 5.0))!! + // z16 のボストンで 1 px ≒ 1.77 m: 半径 5 m は 2.8 px、直径 5.6 px + val z16 = simplifyCircle(tile, 256.0 * (1 shl 16)) as CircleTileShape.Arc + assertTrue(z16.outlined) + // z15: 直径 2.8 px + val z15 = simplifyCircle(tile, 256.0 * (1 shl 15)) as CircleTileShape.Arc + assertFalse(z15.outlined) + } + + @Test + fun `高緯度の大きな円は 128 角形で、点は circleToRing の点`() { + val state = circle(center = GeoPoint.fromLatLong(70.0, 20.0), radius = 200_000.0) + val tile = TileCircle.from(state)!! + val scale = 256.0 * (1 shl 6) + val shape = simplifyCircle(tile, scale) + assertTrue(shape is CircleTileShape.Ring) + shape as CircleTileShape.Ring + assertTrue(shape.outlined) + // 北側の半径が南側より長い(メルカトルのゆがみ) + val ryN = (tile.y - tile.northY) * scale + val ryS = (tile.southY - tile.y) * scale + assertTrue("ryN=$ryN ryS=$ryS", ryN - ryS > 1.0) + // 残った点は、ネイティブの 128 角形の点を画素格子に丸めたもの + val native = toMercatorRing(circleToRing(state.center, 200_000.0, true, 128)) + for (i in shape.points.indices step 2) { + val px = shape.points[i] + val py = shape.points[i + 1] + var nearest = Double.POSITIVE_INFINITY + for (j in native.indices step 2) { + nearest = minOf(nearest, max(abs(native[j] * scale - px), abs(native[j + 1] * scale - py))) + } + assertTrue("($px, $py) は 128 角形の点から $nearest px", nearest <= 0.5) + } + } + + @Test + fun `真円と 128 角形の切り替えはメルカトルのゆがみが 4 分の 1 px を越えたとき`() { + val tile = TileCircle.from(circle(center = GeoPoint.fromLatLong(42.3555, -71.0605), radius = 5_000.0))!! + // 5 km の円: 低いズームでは真円、高いズームでは 128 角形 + assertTrue(simplifyCircle(tile, 256.0 * (1 shl 8)) is CircleTileShape.Arc) + assertTrue(simplifyCircle(tile, 256.0 * (1 shl 16)) is CircleTileShape.Ring) + } + + @Test + fun `並びは実効 zIndex(未指定は中心からの自動値)`() { + val south = circle(center = GeoPoint.fromLatLong(42.0, -71.0)) + val north = circle(center = GeoPoint.fromLatLong(43.0, -71.0)) + assertEquals(calculateZIndex(south.center), effectiveZIndex(south)) + // 自動値では南が上(大きい) + assertTrue(effectiveZIndex(south) > effectiveZIndex(north)) + assertEquals(7, effectiveZIndex(circle(zIndex = 7))) + } + + @Test + fun `見えない縁(透明・幅 0)は余白にも数えない`() { + val noStroke = TileCircle.from(circle(stroke = Color.Transparent, strokeWidth = 6f))!! + assertFalse(noStroke.strokeVisible) + assertEquals(0f, CircleTilePainter.strokeWidth(noStroke)) + val zeroWidth = TileCircle.from(circle(strokeWidth = 0f))!! + assertEquals(0f, CircleTilePainter.strokeWidth(zeroWidth)) + val visible = TileCircle.from(circle(strokeWidth = 6f)) + assertNotNull(visible) + assertEquals(6f, CircleTilePainter.strokeWidth(visible!!)) + } + + @Test + fun `タイルのレイヤーは決まった id`() { + val state = circleTileRasterLayerState("http://127.0.0.1/tiles/c/256/1/{z}/{x}/{y}.png") + assertEquals(CIRCLE_TILE_LAYER_ID, state.id) + assertEquals("mc-circle-tiles", state.id) + } +} diff --git a/src/test/java/com/mapconductor/core/controller/OverlayStackingTest.kt b/src/test/java/com/mapconductor/core/controller/OverlayStackingTest.kt index fe6ac20..4a997b4 100644 --- a/src/test/java/com/mapconductor/core/controller/OverlayStackingTest.kt +++ b/src/test/java/com/mapconductor/core/controller/OverlayStackingTest.kt @@ -160,6 +160,62 @@ class ShapeTileStackingTest { } } +/** + * 円のタイルはサークルの帯の一番下: ポリゴン(タイル・ネイティブとも)の上、ネイティブの円・ + * ポリラインのタイル・マーカー(のタイル)の下。 + */ +class CircleTileStackingTest { + private val polygonTile = OverlayStacking.Key(OverlayKind.Polygon, Int.MIN_VALUE) + private val circleTile = OverlayStacking.Key(OverlayKind.Circle, Int.MIN_VALUE) + private val polylineTile = OverlayStacking.Key(OverlayKind.Polyline, Int.MIN_VALUE) + private val markerTile = OverlayStacking.Key(OverlayKind.Marker, Int.MIN_VALUE) + + @Test + fun `円のタイルはポリゴンの上、ネイティブの円・ポリラインのタイル・マーカーの下`() { + val keys = + listOf( + markerTile, + polylineTile, + OverlayStacking.Key(OverlayKind.Circle, -1_000_000), + circleTile, + OverlayStacking.Key(OverlayKind.Polygon, Int.MAX_VALUE), + polygonTile, + ) + assertEquals(keys.reversed(), keys.sorted()) + } + + @Test + fun `flatZIndex でも同じ順`() { + val circleTileZ = OverlayStacking.flatZIndex(OverlayKind.Circle, Int.MIN_VALUE) + assertTrue(circleTileZ > OverlayStacking.flatZIndex(OverlayKind.Polygon, Int.MAX_VALUE)) + assertTrue(circleTileZ > OverlayStacking.flatZIndex(OverlayKind.Polygon, Int.MIN_VALUE)) + assertTrue(circleTileZ < OverlayStacking.flatZIndex(OverlayKind.Circle, -1_000)) + assertTrue(circleTileZ < OverlayStacking.flatZIndex(OverlayKind.Polyline, Int.MIN_VALUE)) + assertTrue(circleTileZ < OverlayStacking.flatZIndex(OverlayKind.Marker, Int.MIN_VALUE)) + } + + @Test + fun `GL 系の層の並びでは、ポリゴンのタイルの上、ネイティブの円とポリラインのタイルの下へ入る`() { + val stack = OverlayLayerStack() + stack.put("raster-layer-mc-polygon-tiles", polygonTile) + stack.put("circle-layer", OverlayStacking.Key(OverlayKind.Circle)) + stack.put("raster-layer-mc-polyline-tiles", polylineTile) + stack.put("raster-layer-marker-tile-1", markerTile) + val layers = + listOf( + "water", + "raster-layer-mc-polygon-tiles", + "circle-layer", + "raster-layer-mc-polyline-tiles", + "raster-layer-marker-tile-1", + ) + assertEquals("circle-layer", stack.beforeId(layers, circleTile)) + // ネイティブの円が無ければポリラインのタイルの下 + stack.remove("circle-layer") + assertEquals("raster-layer-mc-polyline-tiles", stack.beforeId(layers - "circle-layer", circleTile)) + } +} + class OverlayLayerStackTest { @Test fun `台帳に無い層は無視し、スタイルを読み直しても同じ位置を返す`() { diff --git a/src/test/java/com/mapconductor/core/raster/RasterLayerCoexistenceTest.kt b/src/test/java/com/mapconductor/core/raster/RasterLayerCoexistenceTest.kt index 7b880fc..c3696d6 100644 --- a/src/test/java/com/mapconductor/core/raster/RasterLayerCoexistenceTest.kt +++ b/src/test/java/com/mapconductor/core/raster/RasterLayerCoexistenceTest.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.raster +import com.mapconductor.core.circle.circleTileRasterLayerState import com.mapconductor.core.polygon.polygonTileRasterLayerState import com.mapconductor.core.polyline.polylineTileRasterLayerState import kotlinx.coroutines.CoroutineScope @@ -9,8 +10,9 @@ import org.junit.Assert.assertEquals import org.junit.Test /** - * 1 枚の地図に載るラスターレイヤーは 4 系統ある。アプリの RasterLayer(add = composition)、 - * マーカータイル(marker-tile-*)、ポリゴンタイル(mc-polygon-tiles)、ポリラインタイル(mc-polyline-tiles)。 + * 1 枚の地図に載るラスターレイヤーは 5 系統ある。アプリの RasterLayer(add = composition)、 + * マーカータイル(marker-tile-*)、ポリゴンタイル(mc-polygon-tiles)、ポリラインタイル(mc-polyline-tiles)、 + * 円のタイル(mc-circle-tiles)。 * * js-sdk-core の `RasterLayerCoexistence.test.mjs`、ios-sdk の `RasterLayerCoexistenceTests` と * 1 対 1 で対応する。 @@ -59,31 +61,38 @@ class RasterLayerCoexistenceTest { ) @Test - fun `アプリの RasterLayer・マーカータイル・ポリゴンタイル・ポリラインタイルは互いを消さない`() = + fun `アプリの RasterLayer・マーカータイル・ポリゴンタイル・ポリラインタイル・円のタイルは互いを消さない`() = runBlocking { val onMap = mutableSetOf() val controller = Controller(Renderer(onMap)) controller.add(listOf(layer("relief"))) controller.upsert(polygonTileRasterLayerState("http://127.0.0.1/tiles/p/256/1/{z}/{x}/{y}.png")) + controller.upsert(circleTileRasterLayerState("http://127.0.0.1/tiles/c/256/1/{z}/{x}/{y}.png")) controller.upsert(polylineTileRasterLayerState("http://127.0.0.1/tiles/l/256/1/{z}/{x}/{y}.png")) controller.upsert(markerTiles(1)) - assertEquals(listOf("marker-tile-m", "mc-polygon-tiles", "mc-polyline-tiles", "relief"), onMap.sorted()) + val sdk = listOf("marker-tile-m", "mc-circle-tiles", "mc-polygon-tiles", "mc-polyline-tiles") + assertEquals(sdk + "relief", onMap.sorted()) // アプリの RasterLayer が変わっても、SDK のタイルは残る controller.add(listOf(layer("photo"))) - assertEquals(listOf("marker-tile-m", "mc-polygon-tiles", "mc-polyline-tiles", "photo"), onMap.sorted()) + assertEquals(sdk + "photo", onMap.sorted()) // マーカータイルの版が変わっても、ほかは残る controller.upsert(markerTiles(2)) - assertEquals(listOf("marker-tile-m", "mc-polygon-tiles", "mc-polyline-tiles", "photo"), onMap.sorted()) + assertEquals(sdk + "photo", onMap.sorted()) - // ポリラインタイルの版が変わっても、ほかは残る + // ポリラインタイル・円のタイルの版が変わっても、ほかは残る controller.upsert(polylineTileRasterLayerState("http://127.0.0.1/tiles/l/256/2/{z}/{x}/{y}.png")) - assertEquals(listOf("marker-tile-m", "mc-polygon-tiles", "mc-polyline-tiles", "photo"), onMap.sorted()) + controller.upsert(circleTileRasterLayerState("http://127.0.0.1/tiles/c/256/2/{z}/{x}/{y}.png")) + assertEquals(sdk + "photo", onMap.sorted()) // マーカータイルとポリラインタイルを外しても、ほかは残る controller.removeById("marker-tile-m") controller.removeById("mc-polyline-tiles") + assertEquals(listOf("mc-circle-tiles", "mc-polygon-tiles", "photo"), onMap.sorted()) + + // 円のタイルを外しても、ほかは残る + controller.removeById("mc-circle-tiles") assertEquals(listOf("mc-polygon-tiles", "photo"), onMap.sorted()) } } diff --git a/src/test/java/com/mapconductor/core/shapetile/ShapeGridIndexTest.kt b/src/test/java/com/mapconductor/core/shapetile/ShapeGridIndexTest.kt new file mode 100644 index 0000000..59bd9bb --- /dev/null +++ b/src/test/java/com/mapconductor/core/shapetile/ShapeGridIndexTest.kt @@ -0,0 +1,54 @@ +package com.mapconductor.core.shapetile + +import org.junit.Assert.assertArrayEquals +import org.junit.Test +import kotlin.random.Random + +class ShapeGridIndexTest { + @Test fun wideQueriesUseOccupiedGroupsInsteadOfScanningEveryShape() { + val boxes = List(4096) { i -> + val x = (i % 64 + 0.5) / 64.0 + val y = (i / 64 + 0.5) / 64.0 + doubleArrayOf(x, y, x + 0.000001, y + 0.000001) + } + val index = ShapeGridIndex.build(boxes.size) { boxes[it] } + var inspected = 0 + val actual = index.query({ inspected++; boxes[it] }, 0.1, 0.1, 0.1625, 0.1625) + val expected = boxes.indices.filter { i -> + val b = boxes[i] + b[0] <= 0.1625 && b[2] >= 0.1 && b[1] <= 0.1625 && b[3] >= 0.1 + }.toIntArray() + assertArrayEquals(expected, actual) + org.junit.Assert.assertTrue("inspected $inspected of ${boxes.size}", inspected < boxes.size / 4) + } + + @Test fun mixedSizesMatchBruteForceWithoutDuplicatesInDrawOrder() { + val random = Random(307) + val boxes = + List(4000) { i -> + if (i % 17 == 0) { + null + } else { + val x = random.nextDouble(-0.05, 1.05) + val y = random.nextDouble(0.0, 1.0) + val width = listOf(0.00001, 0.001, 0.01, 0.25)[i % 4] + doubleArrayOf(x, y, x + width, y + width) + } + } + val index = ShapeGridIndex.build(boxes.size) { boxes[it] } + for (z in listOf(0, 2, 4, 8, 12, 18)) { + repeat(30) { + val x = random.nextDouble(-0.1, 1.1) + val y = random.nextDouble(-0.1, 1.1) + val size = 1.0 / (1 shl z) + val expected = + boxes.indices + .filter { i -> + boxes[i]?.let { b -> b[0] <= x + size && b[2] >= x && b[1] <= y + size && b[3] >= y } == + true + }.toIntArray() + assertArrayEquals("zoom=$z", expected, index.query({ boxes[it] }, x, y, x + size, y + size)) + } + } + } +}