diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..671a084 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,6 @@ +{ + "attribution": { + "commit": "", + "pr": "" + } +} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 79f872f..f0d3bb0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -38,8 +38,29 @@ jobs: cache: 'gradle' - name: Build core and compose locally + env: + HEAD_REF: ${{ github.head_ref }} run: | - git clone --depth 1 https://github.com/MapConductor/android-sdk-core.git _core + # コア側に PR と同名のブランチがあるなら、そちらを組む。 + # + # ここを default ブランチ固定にしていると、**コアの未マージな変更に追随する + # PR は永久に赤いまま**になる。実際 CameraBearing をコアへ足したとき、 + # プロバイダ側の PR が 10 本まとめて Unresolved reference で落ちた。 + # コアが先にマージされるまで待つ、という運用は取り込み順の事故を呼ぶので、 + # 同名ブランチがあれば拾う形にしてある(無ければ従来どおり default)。 + clone_matching() { + repo="$1"; dir="$2" + url="https://github.com/MapConductor/$repo.git" + if [ -n "$HEAD_REF" ] && git ls-remote --exit-code --heads "$url" "$HEAD_REF" >/dev/null 2>&1; then + echo "$repo: matching branch $HEAD_REF" + git clone --depth 1 --branch "$HEAD_REF" "$url" "$dir" + else + echo "$repo: default branch" + git clone --depth 1 "$url" "$dir" + fi + } + + clone_matching android-sdk-core _core cd _core ./gradlew --no-daemon publishToMavenLocal cd .. @@ -53,7 +74,7 @@ jobs: } EOF - git clone --depth 1 https://github.com/MapConductor/android-sdk-compose.git _compose + clone_matching android-sdk-compose _compose cd _compose ./gradlew --no-daemon publishToMavenLocal cd .. diff --git a/api/android-for-openmobilemaps.api b/api/android-for-openmobilemaps.api index e3e5a8d..03c850b 100644 --- a/api/android-for-openmobilemaps.api +++ b/api/android-for-openmobilemaps.api @@ -94,6 +94,7 @@ public final class com.mapconductor.openmobilemaps.OpenMobileMapsDesign implemen public java.lang.Object getValue(); } public final class com.mapconductor.openmobilemaps.OpenMobileMapsDesign$Companion { + public final com.mapconductor.openmobilemaps.OpenMobileMapsDesign getNone(); public final com.mapconductor.openmobilemaps.OpenMobileMapsDesign getOpenStreetMap(); public final com.mapconductor.openmobilemaps.OpenMobileMapsDesign getOpenStreetMapJapan(); public final com.mapconductor.openmobilemaps.OpenMobileMapsDesign getOpenTopoMap(); @@ -120,8 +121,15 @@ public final class com.mapconductor.openmobilemaps.OpenMobileMapsGroundImageOver } public final class com.mapconductor.openmobilemaps.OpenMobileMapsLayers { public static final int DESIGN_INDEX; + public static final int RASTER_INDEX_FIRST; public static final int BELOW_INDEX_FIRST; + public static final int GROUND_IMAGE_INDEX_FIRST; + public static final int POLYGON_TILE_INDEX_FIRST; public static final int FIXED_INDEX_FIRST; + public static final int POLYLINE_TILE_INDEX_FIRST; + public static final int POLYLINE_INDEX; + public static final int MARKER_TILE_INDEX_FIRST; + public static final int ICON_INDEX; public com.mapconductor.openmobilemaps.OpenMobileMapsLayers(); public final io.openmobilemaps.mapscore.shared.map.layers.polygon.PolygonLayerInterface getPolygonFillLayer(); public final io.openmobilemaps.mapscore.shared.map.layers.line.LineLayerInterface getPolygonOutlineLayer(); @@ -132,9 +140,22 @@ public final class com.mapconductor.openmobilemaps.OpenMobileMapsLayers { public final void attachTo(io.openmobilemaps.mapscore.shared.map.MapInterface); public final void setDesignLayer(io.openmobilemaps.mapscore.shared.map.MapInterface, io.openmobilemaps.mapscore.shared.map.LayerInterface); public final io.openmobilemaps.mapscore.shared.map.LayerInterface insertBelowOverlays(io.openmobilemaps.mapscore.shared.map.MapInterface, io.openmobilemaps.mapscore.shared.map.LayerInterface); + public final io.openmobilemaps.mapscore.shared.map.LayerInterface insertGroundImage(io.openmobilemaps.mapscore.shared.map.MapInterface, io.openmobilemaps.mapscore.shared.map.LayerInterface); + public final io.openmobilemaps.mapscore.shared.map.LayerInterface insertPolygonTile(io.openmobilemaps.mapscore.shared.map.MapInterface, io.openmobilemaps.mapscore.shared.map.LayerInterface); + public final io.openmobilemaps.mapscore.shared.map.LayerInterface insertCircleTile(io.openmobilemaps.mapscore.shared.map.MapInterface, io.openmobilemaps.mapscore.shared.map.LayerInterface); + public final io.openmobilemaps.mapscore.shared.map.LayerInterface insertPolylineTile(io.openmobilemaps.mapscore.shared.map.MapInterface, io.openmobilemaps.mapscore.shared.map.LayerInterface); + public final io.openmobilemaps.mapscore.shared.map.LayerInterface insertMarkerTile(io.openmobilemaps.mapscore.shared.map.MapInterface, io.openmobilemaps.mapscore.shared.map.LayerInterface); public final void remove(io.openmobilemaps.mapscore.shared.map.MapInterface, io.openmobilemaps.mapscore.shared.map.LayerInterface); public final void clearAll(); } +final class com.mapconductor.openmobilemaps.OpenMobileMapsLayers$Band { + public final int getFirst(); + public final int getEnd(); + public final java.util.TreeSet getFree(); + public final int getNext(); + public final void setNext(int); + public final int take(); +} final class com.mapconductor.openmobilemaps.OpenMobileMapsLayers$Companion { } public interface com.mapconductor.openmobilemaps.OpenMobileMapsMapDesignTypeInterface extends com.mapconductor.core.map.MapDesignTypeInterface { @@ -199,12 +220,15 @@ public final class com.mapconductor.openmobilemaps.OpenMobileMapsMapViewHolder i public androidx.compose.ui.geometry.Offset toScreenOffset-x-9fifI(com.mapconductor.core.features.GeoPointInterface); public com.mapconductor.core.features.GeoPoint fromScreenOffsetSync-k-4lQ0M(long); public java.lang.Object fromScreenOffset-3MmeM6k(long, kotlin.coroutines.Continuation); + public com.mapconductor.core.projection.ProjectedPoint toProjectedPoint(com.mapconductor.core.features.GeoPointInterface); + public com.mapconductor.core.features.GeoPoint fromProjectedPoint(com.mapconductor.core.projection.ProjectedPoint); + public com.mapconductor.core.projection.MapCoordinateSystem getCoordinateSystem(); public java.lang.Object getMapView(); public java.lang.Object getMap(); } public final class com.mapconductor.openmobilemaps.OpenMobileMapsMapViewKt { public static final com.mapconductor.openmobilemaps.OpenMobileMapsViewState rememberOpenMobileMapsMapViewState(com.mapconductor.openmobilemaps.OpenMobileMapsMapDesignTypeInterface, com.mapconductor.core.map.MapCameraPositionInterface, androidx.compose.runtime.Composer, int, int); - public static final void OpenMobileMapsMapView(com.mapconductor.openmobilemaps.OpenMobileMapsViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function2, ? extends java.lang.Object>, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); + public static final void OpenMobileMapsMapView(com.mapconductor.openmobilemaps.OpenMobileMapsViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function2, ? extends java.lang.Object>, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, com.mapconductor.core.map.MapViewStyle, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); public static final com.mapconductor.openmobilemaps.OpenMobileMapsMapViewController createOpenMobileMapsViewController(com.mapconductor.openmobilemaps.OpenMobileMapsMapViewHolder, java.util.ArrayList, float, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.MutableMapServiceRegistry); } public final class com.mapconductor.openmobilemaps.OpenMobileMapsMapViewSaver extends com.mapconductor.compose.map.BaseMapViewSaver { @@ -231,6 +255,7 @@ public final class com.mapconductor.openmobilemaps.OpenMobileMapsMarkerOverlayRe public java.lang.Object onChange(java.util.List>, kotlin.coroutines.Continuation>); public java.lang.Object onRemove(java.util.List>, kotlin.coroutines.Continuation); public java.lang.Object onPostProcess(kotlin.coroutines.Continuation); + protected java.lang.Object applyDrawOrder(java.util.List>, kotlin.coroutines.Continuation); public void onDragSelectionChanged(com.mapconductor.core.marker.MarkerEntityInterface, com.mapconductor.core.marker.MarkerEntityInterface); public void onDragPositionChanged(com.mapconductor.core.features.GeoPointInterface); public final void onVisualTiltChanged(); @@ -294,6 +319,9 @@ public final class com.mapconductor.openmobilemaps.OpenMobileMapsTiltEmulation { public final kotlin.Pair shiftedCamera(com.mapconductor.core.map.MapCameraPosition); public final kotlin.Pair restoreLogicalCamera(com.mapconductor.core.features.GeoPointInterface, double, double, double); } +public final class com.mapconductor.openmobilemaps.OpenMobileMapsTiltEmulationKt { + public static final double OPEN_MOBILE_MAPS_VERTICAL_FOV; +} public final class com.mapconductor.openmobilemaps.OpenMobileMapsTouchListener extends io.openmobilemaps.mapscore.map.util.SimpleTouchInterface { public com.mapconductor.openmobilemaps.OpenMobileMapsTouchListener(com.mapconductor.openmobilemaps.OpenMobileMapsMapViewController); public boolean onTouchDown(io.openmobilemaps.mapscore.shared.graphics.common.Vec2F); @@ -339,11 +367,14 @@ public final class com.mapconductor.openmobilemaps.marker.OpenMobileMapsMarkerCo public void destroy(); public java.lang.Object update(java.lang.Object, kotlin.coroutines.Continuation); } +final class com.mapconductor.openmobilemaps.marker.OpenMobileMapsMarkerController$Companion { + public final long getTILE_REFRESH_COALESCE-UwyO8pc(); +} public final class com.mapconductor.openmobilemaps.tile.WebMercatorTileLayerConfig extends io.openmobilemaps.mapscore.shared.map.layers.tiled.Tiled2dMapLayerConfig { public static final double WORLD_WIDTH_METERS; public static final double HALF_WORLD; - public com.mapconductor.openmobilemaps.tile.WebMercatorTileLayerConfig(java.lang.String, java.lang.String, int, int, int, com.mapconductor.core.raster.TileScheme, int, boolean); - public com.mapconductor.openmobilemaps.tile.WebMercatorTileLayerConfig(java.lang.String, java.lang.String, int, int, int, com.mapconductor.core.raster.TileScheme, int, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.openmobilemaps.tile.WebMercatorTileLayerConfig(java.lang.String, java.lang.String, int, int, int, com.mapconductor.core.raster.TileScheme, int, boolean, boolean); + public com.mapconductor.openmobilemaps.tile.WebMercatorTileLayerConfig(java.lang.String, java.lang.String, int, int, int, com.mapconductor.core.raster.TileScheme, int, boolean, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); public int getCoordinateSystemIdentifier(); public java.lang.String getLayerName(); public java.lang.String getTileUrl(int, int, int, int); diff --git a/build.gradle.kts b/build.gradle.kts index 1c55aa2..cf5f23c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -29,6 +29,7 @@ android { defaultConfig { minSdk = project.property("minSdk").toString().toInt() + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles("consumer-rules.pro") } @@ -64,8 +65,9 @@ dependencies { // Open Mobile Maps SDK api(libs.openmobilemaps.mapscore) // ローカルタイルサーバの 404 を 204 へ書き換えるインターセプタで使う - // (mapscore の transitive 依存と同じ版。DataLoader が okhttp3.Interceptor を受け取る) - implementation("com.squareup.okhttp3:okhttp:5.1.0") + // (DataLoader が okhttp3.Interceptor を受け取る。mapscore 4.0.0 の transitive は + // 5.1.0 だが、ここで版をカタログに寄せて明示的に引き上げている) + implementation(libs.okhttp) // 集約ビルド(android-sdk)ではプロジェクト参照、単体ビルド(CI のリリース)では // Maven 座標で解決する。他プロバイダと同じ形。 @@ -76,8 +78,11 @@ dependencies { } testImplementation(libs.junit) -} + // Saver の保存 → 復元を実機の Bundle / Parcel で確かめる(SaverRoundTripTest)。 + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) +} // Set project version for NMCP plugin version = libraryVersion @@ -86,9 +91,10 @@ val libraryDescription = "Open Mobile Maps implementation for MapConductor unifi // Gradle 9.6 で `by tasks.registering` は非推奨(スクリプトコンパイルエラーになる)。 // googlemaps 等の既存モジュールは古い形のままなので、再コンパイル時に同じ問題が出る。 -val javadocJar = tasks.register("javadocJar") { - archiveClassifier.set("javadoc") -} +val javadocJar = + tasks.register("javadocJar") { + archiveClassifier.set("javadoc") + } afterEvaluate { publishing { diff --git a/gradle.properties b/gradle.properties index c018eb9..8b1a332 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,5 +8,5 @@ minSdk=26 javaVersion=17 jvmTarget=17 -libraryVersion=1.3.1 +libraryVersion=1.4.0 android.generateSyncIssueWhenLibraryConstraintsAreEnabled=false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 583b54c..01623f6 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,16 +1,19 @@ [versions] -composeLibs = "1.7.8" +composeLibs = "1.12.1" +# material3 は compose-ui とは別のバージョン系列。composeLibs(ui 系)を流用すると +# 存在しない material3:1.7.8 を要求してクラスパスごと解決に失敗する。 +material3 = "1.4.0" openmobilemaps = "4.0.0" -coroutines = "1.9.0" -agp = "9.2.1" -kotlin = "2.4.10" - -composeBom = "2025.02.00" -coreKtx = "1.16.0" -lifecycleRuntimeKtx = "2.8.7" -okhttp = "5.3.2" -playServicesMaps = "20.0.0" -activityCompose = "1.9.3" +coroutines = "1.11.0" +agp = "9.4.1" +kotlin = "2.4.20" + +composeBom = "2026.09.00" +coreKtx = "1.19.1" +lifecycleRuntimeKtx = "2.11.0" +okhttp = "5.5.1" +playServicesMaps = "20.1.0" +activityCompose = "1.13.0" ktLint = "14.2.0" junit = "4.13.2" @@ -37,7 +40,7 @@ play-services-maps = { module = "com.google.android.gms:play-services-maps", ver # Sample app androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } -androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "composeLibs" } +androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" } androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "composeLibs" } # Test diff --git a/settings.gradle.kts b/settings.gradle.kts index 949e00a..f1aa3ad 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -42,4 +42,3 @@ dependencyResolutionManagement { } rootProject.name = "android-for-openmobilemaps" - diff --git a/src/androidTest/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapViewSaverTest.kt b/src/androidTest/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapViewSaverTest.kt new file mode 100644 index 0000000..9a55e89 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapViewSaverTest.kt @@ -0,0 +1,85 @@ +package com.mapconductor.openmobilemaps + +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.SaverScope +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.AttributionRule +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapUISettings +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import android.os.Bundle +import android.os.Parcel + +/** + * 回転などの構成変更で state が [OpenMobileMapsMapViewSaver] を通って作り直されても、デザイン(id・ + * attributionRules ほか)と uiSettings・カメラが落ちないこと。Bundle は実機の Parcel を一度通す。 + */ +@RunWith(AndroidJUnit4::class) +class OpenMobileMapsMapViewSaverTest { + private val rules = + listOf(AttributionRule("© test"), AttributionRule("© ranged", minZoom = 3, maxZoom = 15)) + + private val camera = + MapCameraPosition( + position = GeoPoint(21.38, -157.93), + zoom = 12.0, + bearing = 20.0, + tilt = 10.0, + ) + + @Test + fun keepsDesignWithAttributionRules() { + val design = + OpenMobileMapsDesign( + id = "my-tiles", + tileUrlTemplate = "https://tiles.example.com/{z}/{x}/{y}.png", + tileSize = 512, + attributionRules = rules, + ) + val state = OpenMobileMapsViewState(mapDesignType = design, id = "omm-1", cameraPosition = camera) + state.uiSettings = MapUISettings(rotateGesture = false, tiltGesture = false) + + val restored = roundTrip(OpenMobileMapsMapViewSaver().createSaver(), state) + + assertEquals(design, restored.mapDesignType) + assertCommon(restored, "omm-1") + } + + @Test + fun keepsPresetDesignAndItsAttribution() { + val state = OpenMobileMapsViewState(mapDesignType = OpenMobileMapsDesign.OpenTopoMap, id = "omm-2") + val restored = roundTrip(OpenMobileMapsMapViewSaver().createSaver(), state) + assertEquals(OpenMobileMapsDesign.OpenTopoMap, restored.mapDesignType) + } + + private fun assertCommon(restored: com.mapconductor.core.map.MapViewStateInterface<*>, id: String) { + assertEquals(id, restored.id) + assertEquals(false, restored.uiSettings.rotateGesture) + assertEquals(false, restored.uiSettings.tiltGesture) + assertEquals(true, restored.uiSettings.scrollGesture) + assertEquals(12.0, restored.cameraPosition.zoom, 1e-9) + assertEquals(20.0, restored.cameraPosition.bearing, 1e-9) + assertEquals(21.38, restored.cameraPosition.position.latitude, 1e-9) + } + + private fun roundTrip( + saver: Saver, + value: T, + ): T { + val saved = with(saver) { SaverScope { true }.save(value) }!! + // 一度 Parcel に書いて読み戻す(プロセスが落ちたあとの復元と同じ経路)。 + val parcel = Parcel.obtain() + try { + parcel.writeBundle(saved) + parcel.setDataPosition(0) + return saver.restore(parcel.readBundle(javaClass.classLoader)!!)!! + } finally { + parcel.recycle() + } + } +} diff --git a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsDesign.kt b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsDesign.kt index c349a3b..486b15d 100644 --- a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsDesign.kt +++ b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsDesign.kt @@ -45,6 +45,9 @@ data class OpenMobileMapsDesign( */ private const val OSM_ATTRIBUTION = "© OpenStreetMap contributors" + /** ベースマップ無し。タイルレイヤを載せないので、アプリが載せたものだけが描かれる。 */ + val None = OpenMobileMapsDesign(id = "none", tileUrlTemplate = "") + val OpenStreetMap = OpenMobileMapsDesign( id = "osm", diff --git a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsLayers.kt b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsLayers.kt index 1cbd05a..cc973b8 100644 --- a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsLayers.kt +++ b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsLayers.kt @@ -19,10 +19,15 @@ import io.openmobilemaps.mapscore.shared.map.layers.polygon.PolygonLayerInterfac * ## 重ね順(下から) * * ``` - * 地図デザイン → ラスターレイヤ・グラウンドイメージ → ポリゴン塗り → ポリゴン輪郭 + * 地図デザイン → ラスターレイヤ・グラウンドイメージ → ポリゴンのタイル → ポリゴン塗り → ポリゴン輪郭 * → 円の塗り → 円の輪郭 → ポリライン → マーカー * ``` * + * すべてのプロバイダ共通の決まり([com.mapconductor.core.controller.OverlayStacking])。 + * ラスターとグラウンドイメージ、ポリゴン・マーカーのタイルは数が変わるので、帯ごとに索引の区間を分けて + * 割り当てる(以前はラスターとグラウンドイメージが同じ区間を空き番号から使い回していたため、 + * 追加・送り直しの順で上下が入れ替わった)。 + * * 他プロバイダのクリックのカスケード(marker → circle → groundImage → polyline → * polygon → map)と**上下が逆に見える**が、これは正しい。カスケードは「上にあるものから * 順に当たり判定する」ので、描画の重ね順を上から読むとカスケード順に一致する。 @@ -56,18 +61,33 @@ class OpenMobileMapsLayers { /** 地図デザインとオーバーレイ群の間に入っているレイヤ(ラスター / グラウンドイメージ)と、その索引。 */ private val belowOverlayIndices = mutableMapOf() - /** 外したレイヤの索引。使い回さないと、タイルの張り替えを繰り返すうちに索引が尽きる。 */ - private val freeBelowIndices = sortedSetOf() - private var nextBelowIndex = BELOW_INDEX_FIRST + /** 帯ごとの索引の割り当て。外したレイヤの索引は使い回す(張り替えを繰り返すうちに尽きないよう)。 */ + private class Band( + val first: Int, + val end: Int, + ) { + val free = sortedSetOf() + var next = first + + fun take(): Int = free.pollFirst() ?: next++.also { check(it < end) { "layer index band exhausted" } } + } - private val fixedLayers: List by lazy { + private val rasterBand = Band(RASTER_INDEX_FIRST, GROUND_IMAGE_INDEX_FIRST) + private val groundImageBand = Band(GROUND_IMAGE_INDEX_FIRST, POLYGON_TILE_INDEX_FIRST) + private val polygonTileBand = Band(POLYGON_TILE_INDEX_FIRST, FIXED_INDEX_FIRST) + private val circleTileBand = Band(FIXED_INDEX_FIRST + 2, FIXED_INDEX_FIRST + 6) + private val polylineTileBand = Band(POLYLINE_TILE_INDEX_FIRST, POLYLINE_INDEX) + private val markerTileBand = Band(MARKER_TILE_INDEX_FIRST, ICON_INDEX) + private val bandOfLayer = mutableMapOf() + + private val fixedLayers: List> by lazy { listOf( - polygonFillLayer.asLayerInterface(), - polygonOutlineLayer.asLayerInterface(), - circleFillLayer.asLayerInterface(), - circleOutlineLayer.asLayerInterface(), - polylineLayer.asLayerInterface(), - iconLayer.asLayerInterface(), + polygonFillLayer.asLayerInterface() to FIXED_INDEX_FIRST, + polygonOutlineLayer.asLayerInterface() to FIXED_INDEX_FIRST + 1, + circleFillLayer.asLayerInterface() to FIXED_INDEX_FIRST + 6, + circleOutlineLayer.asLayerInterface() to FIXED_INDEX_FIRST + 7, + polylineLayer.asLayerInterface() to POLYLINE_INDEX, + iconLayer.asLayerInterface() to ICON_INDEX, ) } @@ -90,8 +110,8 @@ class OpenMobileMapsLayers { polylineLayer.setLayerClickable(false) iconLayer.setLayerClickable(false) - fixedLayers.forEachIndexed { offset, layer -> - map.insertLayerAt(layer, FIXED_INDEX_FIRST + offset) + fixedLayers.forEach { (layer, index) -> + map.insertLayerAt(layer, index) } } @@ -114,9 +134,43 @@ class OpenMobileMapsLayers { fun insertBelowOverlays( map: MapInterface, layer: LayerInterface, + ): LayerInterface = insertInBand(map, layer, rasterBand) + + /** グラウンドイメージ: ラスターレイヤの上、ポリゴンの下。 */ + fun insertGroundImage( + map: MapInterface, + layer: LayerInterface, + ): LayerInterface = insertInBand(map, layer, groundImageBand) + + /** ポリゴンのタイル: ポリゴンの帯の一番下(グラウンドイメージの上、ポリゴン塗りの下)。 */ + fun insertPolygonTile( + map: MapInterface, + layer: LayerInterface, + ): LayerInterface = insertInBand(map, layer, polygonTileBand) + + /** ポリラインのタイル: ポリラインの帯の一番下(サークルの上、ネイティブのポリラインの下)。 */ + fun insertCircleTile(map: MapInterface, layer: LayerInterface): LayerInterface = + insertInBand(map, layer, circleTileBand) + + fun insertPolylineTile( + map: MapInterface, + layer: LayerInterface, + ): LayerInterface = insertInBand(map, layer, polylineTileBand) + + /** マーカーのタイル: ポリラインの上、マーカー(アイコン)の下。 */ + fun insertMarkerTile( + map: MapInterface, + layer: LayerInterface, + ): LayerInterface = insertInBand(map, layer, markerTileBand) + + private fun insertInBand( + map: MapInterface, + layer: LayerInterface, + band: Band, ): LayerInterface { - val index = freeBelowIndices.pollFirst() ?: nextBelowIndex++ + val index = band.take() belowOverlayIndices[layer] = index + bandOfLayer[layer] = band map.insertLayerAt(layer, index) return layer } @@ -125,7 +179,9 @@ class OpenMobileMapsLayers { map: MapInterface, layer: LayerInterface, ) { - belowOverlayIndices.remove(layer)?.let { freeBelowIndices.add(it) } + val index = belowOverlayIndices.remove(layer) + val band = bandOfLayer.remove(layer) + if (index != null && band != null) band.free.add(index) map.removeLayer(layer) } @@ -142,10 +198,32 @@ class OpenMobileMapsLayers { /** 地図デザイン。一番下。 */ const val DESIGN_INDEX = 0 - /** ラスターレイヤ・グラウンドイメージ。地図デザインとオーバーレイ群の間。 */ - const val BELOW_INDEX_FIRST = 1 + /** ラスターレイヤ。地図デザインの上。 */ + const val RASTER_INDEX_FIRST = 1 + + /** 以前の名前(ラスターとグラウンドイメージが共用していた区間の先頭)。 */ + @Suppress("unused") + const val BELOW_INDEX_FIRST = RASTER_INDEX_FIRST + + /** グラウンドイメージ。ラスターの上、ポリゴンの下。 */ + const val GROUND_IMAGE_INDEX_FIRST = 500 + + /** ポリゴンのタイル。グラウンドイメージの上、ポリゴン塗りの下。 */ + const val POLYGON_TILE_INDEX_FIRST = 900 /** 固定のオーバーレイ 6 種。下の枠を使い切らないよう十分離す。 */ const val FIXED_INDEX_FIRST = 1_000 + + /** ポリラインのタイル。サークルの上、ネイティブのポリラインの下。 */ + const val POLYLINE_TILE_INDEX_FIRST = FIXED_INDEX_FIRST + 10 + + /** ネイティブのポリライン(固定)。ポリラインのタイルの上。 */ + const val POLYLINE_INDEX = FIXED_INDEX_FIRST + 50 + + /** マーカーのタイル。ポリラインの上、マーカーの下。 */ + const val MARKER_TILE_INDEX_FIRST = 1_100 + + /** マーカー(アイコン)。一番上。 */ + const val ICON_INDEX = 2_000 } } diff --git a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapView.kt b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapView.kt index ff0bcd2..f205baa 100644 --- a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapView.kt +++ b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapView.kt @@ -18,7 +18,9 @@ import com.mapconductor.core.map.CameraRestriction import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.map.MapViewState +import com.mapconductor.core.map.MapViewStateBundle import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.map.MapViewStyle import com.mapconductor.core.map.MutableMapServiceRegistry import com.mapconductor.core.marker.MarkerEventControllerInterface import com.mapconductor.core.marker.MarkerManager @@ -62,7 +64,10 @@ class OpenMobileMapsViewState( cameraPosition: MapCameraPosition = MapCameraPosition.Default, ) : MapViewState(cameraPosition), OpenMobileMapsViewStateInterface { - private var controller: OpenMobileMapsMapViewController? = null + // Read through the base so that letting go of the controller there (MapViewBase + // does it when the map is torn down) leaves nothing behind here. + private val controller: OpenMobileMapsMapViewController? + get() = attachedMapController as? OpenMobileMapsMapViewController private var current: OpenMobileMapsMapDesignTypeInterface = mapDesignType override var mapDesignType: OpenMobileMapsMapDesignTypeInterface @@ -73,7 +78,6 @@ class OpenMobileMapsViewState( } internal fun setController(controller: OpenMobileMapsMapViewController) { - this.controller = controller attachController(controller) } @@ -98,6 +102,7 @@ class OpenMobileMapsMapViewSaver : BaseMapViewSaver() { bundle.putString("id", state.mapDesignType.id) bundle.putString("tileUrlTemplate", state.mapDesignType.tileUrlTemplate) bundle.putInt("tileSize", state.mapDesignType.tileSize) + MapViewStateBundle.putAttributionRules(bundle, state.mapDesignType.attributionRules) } override fun createState( @@ -114,6 +119,7 @@ class OpenMobileMapsMapViewSaver : BaseMapViewSaver() { mapDesignBundle?.getString("tileUrlTemplate") ?: OpenMobileMapsDesign.OpenStreetMap.tileUrlTemplate, tileSize = mapDesignBundle?.getInt("tileSize")?.takeIf { it > 0 } ?: 256, + attributionRules = MapViewStateBundle.getAttributionRules(mapDesignBundle), ), cameraPosition = cameraPosition, ) @@ -162,6 +168,15 @@ fun OpenMobileMapsMapView( onCameraMoveStart: OnCameraMoveHandler? = null, onCameraMove: OnCameraMoveHandler? = null, onCameraMoveEnd: OnCameraMoveHandler? = null, + /** + * How the map looks, when the app states it rather than naming a design. + * + * A vector style *is* the basemap. `com.mapconductor:vectorstyle` builds + * one; what happens underneath depends on this backend and the app does + * not have to know. + */ + style: MapViewStyle? = null, + onStyleDiagnostics: ((List) -> Unit)? = null, content: (@Composable OpenMobileMapsMapViewScope.() -> Unit)? = null, ) { val context = LocalContext.current @@ -265,6 +280,18 @@ fun OpenMobileMapsMapView( true } }, + style = style, + onStyleDiagnostics = onStyleDiagnostics, + // registerLifecycle() put the MapView on the Activity's lifecycle, and + // its own onDestroy() does not take it off again: left there, the + // Activity keeps every map the user switched away from (and through + // its callbacks the controller with every overlay). Take it off first + // so the Activity's ON_DESTROY cannot destroy it a second time. + onDestroyMapView = { surface -> + lifecycleOwner.lifecycle.removeObserver(surface.mapView) + surface.mapView.onPause() + surface.mapView.onDestroy() + }, content = content, ) } diff --git a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapViewController.kt b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapViewController.kt index 3985ce3..4fd654f 100644 --- a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapViewController.kt +++ b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsMapViewController.kt @@ -1,11 +1,18 @@ package com.mapconductor.openmobilemaps +import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID +import com.mapconductor.core.circle.CircleTiler +import com.mapconductor.core.circle.circleTileRasterLayerState 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.CameraBearing +import com.mapconductor.core.map.CameraPaddingEmulation import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCapabilityStatus +import com.mapconductor.core.map.MapPaddings +import com.mapconductor.core.map.MapPaddingsInterface import com.mapconductor.core.map.MapUISettings import com.mapconductor.core.map.MutableMapServiceRegistry import com.mapconductor.core.map.VisibleRegion @@ -18,6 +25,12 @@ import com.mapconductor.core.marker.MarkerRenderingStrategyInterface import com.mapconductor.core.marker.OnMarkerEventHandler import com.mapconductor.core.marker.StrategyMarkerController import com.mapconductor.core.marker.dispatchGeoMarkerClick +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.polygon.PolygonTiler +import com.mapconductor.core.polygon.polygonTileRasterLayerState +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID +import com.mapconductor.core.polyline.PolylineTiler +import com.mapconductor.core.polyline.polylineTileRasterLayerState import com.mapconductor.openmobilemaps.marker.OpenMobileMapsMarkerController import com.mapconductor.openmobilemaps.tile.WebMercatorTileLayerConfig import com.mapconductor.openmobilemaps.zoom.ZoomAltitudeConverter @@ -96,6 +109,15 @@ class OpenMobileMapsMapViewController( */ private var logicalTilt: Double = 0.0 + /** + * 今カメラに付いているパディング(dp)。 + * + * SDK の `setPaddingLeft` などは使わない。付けた瞬間に画面がずれ、こちらで刻んでいる + * アニメーションにも載らないため。代わりにカメラ中心をずらして再現し + * ([CameraPaddingEmulation])、読むときに元へ戻すためにここで覚えておく。 + */ + private var cameraPaddings: MapPaddingsInterface = MapPaddings.Zeros + /** 直近に適用した tilt。アイコンの引き伸ばしを毎フレーム付け直さないための番人。 */ private var lastAppliedTilt: Double = 0.0 @@ -163,11 +185,54 @@ class OpenMobileMapsMapViewController( .forEach { rasterLayerController.removeById(it.state.id) } } } + + // Many polygons are drawn as raster tiles, shown through the same RasterLayer + // controller as the marker tiles (upsert / removeById, never the app's layers). + polygonController.tiler = + PolygonTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(polygonTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(POLYGON_TILE_LAYER_ID) + } + } + } + + // Many polylines too: the same raster layer path, in the polyline band. + polylineController.tiler = + PolylineTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(polylineTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(POLYLINE_TILE_LAYER_ID) + } + } + } + circleController.tiler = + CircleTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(circleTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(CIRCLE_TILE_LAYER_ID) + } + } + } } + /** + * 地図に挿したタッチリスナー。SDK はネイティブ側から JNI の global 参照で掴むので、 + * [destroy] で外さないとこのコントローラ(と全オーバーレイ)がプロセスに残る。 + */ + private var touchListener: OpenMobileMapsTouchListener? = null + /** SDK のイベントをコアの受け口へ転送する。 */ fun installListeners() { - holder.map.getTouchHandler().insertListener(OpenMobileMapsTouchListener(this), 0) + val listener = OpenMobileMapsTouchListener(this) + touchListener = listener + holder.map.getTouchHandler().insertListener(listener, 0) holder.map.getCamera().addListener(cameraListener) notifyMapInitialized() } @@ -243,13 +308,25 @@ class OpenMobileMapsMapViewController( val (center, zoom) = OpenMobileMapsTiltEmulation.restoreLogicalCamera(rawCenter, rawZoom, bearing, logicalTilt) - return MapCameraPosition(position = center, zoom = zoom, bearing = bearing, tilt = logicalTilt) + return CameraPaddingEmulation.fromNativeCamera( + MapCameraPosition(position = center, zoom = zoom, bearing = bearing, tilt = logicalTilt), + cameraPaddings, + OPEN_MOBILE_MAPS_VERTICAL_FOV, + viewportHeightDp(), + ) + } + + /** 地図の高さ(dp)。 */ + private fun viewportHeightDp(): Double { + val density = holder.mapView.resources.displayMetrics.density + return holder.mapView.height / density.toDouble() } private fun visibleRegion(): VisibleRegion? = holder.buildVisibleRegion() override fun moveCamera(position: MapCameraPosition) { cancelCameraAnimation() + position.paddings?.let { cameraPaddings = it } applyCamera(position) } @@ -272,10 +349,14 @@ class OpenMobileMapsMapViewController( ) { cancelCameraAnimation() if (duration <= 0L) { + position.paddings?.let { cameraPaddings = it } applyCamera(position) return } + // 先に新しいパディングへ切り替えてから始点を読む。始点も新しいパディングで + // 表した位置になるので、最初のフレームで画面が跳ばない。 + position.paddings?.let { cameraPaddings = it } val from = readLogicalCamera() cameraAnimationJob = mainCoroutine.launch { @@ -329,7 +410,13 @@ class OpenMobileMapsMapViewController( .forEach { it.onVisualTiltChanged() } } - val (center, zoom) = OpenMobileMapsTiltEmulation.shiftedCamera(position) + val native = + CameraPaddingEmulation.toNativeCamera( + position.copy(paddings = cameraPaddings), + OPEN_MOBILE_MAPS_VERTICAL_FOV, + viewportHeightDp(), + ) + val (center, zoom) = OpenMobileMapsTiltEmulation.shiftedCamera(native) val camera = holder.map.getCamera() camera.moveToCenterPositionZoom(center.toOmmCoord(), ZOOM_CONVERTER.toNativeZoom(zoom), false) // 方位が変わっていないなら触らない。毎フレーム呼ぶと SDK 側で無駄な @@ -384,6 +471,8 @@ class OpenMobileMapsMapViewController( groundImageController.clear() rasterLayerController.clear() layers.clearAll() + // 拡張モジュール(クラスタリングなど)が登録した Strategy のマーカーも消す。 + clearStrategyMarkerControllers() } // ── 地図デザイン ──────────────────────────────────────────────────── @@ -391,6 +480,12 @@ class OpenMobileMapsMapViewController( fun setMapDesignType(value: OpenMobileMapsMapDesignTypeInterface) { if (currentDesign?.getValue() == value.getValue()) return currentDesign = value + // テンプレートが無ければレイヤも無し: 何も描かないデザイン。 + if (value.tileUrlTemplate.isEmpty()) { + layers.setDesignLayer(holder.map, null) + mapDesignTypeChangeListener?.invoke(value) + return + } val config = WebMercatorTileLayerConfig( layerName = "design-${value.id}", @@ -460,6 +555,8 @@ class OpenMobileMapsMapViewController( override fun destroy() { cancelCameraAnimation() runCatching { holder.map.getCamera().removeListener(cameraListener) } + touchListener?.let { listener -> runCatching { holder.map.getTouchHandler().removeListener(listener) } } + touchListener = null removeDragTouchInterceptor() super.destroy() } @@ -475,20 +572,20 @@ class OpenMobileMapsMapViewController( companion object { /** - * 方位の符号。**SDK は MapConductor と逆回りである。** + * 方位の符号。**SDK の `setRotation` は MapConductor の bearing と同じ向き** + * (どちらも「地図を時計回りに回す量」)なので、変換は恒等になる。 * - * MapConductor の bearing は Google 準拠で「カメラが向いている方位を北から時計回りに測る」。 - * SDK の `setRotation` は地図を反時計回りに回す量なので、符号を反転する。 - * 反転を忘れると bearing 270 の地図が 90 として描かれ、**ちょうど 180 度ずれる** - * (tilt ページを MapLibre と並べて気づいた。単独で見ると「回っている」ので正しく見える)。 + * ここは机上ではなく端末で決めた値である。基準は「MapLibre と並べて同じ向きに + * 描かれること」で、MapLibre 側が heading 系(bearing の符号反転)に変わったのに + * 合わせてこちらも反転させてある。**符号を触ったら必ず tilt ページを MapLibre と + * 並べて確認すること。** 単独で見ると「回っている」ので正しく見えてしまう。 */ - internal fun nativeRotationFromBearing(bearing: Double): Float = (-bearing).toFloat() + internal fun nativeRotationFromBearing(bearing: Double): Float = + CameraBearing.toNativeRotation(bearing).toFloat() /** SDK の回転角 → MapConductor の bearing(0 以上 360 未満)。 */ - internal fun bearingFromNativeRotation(rotation: Float): Double { - val bearing = -rotation.toDouble() % 360.0 - return if (bearing < 0) bearing + 360.0 else bearing - } + internal fun bearingFromNativeRotation(rotation: Float): Double = + CameraBearing.bearingFromNativeRotation(rotation.toDouble()) /** * ズームの往復換算。 diff --git a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsOverlays.kt b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsOverlays.kt index 8f7939c..3774910 100644 --- a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsOverlays.kt +++ b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsOverlays.kt @@ -20,10 +20,14 @@ import com.mapconductor.core.groundimage.GroundImageState import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.marker.AbstractMarkerOverlayRenderer import com.mapconductor.core.marker.BitmapIcon +import com.mapconductor.core.marker.MarkerDrawOrder import com.mapconductor.core.marker.MarkerEntityInterface import com.mapconductor.core.marker.MarkerManager import com.mapconductor.core.marker.MarkerOverlayRendererInterface import com.mapconductor.core.polygon.AbstractPolygonOverlayRenderer +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID import com.mapconductor.core.polygon.PolygonController import com.mapconductor.core.polygon.PolygonEntityInterface import com.mapconductor.core.polygon.PolygonManagerInterface @@ -191,6 +195,11 @@ class OpenMobileMapsMarkerOverlayRenderer( applyIcons() } + // 地図が回ったら、今の向きで並べ直して流し直す。 + override suspend fun applyDrawOrder(entities: List>) { + applyIcons() + } + override fun onDragSelectionChanged( previous: MarkerEntityInterface?, current: MarkerEntityInterface?, @@ -209,13 +218,17 @@ class OpenMobileMapsMarkerOverlayRenderer( * * `tiling` が立っている entity は [com.mapconductor.core.marker.MarkerTileRenderer] が * ラスタータイルとして描くので、ここでは除く(除かないと同じマーカーが二重に出る)。 + * + * アイコンレイヤはリストの後ろほど上に描くので、[MarkerDrawOrder] の小さい順に並べる + * (zIndex が大きいほど、同じなら画面で下ほど上)。マネージャの順(足した順)に任せない。 */ private fun applyIcons() { val icons = markerManager .allEntities() .asSequence() - .filter { !it.tiling && it.visible } + .filter { !it.tiling && it.visible && it.marker != null } + .sortedBy { drawOrderOf(it.state) } .mapNotNull { it.marker } .toCollection(ArrayList()) iconLayer.setIcons(icons) @@ -406,8 +419,19 @@ class OpenMobileMapsPolylineOverlayRenderer( override suspend fun removePolyline(entity: PolylineEntityInterface) = Unit override suspend fun onPostProcess() { - lineLayer.setLines(polylineManager.allEntities().flatMapTo(ArrayList()) { it.polyline.orEmpty() }) + // 帯の中は zIndex の順(同じなら渡された順)。タイルで描く線(線の無い entity)は飛ばす。 + lineLayer.setLines( + polylineManager + .allEntities() + .sortedBy { it.state.zIndex } + .flatMapTo(ArrayList()) { nativePolylineOf(it).orEmpty() }, + ) } + + @Suppress("USELESS_CAST") + private fun nativePolylineOf( + entity: PolylineEntityInterface, + ): OpenMobileMapsActualPolyline? = entity.polyline as OpenMobileMapsActualPolyline? } // ── ポリゴン ────────────────────────────────────────────────────────────── @@ -475,13 +499,25 @@ class OpenMobileMapsPolygonOverlayRenderer( override suspend fun removePolygon(entity: PolygonEntityInterface) = Unit override suspend fun onPostProcess() { - val entities = polygonManager.allEntities() + // Polygons drawn as tiles (PolygonController.tiler) stay in the manager + // for taps with no native polygon. + // 帯の中は zIndex の順(同じなら渡された順)。 + val entities = + polygonManager + .allEntities() + .sortedBy { it.state.zIndex } + .mapNotNull { nativePolygonOf(it) } // add / addAll ではなく setPolygons を使うこと。4.0 の PolygonLayer は // 原点(第 2 引数)を持つようになっていて、setPolygons を一度も通っていない // レイヤに add すると**何も描かれない**(例外も警告も出ない)。 - fillLayer.setPolygons(entities.flatMapTo(ArrayList()) { it.polygon.fills }, RENDER_ORIGIN) - outlineLayer.setLines(entities.flatMapTo(ArrayList()) { it.polygon.outlines }) + fillLayer.setPolygons(entities.flatMapTo(ArrayList()) { it.fills }, RENDER_ORIGIN) + outlineLayer.setLines(entities.flatMapTo(ArrayList()) { it.outlines }) } + + @Suppress("USELESS_CAST") + private fun nativePolygonOf( + entity: PolygonEntityInterface, + ): OpenMobileMapsActualPolygon? = entity.polygon as OpenMobileMapsActualPolygon? } // ── 円 ──────────────────────────────────────────────────────────────────── @@ -530,7 +566,8 @@ class OpenMobileMapsCircleOverlayRenderer( override suspend fun removeCircle(entity: CircleEntityInterface) = Unit override suspend fun onPostProcess() { - val entities = circleManager.allEntities() + // Tiled circles have no native fill or outline handle. + val entities = circleManager.nativeEntities().sortedBy { it.state.zIndex ?: 0 } fillLayer.setPolygons(entities.flatMapTo(ArrayList()) { it.circle.fills }, RENDER_ORIGIN) outlineLayer.setLines(entities.flatMapTo(ArrayList()) { it.circle.outlines }) } @@ -583,7 +620,7 @@ class OpenMobileMapsGroundImageOverlayRenderer( return OpenMobileMapsActualGroundImage( layer = layer, - layerInterface = layers.insertBelowOverlays(holder.map, layer.asLayerInterface()), + layerInterface = layers.insertGroundImage(holder.map, layer.asLayerInterface()), ) } @@ -674,6 +711,9 @@ class OpenMobileMapsRasterLayerOverlayRenderer( // ラスターオーバーレイは透過前提なので、粗い親レベルを重ね描きしない numDrawPreviousLayers = 0, maskTile = true, + // 切り捨てだと、ズーム 17.75 で z17 を 1.68 倍に伸ばして出す。MapLibre 系は z18 を + // 0.84 倍で出すので、マーカータイルのアイコンとラベルが 2 倍違って見えた。 + roundToNearestLevel = true, ) val layer = Tiled2dMapRasterLayerInterface.create(config, loaders) layer.setAlpha(state.opacity) @@ -682,7 +722,21 @@ class OpenMobileMapsRasterLayerOverlayRenderer( } return OpenMobileMapsActualRasterLayer( layer = layer, - layerInterface = layers.insertBelowOverlays(holder.map, layer.asLayerInterface()), + layerInterface = + if (state.id.startsWith("marker-tile-")) { + // マーカーのタイルはマーカーの帯(ポリラインの上)。 + layers.insertMarkerTile(holder.map, layer.asLayerInterface()) + } else if (state.id == POLYGON_TILE_LAYER_ID) { + // ポリゴンのタイルはポリゴンの帯の一番下(画像になったポリゴンであって、地図の画像ではない)。 + layers.insertPolygonTile(holder.map, layer.asLayerInterface()) + } else if (state.id == CIRCLE_TILE_LAYER_ID) { + layers.insertCircleTile(holder.map, layer.asLayerInterface()) + } else if (state.id == POLYLINE_TILE_LAYER_ID) { + // ポリラインのタイルはポリラインの帯の一番下(サークルの上、ネイティブのポリラインの下)。 + layers.insertPolylineTile(holder.map, layer.asLayerInterface()) + } else { + layers.insertBelowOverlays(holder.map, layer.asLayerInterface()) + }, ) } } diff --git a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsTiltEmulation.kt b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsTiltEmulation.kt index 497bf18..2c5a6a9 100644 --- a/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsTiltEmulation.kt +++ b/src/main/java/com/mapconductor/openmobilemaps/OpenMobileMapsTiltEmulation.kt @@ -2,6 +2,7 @@ package com.mapconductor.openmobilemaps import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.map.CameraBearing import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.spherical.Spherical import com.mapconductor.core.zoom.AbstractZoomAltitudeConverter @@ -10,6 +11,14 @@ import kotlin.math.abs import kotlin.math.cos import kotlin.math.tan +/** + * OpenMobileMaps のカメラの縦方向の視野角(度)。SDK のカメラは 2D なので、傾きは + * ビューを X 軸まわりに回して見せている([OpenMobileMapsMapSurface])。その遠近は + * ほとんど付かず、TB520FU で傾けたときの縦の間隔は cos(tilt) 倍と 0.3% 以内で + * 一致した。遠近なしの傾きとして 0 と表す。 + */ +internal const val OPEN_MOBILE_MAPS_VERTICAL_FOV = 0.0 + /** * Open Mobile Maps の 2D カメラ向けの tilt 擬似表現。 * @@ -53,7 +62,9 @@ internal object OpenMobileMapsTiltEmulation { val tiltAbsRad = Math.toRadians(tiltAbsDeg) val altitude = altitudeFor(position.zoom, position.position.latitude) val distanceForward = altitude * cos(tiltAbsRad) * tan(tiltAbsRad) * TARGET_DISTANCE_SCALE - val target = Spherical.computeOffset(position.position, distanceForward, position.bearing) + val target = + Spherical + .computeOffset(position.position, distanceForward, CameraBearing.toNativeHeading(position.bearing)) return target to zoom } @@ -71,7 +82,11 @@ internal object OpenMobileMapsTiltEmulation { val tiltAbsRad = Math.toRadians(tiltAbsDeg) val altitude = altitudeFor(originalZoom, center.latitude) val distanceBackward = altitude * cos(tiltAbsRad) * tan(tiltAbsRad) * TARGET_DISTANCE_SCALE - val originalPosition: GeoPoint = Spherical.computeOffset(center, distanceBackward, bearing + 180.0) + val originalPosition: GeoPoint = + Spherical.computeOffset( + center, distanceBackward, + CameraBearing.toNativeHeading(bearing) + 180.0, + ) return originalPosition to originalZoom } diff --git a/src/main/java/com/mapconductor/openmobilemaps/marker/OpenMobileMapsMarkerController.kt b/src/main/java/com/mapconductor/openmobilemaps/marker/OpenMobileMapsMarkerController.kt index 4e9e90b..6f17c67 100644 --- a/src/main/java/com/mapconductor/openmobilemaps/marker/OpenMobileMapsMarkerController.kt +++ b/src/main/java/com/mapconductor/openmobilemaps/marker/OpenMobileMapsMarkerController.kt @@ -21,8 +21,11 @@ import com.mapconductor.core.tileserver.TileServerRegistry import com.mapconductor.openmobilemaps.OpenMobileMapsActualMarker import com.mapconductor.openmobilemaps.OpenMobileMapsMarkerOverlayRenderer 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.sync.withPermit @@ -123,11 +126,12 @@ class OpenMobileMapsMarkerController( if (currentFinger == prevFinger) return semaphore.withPermit { + // 件数だけが要る。allEntities() は全件の写しを作るので、ラベルの付け替えのように + // 数十本が続けて変わると、そのたびに 14 万件を写すことになる。 val tilingEnabled = - markerTiling.enabled && markerManager.allEntities().size >= markerManager.minMarkerCount + markerTiling.enabled && markerManager.getMemoryStats().entityCount >= markerManager.minMarkerCount val wantsTiled = tilingEnabled && !state.draggable && state.getAnimation() == null val wasTiled = tiledMarkerIds.contains(state.id) - val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon if (wantsTiled) { if (!wasTiled) { @@ -145,14 +149,19 @@ class OpenMobileMapsMarkerController( tiling = true, ), ) - renderer.onPostProcess() - syncTiledOverlay() + // タイル担当のままなら、ネイティブのマーカーには何も起きていない。onPostProcess は + // 全件を写してネイティブ分を描き直すので(14 万件で 1 回 50ms)、ネイティブから + // タイルへ移ったときだけ呼ぶ。 + if (!wasTiled) renderer.onPostProcess() + scheduleTileRefresh() return@withPermit } if (wasTiled) { tiledMarkerIds.remove(state.id) } + // ネイティブマーカーとして描くときだけ焼き込む。タイル担当なら要らない。 + val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon val params = object : MarkerOverlayRendererInterface.ChangeParamsInterface { @@ -183,7 +192,7 @@ class OpenMobileMapsMarkerController( renderer.onPostProcess() if (tiledMarkerIds.isNotEmpty()) { - syncTiledOverlay() + scheduleTileRefresh() } else { removeTileOverlay() } @@ -191,6 +200,25 @@ class OpenMobileMapsMarkerController( viewportSwitch.requestReapply() } + private var tileRefreshJob: Job? = null + + /** + * 1 本ずつの変更からの描き直しを 1 回にまとめる。 + * + * ラベルの付け替えのように数十本が続けて変わると、1 本ごとにラスターソースを差し替え、 + * そのたびに地図が見えているタイルを全部取り直していた(MapLibre・Pixel 5a で 45 回、 + * 描き直したタイル 494 枚、最後のタイルまで 6 秒)。続けて来た変更は + * [TILE_REFRESH_COALESCE] の間に受けて、まとめて 1 回だけ差し替える。 + */ + private fun scheduleTileRefresh() { + if (tileRefreshJob?.isActive == true) return + tileRefreshJob = + coroutine.launch { + delay(TILE_REFRESH_COALESCE) + semaphore.withPermit { syncTiledOverlay() } + } + } + override suspend fun clear() { viewportSwitch.destroy() semaphore.withPermit { @@ -226,6 +254,8 @@ class OpenMobileMapsMarkerController( override fun destroy() { viewportSwitch.destroy() + // 待っている描き直しが後から走ると、外したタイル経路をまた登録してしまう。 + tileRefreshJob?.cancel() // タイルサーバはプロセス共有のシングルトン。**stop してはいけない** // (他の地図やオーバーレイ拡張のタイルまで止まる)。自分の経路だけ外す。 markerTileGroupId?.let { tileServer.unregister(it) } @@ -288,6 +318,7 @@ class OpenMobileMapsMarkerController( cacheSizeBytes = markerTiling.cacheSize, debugTileOverlay = markerTiling.debugTileOverlay, iconScaleCallback = markerTiling.iconScaleCallback, + declutterPx = markerTiling.declutterPx, ) markerTileRenderer = tileRenderer tileServer.register(groupId, tileRenderer) @@ -318,4 +349,9 @@ class OpenMobileMapsMarkerController( rasterLayerCallback?.onRasterLayerUpdate(null) markerTileRasterLayerState = null } + + private companion object { + /** 続けて来る変更を 1 回の描き直しにまとめる窓。1 フレーム分。 */ + val TILE_REFRESH_COALESCE = 16.milliseconds + } } diff --git a/src/main/java/com/mapconductor/openmobilemaps/tile/WebMercatorTileLayerConfig.kt b/src/main/java/com/mapconductor/openmobilemaps/tile/WebMercatorTileLayerConfig.kt index 92c2a91..d05243b 100644 --- a/src/main/java/com/mapconductor/openmobilemaps/tile/WebMercatorTileLayerConfig.kt +++ b/src/main/java/com/mapconductor/openmobilemaps/tile/WebMercatorTileLayerConfig.kt @@ -35,6 +35,8 @@ import kotlin.math.pow * @param urlTemplate `{z}` `{x}` `{y}` を含む URL。 * @param tileSize タイル 1 枚の一辺(**dp**)。OSM 系は 256、@2x 系は 512。 * @param scheme [TileScheme.TMS] なら y を反転する。 + * @param roundToNearestLevel true ならカメラのズームを四捨五入したレベルのタイルを出す + * (MapLibre 系・Mapbox・HERE・ArcGIS と同じ)。false は OpenMobileMaps の既定どおり切り捨てる。 */ class WebMercatorTileLayerConfig( private val layerName: String, @@ -45,6 +47,7 @@ class WebMercatorTileLayerConfig( private val scheme: TileScheme = TileScheme.XYZ, private val numDrawPreviousLayers: Int = 2, private val maskTile: Boolean = false, + private val roundToNearestLevel: Boolean = false, ) : Tiled2dMapLayerConfig() { override fun getCoordinateSystemIdentifier(): Int = CoordinateSystemIdentifiers.EPSG3857() @@ -56,6 +59,15 @@ class WebMercatorTileLayerConfig( t: Int, zoom: Int, ): String { + // 間欠不具合の切り分け用: マーカーレイヤが「初期タイルの後、カメラ移動に + // 反応しなくなる」事象を一度観測した(初期 9 枚のあと、パンしても + // オンライン復帰しても要求ゼロ。ベースレイヤは要求し続ける)。再発時は + // adb shell setprop log.tag.OmmTileConfig VERBOSE + // でこのログを生かし、パン時に getTileUrl が呼ばれるか(ネイティブ層の + // カメラ追跡が生きているか)を LocalTileServer のログと突き合わせる。 + if (android.util.Log.isLoggable("OmmTileConfig", android.util.Log.VERBOSE)) { + android.util.Log.v("OmmTileConfig", "getTileUrl layer=$layerName z=$zoom x=$x y=$y") + } val resolvedY = if (scheme == TileScheme.TMS) (1 shl zoom) - 1 - y else y return urlTemplate .replace("{z}", zoom.toString()) @@ -85,7 +97,8 @@ class WebMercatorTileLayerConfig( override fun getZoomInfo(): Tiled2dMapZoomInfo = Tiled2dMapZoomInfo( - 1.0f, + // √2 で次のレベルへ半段早く切り替わり、切り捨てが四捨五入になる。 + if (roundToNearestLevel) 1.4142135f else 1.0f, numDrawPreviousLayers, 0, false,