diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 000000000..671a08447 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,6 @@ +{ + "attribution": { + "commit": "", + "pr": "" + } +} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 000000000..eac6fa95d --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,74 @@ +name: Test + +# JVM ユニットテストのゲート。 +# +# これまで CI は lint.yml(変更モジュールの lint + apiCheck)と publish 系だけで、 +# **テストを走らせるワークフローが無かった。** apiCheck が見るのは公開 API の形 +# だけなので、シグネチャが同じまま中身が壊れる変更は素通りする。 +# +# ## 何を走らせないか +# +# - `connectedAndroidTest`(実機/エミュレータ)。android-sdk-core だけでも +# TilePngEncoder や LocalTileServer の検証があるが、エミュレータは起動に数分 +# かかるうえ不安定。別ワークフロー・別トリガにすること。 +# - `android-for-*`。HERE の aar、Mappls、GitHub Packages の資格情報を要する。 +# ここが落ちる理由の大半は「鍵が無い」で、コードの問題ではない。 +# +# 残した 5 モジュールは外部資格情報なしで通ることを確認済み。ロジックの大半は +# android-sdk-core にある(テストファイル 33 本)。 + +on: + pull_request: + types: [opened, reopened, synchronize, ready_for_review] + branches: + - main + push: + branches: + - main + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + unit-test: + if: github.event.pull_request.draft == false + runs-on: ubuntu-latest + name: JVM unit tests + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + submodules: recursive + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Java + uses: actions/setup-java@v5 + with: + distribution: 'temurin' + java-version: 17 + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Test + run: | + ./gradlew --no-daemon \ + :android-sdk-core:testDebugUnitTest \ + :android-sdk-compose:testDebugUnitTest \ + :android-kml:testDebugUnitTest \ + :android-geojson-layer:testDebugUnitTest \ + :android-icons:testDebugUnitTest + + # 落ちたときに、どのテストがなぜ落ちたかをログを遡らずに読めるようにする。 + - name: Upload reports + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-reports + path: | + **/build/reports/tests/ + **/build/test-results/ + retention-days: 7 diff --git a/README.md b/README.md index 032a9d561..a19bb4c1a 100644 --- a/README.md +++ b/README.md @@ -384,3 +384,17 @@ Feedback, issues, and contributions are welcome. ## License MapConductor Android SDK is released under the Apache License 2.0. + +## Bulk circles and raster tiles + +Inside map content, use `Circles(states)` from `com.mapconductor.compose.circle` to register a collection in one operation. Each collection removes only its own IDs. Use `CircleTiling(CircleTilingOptions.Disabled)` to keep native rendering, or `CircleTiling(CircleTilingOptions(minCircleCount = 5000))` to customize the threshold. Options are in `com.mapconductor.core.circle`. + +By default, raster tiling starts above 2,000 tileable circles. Large collections keep their drawing geometry in a disk-backed cache. Circle radius remains a ground distance in metres and stroke width remains a screen distance. Clicks and `onAdded` use the original states. `onAdded` indicates that the tile layer was handed to the map. + +Circles crossing the antimeridian, reaching Mercator's latitude limit, or having invalid radii stay native. Circle tiles stack above polygons and below polylines. + +## US antenna horizons example + +Choose **US Antenna Horizons** in the example sidebar. It bundles 723,800 OpenCellID records (MCC 310–314), with carrier filters and US and Alaska camera presets. Each estimated cell position is drawn as a 500 m geodesic circle. The radius is a display setting and does not model signal coverage. + +Cell tower data from [OpenCellID](https://opencellid.org) · [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). diff --git a/android-for-arcgis b/android-for-arcgis index b3ed2a57d..b4342b169 160000 --- a/android-for-arcgis +++ b/android-for-arcgis @@ -1 +1 @@ -Subproject commit b3ed2a57d3fe3fa5ad91507404cf68ba76189926 +Subproject commit b4342b1697a0c04416ea536dbe54eaefdd9890b5 diff --git a/android-for-googlemaps b/android-for-googlemaps index 44e125f7e..2e4dbb7e3 160000 --- a/android-for-googlemaps +++ b/android-for-googlemaps @@ -1 +1 @@ -Subproject commit 44e125f7e3a12b94a38dbb343740a97b8c1f4498 +Subproject commit 2e4dbb7e36e3d5c4feb739cc6f0a595d2f920b39 diff --git a/android-for-here b/android-for-here index 9fd81f503..5c23d3a76 160000 --- a/android-for-here +++ b/android-for-here @@ -1 +1 @@ -Subproject commit 9fd81f503433b723fb509628027ca015d6002585 +Subproject commit 5c23d3a76fcd6cc0de156262b9b5e1939d722c16 diff --git a/android-for-longdo b/android-for-longdo index 94b820140..bb768fd97 160000 --- a/android-for-longdo +++ b/android-for-longdo @@ -1 +1 @@ -Subproject commit 94b82014094624d5d7f7e0241c571a5ff11ba4db +Subproject commit bb768fd97a5a42f4f8d176e63df3bb935b5cbcca diff --git a/android-for-mapbox b/android-for-mapbox index e0ef28368..0089b59e0 160000 --- a/android-for-mapbox +++ b/android-for-mapbox @@ -1 +1 @@ -Subproject commit e0ef28368faeda0f3ce20a5f3522627d45e0fe8b +Subproject commit 0089b59e0877098a7dc344e330074a75f75d073b diff --git a/android-for-maplibre b/android-for-maplibre index 1dd810057..10b3b6274 160000 --- a/android-for-maplibre +++ b/android-for-maplibre @@ -1 +1 @@ -Subproject commit 1dd81005785aeac264a890aabc5702e55fc9da45 +Subproject commit 10b3b6274e61d34e715a36cac2962abf4def9022 diff --git a/android-for-mappls b/android-for-mappls index 486a766cd..b14ab67f8 160000 --- a/android-for-mappls +++ b/android-for-mappls @@ -1 +1 @@ -Subproject commit 486a766cd8f949f5a6eec1e4da60885617f833d6 +Subproject commit b14ab67f8c5ef88be60541181973db00bdd462ff diff --git a/android-for-maptiler b/android-for-maptiler index af9fa7391..2d9d0b00e 160000 --- a/android-for-maptiler +++ b/android-for-maptiler @@ -1 +1 @@ -Subproject commit af9fa7391c2ee4452b6dd4842cc99c091feac774 +Subproject commit 2d9d0b00e8fb73f4dbf0a718720d55aa788d2b4f diff --git a/android-for-openmobilemaps b/android-for-openmobilemaps index 3a873e860..99e7ec03b 160000 --- a/android-for-openmobilemaps +++ b/android-for-openmobilemaps @@ -1 +1 @@ -Subproject commit 3a873e860f5131fd93b665f490699f60e1bb3eae +Subproject commit 99e7ec03b85cdb40818523dafc220162a133858b diff --git a/android-for-template b/android-for-template index f467eb06d..f3ab21fbf 160000 --- a/android-for-template +++ b/android-for-template @@ -1 +1 @@ -Subproject commit f467eb06d7c7f67b59c980e402c396f8e45577d5 +Subproject commit f3ab21fbfa875d9fbfd2b699dcfe2be23b5acbe6 diff --git a/android-for-tomtom b/android-for-tomtom index 18922d15f..ad7d05406 160000 --- a/android-for-tomtom +++ b/android-for-tomtom @@ -1 +1 @@ -Subproject commit 18922d15f2a91f318b10544f44681eb0959b95dc +Subproject commit ad7d054065c0763a65fcf3460001e247f07c214d diff --git a/android-geojson-layer b/android-geojson-layer index 66b5855f3..1b5ca97d4 160000 --- a/android-geojson-layer +++ b/android-geojson-layer @@ -1 +1 @@ -Subproject commit 66b5855f36cc5f8e7c359c3426dd4029d258c3fa +Subproject commit 1b5ca97d428bd911735ef4036a39c7c174af93d5 diff --git a/android-heatmap b/android-heatmap index d647d5e23..2ef8597cf 160000 --- a/android-heatmap +++ b/android-heatmap @@ -1 +1 @@ -Subproject commit d647d5e2327f9a42c89079be844672c402f5cf0c +Subproject commit 2ef8597cfd92c3045b94d30c931159feb73bae51 diff --git a/android-icons b/android-icons index 0afc20126..934835d7d 160000 --- a/android-icons +++ b/android-icons @@ -1 +1 @@ -Subproject commit 0afc20126fb918283b322dca34cb6201840e9720 +Subproject commit 934835d7dc0dc0793863ac51a92dc808ce7c8c73 diff --git a/android-icons-jp b/android-icons-jp index 36dd2d08d..e27b30d77 160000 --- a/android-icons-jp +++ b/android-icons-jp @@ -1 +1 @@ -Subproject commit 36dd2d08d4f6a41e749ae9f8f032491951ccf254 +Subproject commit e27b30d7700c23272d170f5643340c9a09c5a4b7 diff --git a/android-icons-us b/android-icons-us index b85bf3f83..b0a53ca11 160000 --- a/android-icons-us +++ b/android-icons-us @@ -1 +1 @@ -Subproject commit b85bf3f8327c2237a8e1080f968c223f32bb2657 +Subproject commit b0a53ca11c01c982db5cf8293902f70cc51969c7 diff --git a/android-icons-weather b/android-icons-weather index ac9847a21..79174c878 160000 --- a/android-icons-weather +++ b/android-icons-weather @@ -1 +1 @@ -Subproject commit ac9847a21fe1e6f26b87fa85447716b49dac7027 +Subproject commit 79174c878c3c84c7ca5a388526ce85dc8b88ee60 diff --git a/android-kml b/android-kml index b02b42a4e..fded7454a 160000 --- a/android-kml +++ b/android-kml @@ -1 +1 @@ -Subproject commit b02b42a4eb91c5e8a130dc58c2c9cf539bb17802 +Subproject commit fded7454a970f6b024a13f966924004852b4dc2e diff --git a/android-marker-clustering b/android-marker-clustering index 7ae4aa6ae..517e6354a 160000 --- a/android-marker-clustering +++ b/android-marker-clustering @@ -1 +1 @@ -Subproject commit 7ae4aa6ae80f13186cf22344d602b6c9b050ff27 +Subproject commit 517e6354adacc54c1b0819cbafa66f997f30a133 diff --git a/android-sdk-compose b/android-sdk-compose index 10537ebb0..c16e43ca1 160000 --- a/android-sdk-compose +++ b/android-sdk-compose @@ -1 +1 @@ -Subproject commit 10537ebb006b51211f315c92021b310e40fbd269 +Subproject commit c16e43ca1ff13286176649cd799e0548b4299eb2 diff --git a/android-sdk-core b/android-sdk-core index 760b8432b..451e47bdd 160000 --- a/android-sdk-core +++ b/android-sdk-core @@ -1 +1 @@ -Subproject commit 760b8432bd6914075ac27ccc6c1cf303a59bde43 +Subproject commit 451e47bdd1924be281571fea78dd24e47727ce99 diff --git a/android-vectorstyle/api/android-vectorstyle.api b/android-vectorstyle/api/android-vectorstyle.api new file mode 100644 index 000000000..8c1336505 --- /dev/null +++ b/android-vectorstyle/api/android-vectorstyle.api @@ -0,0 +1,275 @@ +public final class com.mapconductor.vectorstyle.CompiledStyle { + public com.mapconductor.vectorstyle.CompiledStyle(java.lang.String, java.util.List, com.mapconductor.vectorstyle.StyleAffects, boolean, java.util.List); + public final java.lang.String getStyleJson(); + public final java.util.List getMutations(); + public final com.mapconductor.vectorstyle.StyleAffects getAffects(); + public final boolean getPatchable(); + public final java.util.List getDiagnostics(); + public final java.lang.String component1(); + public final java.util.List component2(); + public final com.mapconductor.vectorstyle.StyleAffects component3(); + public final boolean component4(); + public final java.util.List component5(); + public final com.mapconductor.vectorstyle.CompiledStyle copy(java.lang.String, java.util.List, com.mapconductor.vectorstyle.StyleAffects, boolean, java.util.List); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.LayerRole { + public static final com.mapconductor.vectorstyle.LayerRole INSTANCE; + public static final java.lang.String BACKGROUND; + public static final java.lang.String WATER; + public static final java.lang.String WATERWAY; + public static final java.lang.String LAND; + public static final java.lang.String LANDUSE; + public static final java.lang.String PARK; + public static final java.lang.String BUILDING; + public static final java.lang.String ROAD; + public static final java.lang.String ROAD_CASING; + public static final java.lang.String RAIL; + public static final java.lang.String TRANSIT; + public static final java.lang.String BOUNDARY; + public static final java.lang.String AEROWAY; + public static final java.lang.String LABEL; + public static final java.lang.String POI; +} +public final class com.mapconductor.vectorstyle.NativeStyleCompiler { + public static final com.mapconductor.vectorstyle.NativeStyleCompiler INSTANCE; + public final native java.lang.String nativeCompile(java.lang.String, java.lang.String); + public final native java.lang.String nativeDescribe(java.lang.String); + public final native int nativeSchemaVersion(); +} +public final class com.mapconductor.vectorstyle.StyleAffects extends java.lang.Enum { + public static final com.mapconductor.vectorstyle.StyleAffects$Companion Companion; + public static final com.mapconductor.vectorstyle.StyleAffects NONE; + public static final com.mapconductor.vectorstyle.StyleAffects GROUND; + public static final com.mapconductor.vectorstyle.StyleAffects LABELS; + public static final com.mapconductor.vectorstyle.StyleAffects BOTH; + public static com.mapconductor.vectorstyle.StyleAffects[] values(); + public static com.mapconductor.vectorstyle.StyleAffects valueOf(java.lang.String); + public static kotlin.enums.EnumEntries getEntries(); +} +public final class com.mapconductor.vectorstyle.StyleAffects$Companion { + public final com.mapconductor.vectorstyle.StyleAffects of(java.lang.String); +} +public final class com.mapconductor.vectorstyle.StyleLayerInfo { + public com.mapconductor.vectorstyle.StyleLayerInfo(java.lang.String, java.lang.String, java.lang.String, java.util.List, java.util.List); + public final java.lang.String getId(); + public final java.lang.String getKind(); + public final java.lang.String getSourceLayer(); + public final java.util.List getRoles(); + public final java.util.List getEvidence(); + public final java.lang.String component1(); + public final java.lang.String component2(); + public final java.lang.String component3(); + public final java.util.List component4(); + public final java.util.List component5(); + public final com.mapconductor.vectorstyle.StyleLayerInfo copy(java.lang.String, java.lang.String, java.lang.String, java.util.List, java.util.List); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.StyleLayerKind extends java.lang.Enum { + public static final com.mapconductor.vectorstyle.StyleLayerKind BACKGROUND; + public static final com.mapconductor.vectorstyle.StyleLayerKind FILL; + public static final com.mapconductor.vectorstyle.StyleLayerKind LINE; + public static final com.mapconductor.vectorstyle.StyleLayerKind CIRCLE; + public static final com.mapconductor.vectorstyle.StyleLayerKind SYMBOL; + public static final com.mapconductor.vectorstyle.StyleLayerKind OTHER; + public static com.mapconductor.vectorstyle.StyleLayerKind[] values(); + public static com.mapconductor.vectorstyle.StyleLayerKind valueOf(java.lang.String); + public static kotlin.enums.EnumEntries getEntries(); +} +public final class com.mapconductor.vectorstyle.StylePatchBuilder { + public com.mapconductor.vectorstyle.StylePatchBuilder(); + public final java.lang.Boolean getVisible(); + public final void setVisible(java.lang.Boolean); + public final androidx.compose.ui.graphics.Color getColor-QN2ZGVo(); + public final void setColor-Y2TPw74(androidx.compose.ui.graphics.Color); + public final java.lang.Float getOpacity(); + public final void setOpacity(java.lang.Float); + public final java.lang.Float getWidthScale(); + public final void setWidthScale(java.lang.Float); + public final java.lang.Float getMinZoom(); + public final void setMinZoom(java.lang.Float); + public final java.lang.Float getMaxZoom(); + public final void setMaxZoom(java.lang.Float); + public final void desaturate(float); + public final void darken(float); + public final void lighten(float); + public final void invertLightness(); + public final void mix-DxMtmZc(long, float); + public final void filter(java.lang.String); + public final void property(java.lang.String, java.lang.String); + public final void propertyText(java.lang.String, java.lang.String); +} +public final class com.mapconductor.vectorstyle.StyleRules { + public static final com.mapconductor.vectorstyle.StyleRules$Companion Companion; + public static final com.mapconductor.vectorstyle.StyleRules NONE; + public final java.lang.String getJson(); + public boolean equals(java.lang.Object); + public int hashCode(); + public java.lang.String toString(); + public static final com.mapconductor.vectorstyle.StyleRules parse(java.lang.String); + public static final com.mapconductor.vectorstyle.StyleRules build(kotlin.jvm.functions.Function1); + public com.mapconductor.vectorstyle.StyleRules(java.lang.String, kotlin.jvm.internal.DefaultConstructorMarker); +} +public final class com.mapconductor.vectorstyle.StyleRules$Companion { + public final com.mapconductor.vectorstyle.StyleRules parse(java.lang.String); + public final com.mapconductor.vectorstyle.StyleRules build(kotlin.jvm.functions.Function1); +} +public final class com.mapconductor.vectorstyle.StyleRulesBuilder { + public com.mapconductor.vectorstyle.StyleRulesBuilder(); + public final java.lang.String getSchema(); + public final void setSchema(java.lang.String); + public final void customSchema(java.util.Map>); + public final void all(kotlin.jvm.functions.Function1); + public final void role(java.lang.String, kotlin.jvm.functions.Function1); + public final void layerId(java.lang.String, kotlin.jvm.functions.Function1); + public final void sourceLayer(java.lang.String, kotlin.jvm.functions.Function1); + public final void kind(com.mapconductor.vectorstyle.StyleLayerKind, kotlin.jvm.functions.Function1); + public final void where(com.mapconductor.vectorstyle.StyleSelector, kotlin.jvm.functions.Function1); +} +public final class com.mapconductor.vectorstyle.StyleRulesKt { + public static final java.lang.String toJson(com.mapconductor.vectorstyle.StyleSelector); + public static final java.lang.String toStyleText-8_81llA(long); + public static final java.lang.String quote(java.lang.String); +} +public interface com.mapconductor.vectorstyle.StyleSelector { +} +public final class com.mapconductor.vectorstyle.StyleSelector$All implements com.mapconductor.vectorstyle.StyleSelector { + public static final com.mapconductor.vectorstyle.StyleSelector$All INSTANCE; +} +public final class com.mapconductor.vectorstyle.StyleSelector$AllOf implements com.mapconductor.vectorstyle.StyleSelector { + public final java.util.List getOf(); + public final java.util.List component1(); + public final com.mapconductor.vectorstyle.StyleSelector$AllOf copy(java.util.List); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.StyleSelector$AnyOf implements com.mapconductor.vectorstyle.StyleSelector { + public final java.util.List getOf(); + public final java.util.List component1(); + public final com.mapconductor.vectorstyle.StyleSelector$AnyOf copy(java.util.List); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.StyleSelector$Kind implements com.mapconductor.vectorstyle.StyleSelector { + public final com.mapconductor.vectorstyle.StyleLayerKind getKind(); + public final com.mapconductor.vectorstyle.StyleLayerKind component1(); + public final com.mapconductor.vectorstyle.StyleSelector$Kind copy(com.mapconductor.vectorstyle.StyleLayerKind); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.StyleSelector$LayerId implements com.mapconductor.vectorstyle.StyleSelector { + public final java.lang.String getGlob(); + public final java.lang.String component1(); + public final com.mapconductor.vectorstyle.StyleSelector$LayerId copy(java.lang.String); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.StyleSelector$Not implements com.mapconductor.vectorstyle.StyleSelector { + public final com.mapconductor.vectorstyle.StyleSelector getOf(); + public final com.mapconductor.vectorstyle.StyleSelector component1(); + public final com.mapconductor.vectorstyle.StyleSelector$Not copy(com.mapconductor.vectorstyle.StyleSelector); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.StyleSelector$Role implements com.mapconductor.vectorstyle.StyleSelector { + public final java.lang.String getRole(); + public final java.lang.String component1(); + public final com.mapconductor.vectorstyle.StyleSelector$Role copy(java.lang.String); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.StyleSelector$SourceLayer implements com.mapconductor.vectorstyle.StyleSelector { + public final java.lang.String getName(); + public final java.lang.String component1(); + public final com.mapconductor.vectorstyle.StyleSelector$SourceLayer copy(java.lang.String); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.UnsupportedPolicy extends java.lang.Enum { + public static final com.mapconductor.vectorstyle.UnsupportedPolicy REPORT; + public static final com.mapconductor.vectorstyle.UnsupportedPolicy RELOAD; + public static com.mapconductor.vectorstyle.UnsupportedPolicy[] values(); + public static com.mapconductor.vectorstyle.UnsupportedPolicy valueOf(java.lang.String); + public static kotlin.enums.EnumEntries getEntries(); +} +public final class com.mapconductor.vectorstyle.VectorStyle implements com.mapconductor.core.map.MapViewStyle { + public com.mapconductor.vectorstyle.VectorStyle(com.mapconductor.vectorstyle.VectorStyleSource, com.mapconductor.vectorstyle.StyleRules, com.mapconductor.vectorstyle.VectorStyleRasteriser, com.mapconductor.vectorstyle.UnsupportedPolicy, kotlin.jvm.functions.Function1, kotlin.Unit>); + public com.mapconductor.vectorstyle.VectorStyle(com.mapconductor.vectorstyle.VectorStyleSource, com.mapconductor.vectorstyle.StyleRules, com.mapconductor.vectorstyle.VectorStyleRasteriser, com.mapconductor.vectorstyle.UnsupportedPolicy, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final com.mapconductor.vectorstyle.VectorStyleSource getDocument(); + public final com.mapconductor.vectorstyle.StyleRules getRules(); + public final com.mapconductor.vectorstyle.VectorStyleRasteriser getRasteriser(); + public final com.mapconductor.vectorstyle.UnsupportedPolicy getOnUnsupported(); + public final kotlin.jvm.functions.Function1, kotlin.Unit> getOnDiagnostics(); + public java.lang.String getKey(); + public com.mapconductor.core.map.MapStyleInstallation install(com.mapconductor.core.map.MapStyleHost); + public com.mapconductor.vectorstyle.VectorStyle(); +} +final class com.mapconductor.vectorstyle.VectorStyle$Installation implements com.mapconductor.core.map.MapStyleInstallation { + public static final java.lang.String TAG; + public final void start(); + public boolean update(com.mapconductor.core.map.MapViewStyle); + public void dispose(); +} +final class com.mapconductor.vectorstyle.VectorStyle$Installation$Companion { + public final java.lang.String contentId(java.lang.String); + public final java.util.concurrent.ExecutorService getWorkers(); + public final java.lang.String fetch(java.lang.String, java.util.Map); + public final java.util.List attributionsOf(java.lang.String); +} +public final class com.mapconductor.vectorstyle.VectorStyleException extends java.lang.IllegalArgumentException { + public com.mapconductor.vectorstyle.VectorStyleException(java.lang.String); +} +public interface com.mapconductor.vectorstyle.VectorStyleRasterisation { + public abstract void restyle(java.lang.String, com.mapconductor.vectorstyle.StyleAffects); + public abstract void dispose(); +} +public interface com.mapconductor.vectorstyle.VectorStyleRasteriser { + public abstract com.mapconductor.vectorstyle.VectorStyleRasterisation install(com.mapconductor.core.map.MapStyleHost, java.lang.String, com.mapconductor.vectorstyle.StyleAffects); +} +public final class com.mapconductor.vectorstyle.VectorStyleRules { + public static final com.mapconductor.vectorstyle.VectorStyleRules INSTANCE; + public static final int getSchemaVersion(); + public static final com.mapconductor.vectorstyle.CompiledStyle compile(java.lang.String, java.lang.String); + public static final java.util.List describe(java.lang.String); +} +public interface com.mapconductor.vectorstyle.VectorStyleSource { + public abstract java.lang.String getKey(); +} +public final class com.mapconductor.vectorstyle.VectorStyleSource$CurrentDesign implements com.mapconductor.vectorstyle.VectorStyleSource { + public static final com.mapconductor.vectorstyle.VectorStyleSource$CurrentDesign INSTANCE; + public java.lang.String getKey(); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.VectorStyleSource$Text implements com.mapconductor.vectorstyle.VectorStyleSource { + public final java.lang.String getJson(); + public java.lang.String getKey(); + public final java.lang.String component1(); + public final com.mapconductor.vectorstyle.VectorStyleSource$Text copy(java.lang.String); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectorstyle.VectorStyleSource$Url implements com.mapconductor.vectorstyle.VectorStyleSource { + public final java.lang.String getUrl(); + public final java.util.Map getHeaders(); + public java.lang.String getKey(); + public final java.lang.String component1(); + public final java.util.Map component2(); + public final com.mapconductor.vectorstyle.VectorStyleSource$Url copy(java.lang.String, java.util.Map); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} diff --git a/android-vectorstyle/build.gradle.kts b/android-vectorstyle/build.gradle.kts new file mode 100644 index 000000000..310f84902 --- /dev/null +++ b/android-vectorstyle/build.gradle.kts @@ -0,0 +1,150 @@ +plugins { + alias(libs.plugins.android.library) + id("org.jlleitschuh.gradle.ktlint") version "14.2.0" + id("maven-publish") + id("signing") + id("com.gradleup.nmcp") version "1.5.0" +} + +ktlint { + android.set(true) + reporters { + reporter(org.jlleitschuh.gradle.ktlint.reporter.ReporterType.PLAIN) + reporter(org.jlleitschuh.gradle.ktlint.reporter.ReporterType.CHECKSTYLE) + } +} + +android { + namespace = "com.mapconductor.vectorstyle" + compileSdk = project.property("compileSdk").toString().toInt() + + defaultConfig { + minSdk = project.property("minSdk").toString().toInt() + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles("consumer-rules.pro") + aarMetadata { + minCompileSdk = project.property("compileSdk").toString().toInt() + } + // Every ABI, unlike the rasteriser: the compiler is a few hundred + // kilobytes, so leaving one out buys nothing and a missing slice + // means the module simply does not work on that device. + ndk { abiFilters += setOf("arm64-v8a", "armeabi-v7a", "x86_64") } + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro", + ) + } + } + + compileOptions { + sourceCompatibility = JavaVersion.toVersion(project.property("javaVersion").toString()) + targetCompatibility = JavaVersion.toVersion(project.property("javaVersion").toString()) + } + + publishing { + singleVariant("release") { + withSourcesJar() + } + } +} + +dependencies { + // Core and nothing else. This module compiles a style document; it draws + // nothing, so it needs neither Compose nor the rasteriser -- which is the + // whole reason it is a separate artifact from `android-vectortile`. + if (findProject(":android-sdk-core") != null) { + api(project(":android-sdk-core")) + } else { + api("com.mapconductor:core:${project.findProperty("coreLibraryVersion") as String? ?: "1.0.0"}") + } + + // Only for `Color`: the rules name colours and an app writing them in + // Compose should not have to convert. Nothing here draws. + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.ui.graphics) + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) +} + +// Publishing configuration. +// +// **This module had `maven-publish` applied and no publication**, so nothing +// was ever produced -- `publishToMavenLocal` succeeded and wrote nothing. +// That only showed up when React Native needed to depend on it: the RN +// wrapper reads this module from MavenLocal like every other provider. +val libraryGroupId = project.findProperty("libraryGroupId") as String? ?: "com.mapconductor" +val libraryArtifactId = "vectorstyle" +val libraryVersion = project.findProperty("libraryVersion") as String? ?: "1.0.0" + +version = libraryVersion +val libraryName = "MapConductor Vector Style" +val libraryDescription = "Declarative adjustments to a MapLibre style, applied the same way on every renderer" + +val javadocJar by tasks.registering(Jar::class) { + archiveClassifier.set("javadoc") +} + +afterEvaluate { + publishing { + publications { + create("release") { + from(components["release"]) + + groupId = libraryGroupId + artifactId = libraryArtifactId + version = libraryVersion + + artifact(javadocJar.get()) + + pom { + name.set(libraryName) + description.set(libraryDescription) + url.set( + project.findProperty("libraryUrl") as String? + ?: "https://github.com/MapConductor/android-sdk", + ) + + licenses { + license { + name.set("The Apache License, Version 2.0") + url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") + } + } + + developers { + developer { + id.set(project.findProperty("developerId") as String? ?: "mapconductor") + name.set(project.findProperty("developerName") as String? ?: "MapConductor Team") + email.set(project.findProperty("developerEmail") as String? ?: "info@mkgeeklab.com") + } + } + + scm { + connection.set("scm:git:git://github.com/MapConductor/android-sdk.git") + developerConnection.set("scm:git:ssh://github.com:MapConductor/android-sdk.git") + url.set( + project.findProperty("scmUrl") as String? + ?: "https://github.com/MapConductor/android-sdk.git", + ) + } + } + } + } + } + + signing { + val signingKey = findProperty("signingKey") as String? + val signingPassword = findProperty("signingPassword") as String? + if (!signingKey.isNullOrEmpty() && !signingPassword.isNullOrEmpty()) { + useInMemoryPgpKeys(signingKey, signingPassword) + sign(publishing.publications["release"]) + } + } +} diff --git a/android-vectorstyle/consumer-rules.pro b/android-vectorstyle/consumer-rules.pro new file mode 100644 index 000000000..e69de29bb diff --git a/android-vectorstyle/proguard-rules.pro b/android-vectorstyle/proguard-rules.pro new file mode 100644 index 000000000..03ee1bcc0 --- /dev/null +++ b/android-vectorstyle/proguard-rules.pro @@ -0,0 +1,5 @@ +# The JNI entry points are resolved by name from native code, so R8 must not +# rename or strip them. +-keepclasseswithmembernames class com.mapconductor.vectortile.NativeRenderer { + native ; +} diff --git a/android-vectorstyle/src/androidTest/AndroidManifest.xml b/android-vectorstyle/src/androidTest/AndroidManifest.xml new file mode 100644 index 000000000..68f484a43 --- /dev/null +++ b/android-vectorstyle/src/androidTest/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/android-vectorstyle/src/androidTest/assets/versatiles-colorful.json b/android-vectorstyle/src/androidTest/assets/versatiles-colorful.json new file mode 100644 index 000000000..c7bd8d750 --- /dev/null +++ b/android-vectorstyle/src/androidTest/assets/versatiles-colorful.json @@ -0,0 +1 @@ +{"version": 8, "name": "versatiles-colorful", "metadata": {"license": "https://creativecommons.org/publicdomain/zero/1.0/"}, "glyphs": "https://tiles.versatiles.org/assets/glyphs/{fontstack}/{range}.pbf", "sprite": [{"id": "base", "url": "https://tiles.versatiles.org/assets/sprites/base"}], "sources": {"versatiles-shortbread": {"type": "vector", "tiles": ["https://vector.openstreetmap.org/shortbread_v1/{z}/{x}/{y}.mvt"], "minzoom": 0, "maxzoom": 14}}, "layers": [{"id": "background", "type": "background", "paint": {"background-color": "rgb(248,244,240)"}}, {"id": "slot-below-fills", "type": "background", "paint": {"background-opacity": 0}}, {"id": "water-ocean", "type": "fill", "source-layer": "ocean", "paint": {"fill-color": "rgb(191,217,242)"}, "source": "versatiles-shortbread"}, {"id": "land-glacier", "type": "fill", "source-layer": "water_polygons", "filter": ["==", ["get", "kind"], "glacier"], "paint": {"fill-color": "rgb(255,255,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "land-commercial", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["commercial", "retail"]]], "paint": {"fill-color": "rgb(248,238,239)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-industrial", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["industrial", "quarry", "railway"]]], "paint": {"fill-color": "rgb(250,244,225)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-residential", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["garages", "residential"]]], "paint": {"fill-color": "rgb(245,241,237)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-agriculture", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["farmland", "farmyard", "greenhouse_horticulture", "orchard", "plant_nursery", "vineyard"]]], "paint": {"fill-color": "rgb(233,242,206)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-waste", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["landfill"]]], "paint": {"fill-color": "rgb(219,214,189)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-park", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["park", "village_green", "recreation_ground"]]], "paint": {"fill-color": "rgba(205,217,169,0.5)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-garden", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["allotments", "garden"]]], "paint": {"fill-color": "rgb(205,217,169)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-burial", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["cemetery", "grave_yard"]]], "paint": {"fill-color": "rgb(224,228,221)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "land-leisure", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["miniature_golf", "playground", "golf_course"]]], "paint": {"fill-color": "rgb(231,237,222)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-rock", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["bare_rock", "scree", "shingle"]]], "paint": {"fill-color": "rgb(242,242,230)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-forest", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["forest"]]], "paint": {"fill-color": "rgb(203,229,184)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 1]}, "minzoom": 7, "source": "versatiles-shortbread"}, {"id": "land-grass", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["grass", "grassland", "meadow", "wet_meadow"]]], "paint": {"fill-color": "rgb(209,229,195)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-vegetation", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["heath", "scrub"]]], "paint": {"fill-color": "rgb(230,238,199)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-sand", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["beach", "sand"]]], "paint": {"fill-color": "rgb(242,242,206)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-wetland", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["bog", "marsh", "string_bog", "swamp"]]], "paint": {"fill-color": "rgb(211,230,219)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "site-dangerarea", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "danger_area"], "paint": {"fill-color": "rgb(255,0,0)", "fill-outline-color": "rgb(255,0,0)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.302], "fill-pattern": "base:pattern-hatched"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-sportscentre", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "sports_centre"], "paint": {"fill-color": "rgba(246,243,238,0.149)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-education", "type": "fill", "source-layer": "sites", "filter": ["any", ["==", ["get", "kind"], "university"], ["==", ["get", "kind"], "college"], ["==", ["get", "kind"], "school"]], "paint": {"fill-color": "rgba(255,255,128,0.125)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-hospital", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "hospital"], "paint": {"fill-color": "rgba(255,102,102,0.102)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-prison", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "prison"], "paint": {"fill-color": "rgb(253,242,252)", "fill-pattern": "base:pattern-striped", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.102]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-parking", "type": "fill", "source-layer": "sites", "filter": ["any", ["==", ["get", "kind"], "parking"], ["==", ["get", "kind"], "bicycle_parking"]], "paint": {"fill-color": "rgb(235,232,230)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-construction", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "construction"], "paint": {"fill-color": "rgb(169,169,169)", "fill-pattern": "base:pattern-hatched_thin", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.102]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "water-river", "type": "line", "source-layer": "water_lines", "filter": ["all", ["==", ["get", "kind"], "river"], ["!=", ["get", "tunnel"], true], ["!=", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,202,237)", "line-width": ["interpolate", ["exponential", 1.2], ["zoom"], 10, 0.8, 20, 6]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "water-canal", "type": "line", "source-layer": "water_lines", "filter": ["all", ["==", ["get", "kind"], "canal"], ["!=", ["get", "tunnel"], true], ["!=", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,202,237)", "line-width": ["interpolate", ["exponential", 1.3], ["zoom"], 13, 0.5, 20, 6]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "water-stream", "type": "line", "source-layer": "water_lines", "filter": ["all", ["==", ["get", "kind"], "stream"], ["!=", ["get", "tunnel"], true], ["!=", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,202,237)", "line-width": ["interpolate", ["exponential", 1.3], ["zoom"], 13, 0.5, 20, 6]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "water-ditch", "type": "line", "source-layer": "water_lines", "filter": ["all", ["==", ["get", "kind"], "ditch"], ["!=", ["get", "tunnel"], true], ["!=", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,202,237)", "line-width": ["interpolate", ["exponential", 1.3], ["zoom"], 13, 0.5, 20, 2]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "water-area", "type": "fill", "source-layer": "water_polygons", "filter": ["==", ["get", "kind"], "water"], "paint": {"fill-color": "rgb(191,217,242)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "water-area-river", "type": "fill", "source-layer": "water_polygons", "filter": ["==", ["get", "kind"], "river"], "paint": {"fill-color": "rgb(191,217,242)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "water-area-small", "type": "fill", "source-layer": "water_polygons", "filter": ["in", ["get", "kind"], ["literal", ["reservoir", "basin", "dock"]]], "paint": {"fill-color": "rgb(191,217,242)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "water-dam-area", "type": "fill", "source-layer": "dam_polygons", "filter": ["==", ["get", "kind"], "dam"], "paint": {"fill-color": "rgb(248,244,240)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "water-dam", "type": "line", "source-layer": "dam_lines", "filter": ["==", ["get", "kind"], "dam"], "paint": {"line-color": "rgb(191,217,242)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1, 16, 4, 18, 18, 20, 90]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "water-pier-area", "type": "fill", "source-layer": "pier_polygons", "filter": ["in", ["get", "kind"], ["literal", ["pier", "breakwater", "groyne"]]], "paint": {"fill-color": "rgb(248,244,240)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "water-pier", "type": "line", "source-layer": "pier_lines", "filter": ["in", ["get", "kind"], ["literal", ["pier", "breakwater", "groyne"]]], "paint": {"line-color": "rgb(248,244,240)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1, 16, 4, 18, 18, 20, 90]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "airport-area", "type": "fill", "source-layer": "street_polygons", "filter": ["in", ["get", "kind"], ["literal", ["runway", "taxiway"]]], "paint": {"fill-color": "rgb(255,255,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "airport-taxiway:outline", "type": "line", "source-layer": "streets", "filter": ["==", ["get", "kind"], "taxiway"], "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 2, 15, 10, 16, 14, 18, 20, 20, 40]}, "layout": {"line-cap": "butt", "line-join": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "airport-runway:outline", "type": "line", "source-layer": "streets", "filter": ["==", ["get", "kind"], "runway"], "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 6, 13, 9, 14, 16, 15, 24, 16, 40, 17, 100, 18, 160, 20, 300]}, "layout": {"line-cap": "butt", "line-join": "round"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "airport-taxiway", "type": "line", "source-layer": "streets", "filter": ["==", ["get", "kind"], "taxiway"], "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1, 15, 8, 16, 12, 18, 18, 20, 36]}, "layout": {"line-cap": "butt", "line-join": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "airport-runway", "type": "line", "source-layer": "streets", "filter": ["==", ["get", "kind"], "runway"], "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 5, 13, 8, 14, 14, 15, 22, 16, 38, 17, 98, 18, 158, 20, 298], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "layout": {"line-cap": "butt", "line-join": "round"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "building:outline", "type": "fill", "source-layer": "buildings", "paint": {"fill-color": "rgb(223,219,215)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "building", "type": "fill", "source-layer": "buildings", "paint": {"fill-color": "rgb(242,234,226)", "fill-translate": [-2, -2], "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "slot-below-streets", "type": "background", "paint": {"background-opacity": 0}}, {"id": "tunnel-street-pedestrian-zone", "type": "fill", "source-layer": "street_polygons", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "pedestrian"]], "paint": {"fill-color": "rgb(255,255,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-way-footway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(239,231,241)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-steps:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(239,231,241)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-path:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(239,231,241)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-cycleway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(233,238,241)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-track:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 2, 16, 4, 18, 18, 19, 48, 20, 96], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-pedestrian:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(237,236,235)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-livingstreet:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-minor:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-bus:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(237,236,235)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-tertiary-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-arterial-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-trunk-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-motorway-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-tertiary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "tunnel-street-secondary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 2, 14, 5, 16, 8, 18, 30, 19, 68, 20, 138], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "tunnel-street-primary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "tunnel-street-trunk:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "tunnel-street-motorway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 2, 10, 5, 14, 5, 16, 14, 18, 38, 19, 84, 20, 168], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "tunnel-way-footway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(253,244,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-steps", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(253,244,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-path", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(253,244,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-cycleway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(246,252,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-track", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 16, 19, 44, 20, 88], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-pedestrian", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(253,244,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(251,251,251)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-livingstreet", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-minor", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-bus", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(251,251,251)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-pedestrian-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bicycle"], "designated"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(246,252,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-minor-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["living_street", "residential", "unclassified"]]], ["==", ["get", "bicycle"], "designated"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(246,252,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-tertiary-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-arterial-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-trunk-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-motorway-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,227,190)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-tertiary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "tunnel-street-secondary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 1, 14, 4, 16, 6, 18, 28, 19, 64, 20, 130], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "tunnel-street-primary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "tunnel-street-trunk", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "tunnel-street-motorway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,227,190)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1, 10, 4, 14, 4, 16, 12, 18, 36, 19, 80, 20, 160], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-rail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 0.5]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-rail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-lightrail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 0.5]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-lightrail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-subway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(206,216,224)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 3, 16, 3, 18, 6, 19, 8, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 0.5]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-minorrail:outline", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["==", ["get", "tunnel"], true]]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 5, 18, 7, 20, 20], "line-dasharray": [0.1, 0.5], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-rail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(225,229,232)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.5]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-rail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(225,229,232)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-lightrail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(225,229,232)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.5]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-lightrail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(225,229,232)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-subway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(221,228,233)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 2, 16, 2, 18, 5, 19, 6, 20, 8], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.5]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-minorrail", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["==", ["get", "tunnel"], true]]], "paint": {"line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 1, 17, 2, 18, 3, 20, 5], "line-color": "rgb(212,218,223)", "line-opacity": 0.5}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge", "type": "fill", "source-layer": "bridges", "paint": {"fill-color": "rgb(243,239,235)", "fill-antialias": true, "fill-opacity": 0.8}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-pedestrian-zone", "type": "fill", "source-layer": "street_polygons", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "pedestrian"]], "paint": {"fill-color": "rgb(251,235,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.25]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "way-footway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-steps:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-path:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-cycleway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(215,224,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-track:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 2, 16, 4, 18, 18, 19, 48, 20, 96], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-pedestrian:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(221,220,218)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-livingstreet:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-minor:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-bus:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(221,220,218)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-tertiary-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-arterial-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-trunk-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-motorway-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-tertiary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "street-secondary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 2, 14, 5, 16, 8, 18, 30, 19, 68, 20, 138], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "street-primary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "street-trunk:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "street-motorway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 2, 10, 5, 14, 5, 16, 14, 18, 38, 19, 84, 20, 168], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "way-footway", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-steps", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-path", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-cycleway", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-track", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 16, 19, 44, 20, 88], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-pedestrian", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(247,247,247)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-livingstreet", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-minor", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-bus", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(247,247,247)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-pedestrian-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bicycle"], "designated"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-minor-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["living_street", "residential", "unclassified"]]], ["==", ["get", "bicycle"], "designated"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-tertiary-link", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-arterial-link", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-trunk-link", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-motorway-link", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,204,136)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-tertiary", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "street-secondary", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 1, 14, 4, 16, 6, 18, 28, 19, 64, 20, 130], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "street-primary", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "street-trunk", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "street-motorway", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,204,136)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1, 10, 4, 14, 4, 16, 12, 18, 36, 19, 80, 20, 160], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "transport-rail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "transport-rail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-lightrail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "transport-lightrail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-subway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(166,184,199)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 3, 16, 3, 18, 6, 19, 8, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "transport-minorrail:outline", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 5, 18, 7, 20, 20], "line-dasharray": [0.1, 0.5]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "aerialway:outline", "type": "line", "source-layer": "aerialways", "filter": ["any", ["==", ["get", "kind"], "cable_car"], ["==", ["get", "kind"], "gondola"], ["==", ["get", "kind"], "goods"], ["==", ["get", "kind"], "chair_lift"], ["==", ["get", "kind"], "drag_lift"], ["==", ["get", "kind"], "t-bar"], ["==", ["get", "kind"], "j-bar"], ["==", ["get", "kind"], "platter"], ["==", ["get", "kind"], "rope-tow"]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["exponential", 1], ["zoom"], 11, 1, 19, 2.5]}, "minzoom": 13, "layout": {"line-cap": "round"}, "source": "versatiles-shortbread"}, {"id": "transport-rail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-rail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-lightrail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-lightrail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-subway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(193,205,216)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 2, 16, 2, 18, 5, 19, 6, 20, 8], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-minorrail", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]]], "paint": {"line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 1, 17, 2, 18, 3, 20, 5], "line-color": "rgb(177,187,196)"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "aerialway", "type": "line", "source-layer": "aerialways", "filter": ["any", ["==", ["get", "kind"], "cable_car"], ["==", ["get", "kind"], "gondola"], ["==", ["get", "kind"], "goods"], ["==", ["get", "kind"], "chair_lift"], ["==", ["get", "kind"], "drag_lift"], ["==", ["get", "kind"], "t-bar"], ["==", ["get", "kind"], "j-bar"], ["==", ["get", "kind"], "platter"], ["==", ["get", "kind"], "rope-tow"]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["exponential", 1], ["zoom"], 11, 3, 19, 5.5], "line-dasharray": [2, 3]}, "minzoom": 13, "layout": {"line-cap": "round"}, "source": "versatiles-shortbread"}, {"id": "transport-ferry", "type": "line", "source-layer": "ferries", "minzoom": 10, "paint": {"line-color": "rgb(125,152,179)", "line-width": 1.1, "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1], "line-dasharray": [2, 2]}, "layout": {"line-join": "round"}, "source": "versatiles-shortbread"}, {"id": "bridge-way-footway:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "footway"]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 7, 18, 10, 19, 17, 20, 31]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-way-steps:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "steps"]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 7, 18, 10, 19, 17, 20, 31]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-way-paths:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["in", ["get", "kind"], ["literal", ["path", "cycleway"]]]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 7, 18, 10, 19, 17, 20, 31]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-street-track:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "bridge"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 3, 16, 6, 18, 25, 19, 67, 20, 134]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bridge"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 8, 18, 36, 19, 90, 20, 179]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-service:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "bridge"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 3, 16, 6, 18, 25, 19, 67, 20, 134]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-street-minor:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["living_street", "residential", "unclassified"]]], ["==", ["get", "bridge"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 8, 18, 36, 19, 90, 20, 179]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary-link:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 8, 18, 36, 19, 90, 20, 179]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-arterial-link:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 10, 18, 20, 20, 56]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk-link:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 10, 18, 20, 20, 56]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway-link:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 10, 18, 20, 20, 56]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 8, 18, 36, 19, 90, 20, 179]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-secondary:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 11, 3, 14, 7, 16, 11, 18, 42, 19, 95, 20, 193]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "bridge-street-primary:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1, 10, 6, 14, 8, 16, 17, 18, 50, 19, 104, 20, 202]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 3, 10, 6, 14, 8, 16, 17, 18, 50, 19, 104, 20, 202]}, "minzoom": 7, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 3, 10, 7, 14, 7, 16, 20, 18, 53, 19, 118, 20, 235]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian-zone", "type": "fill", "source-layer": "street_polygons", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "pedestrian"]], "paint": {"fill-color": "rgb(255,255,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-way-footway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-steps:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-path:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-cycleway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(215,224,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-track:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 2, 16, 4, 18, 18, 19, 48, 20, 96], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(221,220,218)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-livingstreet:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-minor:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-bus:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(221,220,218)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-arterial-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "bridge-street-secondary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 2, 14, 5, 16, 8, 18, 30, 19, 68, 20, 138], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "bridge-street-primary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 2, 10, 5, 14, 5, 16, 14, 18, 38, 19, 84, 20, 168], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "bridge-way-footway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-steps", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-path", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-cycleway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-track", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 16, 19, 44, 20, 88], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(247,247,247)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-livingstreet", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-minor", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-bus", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(247,247,247)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bicycle"], "designated"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-minor-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["living_street", "residential", "unclassified"]]], ["==", ["get", "bicycle"], "designated"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-arterial-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,204,136)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "bridge-street-secondary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 1, 14, 4, 16, 6, 18, 28, 19, 64, 20, 130], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "bridge-street-primary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,204,136)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1, 10, 4, 14, 4, 16, 12, 18, 36, 19, 80, 20, 160], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "bridge-transport-rail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "bridge-transport-rail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-lightrail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "bridge-transport-lightrail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-subway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,184,199)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 3, 16, 3, 18, 6, 19, 8, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "bridge-transport-minorrail:outline", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["==", ["get", "bridge"], true]]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 5, 18, 7, 20, 20], "line-dasharray": [0.1, 0.5]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-rail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-rail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-lightrail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-lightrail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-subway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(193,205,216)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 2, 16, 2, 18, 5, 19, 6, 20, 8], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-minorrail", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["==", ["get", "bridge"], true]]], "paint": {"line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 1, 17, 2, 18, 3, 20, 5], "line-color": "rgb(177,187,196)"}, "layout": {"line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "slot-below-symbols", "type": "background", "paint": {"background-opacity": 0}}, {"id": "boundary-country:outline", "type": "line", "source-layer": "boundaries", "filter": ["any", ["all", ["==", ["get", "admin_level"], 2], ["!=", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], ["all", ["==", ["get", "admin_level"], 2], ["==", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]]], "paint": {"line-color": "rgb(248,244,240)", "line-opacity": 0.75, "line-width": ["interpolate", ["linear"], ["zoom"], 0, 0, 3, 2, 10, 8]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 0, "source": "versatiles-shortbread"}, {"id": "boundary-state:outline", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 4], ["!=", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], "paint": {"line-color": "rgb(248,244,240)", "line-opacity": 0.75, "line-width": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 2, 10, 4]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 7, "source": "versatiles-shortbread"}, {"id": "boundary-country", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 2], ["!=", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], "paint": {"line-color": "rgb(166,166,200)", "line-width": ["interpolate", ["linear"], ["zoom"], 0, 0, 3, 1, 10, 4]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 0, "source": "versatiles-shortbread"}, {"id": "boundary-country-disputed", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 2], ["==", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], "paint": {"line-color": "rgb(190,188,207)", "line-width": ["interpolate", ["linear"], ["zoom"], 0, 0, 3, 1, 10, 4], "line-dasharray": [2, 1]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 0, "source": "versatiles-shortbread"}, {"id": "boundary-state", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 4], ["!=", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], "paint": {"line-color": "rgb(166,166,200)", "line-width": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 1, 10, 2], "line-opacity": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 1]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 7, "source": "versatiles-shortbread"}, {"id": "boundary-country-maritime", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 2], ["==", ["get", "maritime"], true], ["!=", ["get", "disputed"], true]], "paint": {"line-color": "rgb(185,210,235)", "line-width": ["interpolate", ["linear"], ["zoom"], 0, 0, 3, 1, 10, 4], "line-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "label-address-housenumber", "type": "symbol", "source-layer": "addresses", "filter": ["has", "housenumber"], "layout": {"text-field": ["case", ["has", "unit"], ["concat", ["get", "housenumber"], "/", ["get", "unit"]], ["get", "housenumber"]], "symbol-placement": "point", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 17, 8, 19, 10], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgba(15,11,7,0.302)", "text-color": "rgba(15,11,7,0.302)"}, "minzoom": 17, "source": "versatiles-shortbread"}, {"id": "marking-oneway", "type": "symbol", "source-layer": "streets", "filter": ["all", ["==", ["get", "oneway"], true], ["in", ["get", "kind"], ["literal", ["trunk", "primary", "secondary", "tertiary", "unclassified", "residential", "living_street"]]]], "layout": {"symbol-placement": "line", "symbol-spacing": 175, "icon-rotate": 90, "icon-rotation-alignment": "map", "icon-padding": 5, "symbol-avoid-edges": true, "icon-image": "base:marking-oneway"}, "minzoom": 14, "paint": {"icon-color": "rgb(0,0,0)", "text-color": "rgb(0,0,0)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4, 20, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4, 20, 0.4]}, "source": "versatiles-shortbread"}, {"id": "marking-oneway-reverse", "type": "symbol", "source-layer": "streets", "filter": ["all", ["==", ["get", "oneway_reverse"], true], ["in", ["get", "kind"], ["literal", ["trunk", "primary", "secondary", "tertiary", "unclassified", "residential", "living_street"]]]], "layout": {"symbol-placement": "line", "symbol-spacing": 75, "icon-rotate": -90, "icon-rotation-alignment": "map", "icon-padding": 5, "symbol-avoid-edges": true, "icon-image": "base:marking-oneway"}, "minzoom": 14, "paint": {"icon-color": "rgb(0,0,0)", "text-color": "rgb(0,0,0)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4, 20, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4, 20, 0.4]}, "source": "versatiles-shortbread"}, {"id": "poi-amenity", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "amenity"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "amenity"], "arts_centre", "base:icon-art_gallery", "clinic", "base:icon-doctor", "courthouse", "base:icon-justice", "food_court", "base:icon-restaurant", "public_building", "base:icon-town_hall", "university", "base:icon-college", "atm", "base:icon-atm", "bank", "base:icon-bank", "bar", "base:icon-bar", "bench", "base:icon-bench", "bicycle_rental", "base:icon-bicycle_share", "biergarten", "base:icon-beer_mug", "cafe", "base:icon-cafe", "car_rental", "base:icon-car_rental", "car_sharing", "base:icon-car_rental", "car_wash", "base:icon-car_wash", "cinema", "base:icon-cinema", "college", "base:icon-college", "community_centre", "base:icon-community", "dentist", "base:icon-dentist", "doctors", "base:icon-doctor", "drinking_water", "base:icon-drinking_water", "embassy", "base:icon-embassy", "fast_food", "base:icon-fast_food", "fire_station", "base:icon-fire_station", "fountain", "base:icon-fountain", "fuel", "base:icon-fuel_pump", "grave_yard", "base:icon-cemetery", "hospital", "base:icon-hospital", "hunting_stand", "base:icon-hunting_stand", "library", "base:icon-library", "marketplace", "base:icon-marketplace", "nightclub", "base:icon-nightclub", "nursing_home", "base:icon-nursing_home", "pharmacy", "base:icon-pill", "place_of_worship", ["match", ["get", "religion"], "christian", "base:icon-latin_cross", "muslim", "base:icon-star_and_crescent", "jewish", "base:icon-star_of_david", "buddhist", "base:icon-dharma_wheel", "hindu", "base:icon-om", "sikh", "base:icon-khanda", "taoist", "base:icon-yin_yang", "base:icon-person_kneeling_and_praying"], "police", "base:icon-police_officer", "post_box", "base:icon-postbox", "post_office", "base:icon-post", "prison", "base:icon-prison", "pub", "base:icon-pint_glass", "recycling", "base:icon-recycling", "restaurant", "base:icon-restaurant", "school", "base:icon-school", "shelter", "base:icon-shelter", "telephone", "base:icon-telephone", "theatre", "base:icon-theater", "toilets", "base:icon-restrooms", "townhall", "base:icon-town_hall", "vending_machine", "base:icon-vending_machine", "veterinary", "base:icon-veterinary", "waste_basket", "base:icon-waste_basket", "base:transport-information"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-leisure", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "leisure"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "leisure"], "dog_park", "base:icon-dog", "golf_course", "base:icon-golf", "ice_rink", "base:icon-ice_rink", "pitch", "base:icon-pitch", "playground", "base:icon-seesaw", "stadium", "base:icon-stadium", "swimming_pool", "base:icon-swimming", "water_park", "base:icon-water_park", "base:icon-sports"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-tourism", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "tourism"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "tourism"], "artwork", "base:icon-artwork", "alpine_hut", "base:icon-chalet", "bed_and_breakfast", "base:icon-lodging", "camp_site", "base:icon-campsite", "caravan_site", "base:icon-caravan", "guest_house", "base:icon-lodging", "hostel", "base:icon-lodging", "hotel", "base:icon-lodging", "motel", "base:icon-lodging", "theme_park", "base:icon-amusement_park", "chalet", "base:icon-chalet", "information", "base:transport-information", "picnic_site", "base:icon-picnic_site", "viewpoint", "base:icon-viewpoint", "zoo", "base:icon-zoo", "base:transport-information"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-shop", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "shop"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "shop"], "alcohol", "base:icon-alcohol_shop", "bakery", "base:icon-bakery", "beauty", "base:icon-beauty", "beverages", "base:icon-beverages", "books", "base:icon-books", "butcher", "base:icon-butcher", "chemist", "base:icon-tube_and_toothbrush", "clothes", "base:icon-clothes", "doityourself", "base:icon-do_it_yourself", "dry_cleaning", "base:icon-dry_cleaning", "florist", "base:icon-florist", "furniture", "base:icon-furniture", "garden_centre", "base:icon-garden_center", "general", "base:icon-shop", "gift", "base:icon-gift", "greengrocer", "base:icon-greengrocer", "hairdresser", "base:icon-scissors_and_comb", "hardware", "base:icon-hardware", "jewelry", "base:icon-ring", "kiosk", "base:icon-newspaper", "laundry", "base:icon-laundry", "newsagent", "base:icon-newsagent", "optician", "base:icon-optician", "outdoor", "base:icon-outdoor", "shoes", "base:icon-shoes", "sports", "base:icon-sports", "stationery", "base:icon-stationery", "toys", "base:icon-rocking_horse", "travel_agency", "base:icon-travel_agent", "video", "base:icon-video", "base:icon-shop"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-man_made", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "man_made"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "man_made"], "lighthouse", "base:icon-lighthouse", "wastewater_plant", "base:icon-wastewater", "water_well", "base:icon-drinking_water", "water_works", "base:icon-waterworks", "surveillance", "base:icon-surveillance", "tower", "base:icon-observation_tower", "watermill", "base:icon-watermill", "windmill", "base:icon-windmill", "base:transport-information"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-historic", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "historic"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "historic"], "castle", "base:icon-castle", "monument", "base:icon-monument", "wayside_shrine", "base:icon-shrine", "base:icon-historic"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-emergency", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "emergency"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "emergency"], "defibrillator", "base:icon-defibrillator", "fire_hydrant", "base:icon-hydrant", "phone", "base:icon-emergency_phone", ""], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-highway", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "highway"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "highway"], "emergency_access_point", "base:icon-emergency_access", ""], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-office", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "office"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "office"], "diplomatic", "base:icon-embassy", ""], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "slot-below-labels", "type": "background", "paint": {"background-opacity": 0}}, {"id": "label-motorway-exit", "type": "symbol", "source-layer": "street_labels_points", "filter": ["==", ["get", "kind"], "motorway_junction"], "layout": {"text-field": "{ref}", "symbol-placement": "point", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 9, 18, 11], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 1, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-motorway-shield", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "motorway"], "layout": {"text-field": "{ref}", "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 10, 18, 12, 20, 16], "text-font": ["noto_sans_bold"]}, "paint": {"icon-color": "rgb(255,255,255)", "text-color": "rgb(255,255,255)", "text-halo-color": "rgb(255,204,136)", "text-halo-width": 0.1, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-street-track", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "track"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-pedestrian", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "pedestrian"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-livingstreet", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "living_street"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-residential", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "residential"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-unclassified", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "unclassified"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-tertiary", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "tertiary"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-secondary", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "secondary"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-primary", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "primary"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-trunk", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "trunk"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-pedestrian-zone", "type": "symbol", "source-layer": "streets_polygons_labels", "filter": ["==", ["get", "kind"], "pedestrian"], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 10, 17, 12], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-water-area-major", "type": "symbol", "source-layer": "water_polygons_labels", "filter": ["all", ["!=", ["get", "kind"], "glacier"], [">", ["get", "way_area"], 1000000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "point", "text-size": ["interpolate", ["linear"], ["zoom"], 4, 11, 10, 14], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1], "text-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "label-water-area-large", "type": "symbol", "source-layer": "water_polygons_labels", "filter": ["all", ["!=", ["get", "kind"], "glacier"], [">", ["get", "way_area"], 10000000], ["<=", ["get", "way_area"], 1000000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "point", "text-size": ["interpolate", ["linear"], ["zoom"], 8, 10, 12, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1], "text-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "label-water-area-medium", "type": "symbol", "source-layer": "water_polygons_labels", "filter": ["all", ["!=", ["get", "kind"], "glacier"], [">", ["get", "way_area"], 100000], ["<=", ["get", "way_area"], 10000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "point", "text-size": ["interpolate", ["linear"], ["zoom"], 11, 10, 14, 12], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1], "text-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "label-water-area-small", "type": "symbol", "source-layer": "water_polygons_labels", "filter": ["all", ["!=", ["get", "kind"], "glacier"], [">", ["get", "way_area"], 0], ["<=", ["get", "way_area"], 100000]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "point", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 10, 17, 12], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1], "text-opacity": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-water-river", "type": "symbol", "source-layer": "water_lines_labels", "filter": ["in", ["get", "kind"], ["literal", ["river", "canal"]]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "line", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 12], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-water-stream", "type": "symbol", "source-layer": "water_lines_labels", "filter": ["in", ["get", "kind"], ["literal", ["stream", "ditch"]]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "line", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 9, 17, 11], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "symbol-transit-bus", "type": "symbol", "source-layer": "public_transport", "filter": ["==", ["get", "kind"], "bus_stop"], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:icon-bus", "icon-size": ["interpolate", ["linear"], ["zoom"], 16, 0.5, 18, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 16, "source": "versatiles-shortbread"}, {"id": "symbol-transit-tram", "type": "symbol", "source-layer": "public_transport", "filter": ["==", ["get", "kind"], "tram_stop"], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:transport-tram", "icon-size": ["interpolate", ["linear"], ["zoom"], 15, 0.5, 17, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 15, "source": "versatiles-shortbread"}, {"id": "symbol-transit-station", "type": "symbol", "source-layer": "public_transport", "filter": ["in", ["get", "kind"], ["literal", ["station", "halt"]]], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:icon-rail", "icon-size": ["interpolate", ["linear"], ["zoom"], 13, 0.5, 15, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "symbol-transit-airfield", "type": "symbol", "source-layer": "public_transport", "filter": ["all", ["==", ["get", "kind"], "aerodrome"], ["!", ["has", "iata"]]], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:icon-airfield", "icon-size": ["interpolate", ["linear"], ["zoom"], 13, 0.5, 15, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "symbol-transit-airport", "type": "symbol", "source-layer": "public_transport", "filter": ["all", ["==", ["get", "kind"], "aerodrome"], ["has", "iata"]], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:icon-airport", "icon-size": ["interpolate", ["linear"], ["zoom"], 12, 0.5, 14, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-place-neighbourhood", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "neighbourhood"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": 12, "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 17, 1, 18, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 17, 1, 18, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 14, "maxzoom": 18, "source": "versatiles-shortbread"}, {"id": "label-place-quarter", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "quarter"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": 13, "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 15, 1, 16, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 15, 1, 16, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 13, "maxzoom": 16, "source": "versatiles-shortbread"}, {"id": "label-place-suburb", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "suburb"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 11, 11, 13, 14], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 14, 1, 15, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 14, 1, 15, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 10, "maxzoom": 15, "source": "versatiles-shortbread"}, {"id": "label-place-hamlet", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "hamlet"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 10, 11, 12, 14], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 17, 1, 18, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 17, 1, 18, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 13, "maxzoom": 18, "source": "versatiles-shortbread"}, {"id": "label-place-village", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "village"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 9, 11, 12, 14], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 15, 1, 16, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 15, 1, 16, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 10, "maxzoom": 16, "source": "versatiles-shortbread"}, {"id": "label-place-town", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "town"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 8, 11, 12, 14], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 14, 1, 15, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 14, 1, 15, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 7, "maxzoom": 15, "source": "versatiles-shortbread"}, {"id": "label-boundary-state", "type": "symbol", "source-layer": "boundary_labels", "filter": ["in", ["get", "admin_level"], ["literal", [4, "4"]]], "layout": {"text-field": ["get", "name"], "text-anchor": "top", "text-offset": [0, 0.2], "text-padding": 0, "text-optional": true, "text-size": ["interpolate", ["linear"], ["zoom"], 5, 8, 8, 12], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(61,61,77)", "text-color": "rgb(61,61,77)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 3, "maxzoom": 10, "source": "versatiles-shortbread"}, {"id": "label-place-city", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "city"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 7, 11, 10, 14], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 13, 1, 14, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 13, 1, 14, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 6, "maxzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-place-statecapital", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "state_capital"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 6, 11, 10, 15], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 13, 1, 14, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 13, 1, 14, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 4, "maxzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-place-capital", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "capital"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 5, 12, 10, 16], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 11, 1, 12, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 11, 1, 12, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 4, "maxzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-boundary-country-small", "type": "symbol", "source-layer": "boundary_labels", "filter": ["all", ["in", ["get", "admin_level"], ["literal", [2, "2"]]], ["<=", ["get", "way_area"], 10000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "top", "text-offset": [0, 0.2], "text-padding": 0, "text-optional": true, "text-size": ["interpolate", ["linear"], ["zoom"], 4, 8, 5, 11], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 4, "maxzoom": 10, "source": "versatiles-shortbread"}, {"id": "label-boundary-country-medium", "type": "symbol", "source-layer": "boundary_labels", "filter": ["all", ["in", ["get", "admin_level"], ["literal", [2, "2"]]], ["<", ["get", "way_area"], 90000000], [">", ["get", "way_area"], 10000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "top", "text-offset": [0, 0.2], "text-padding": 0, "text-optional": true, "text-size": ["interpolate", ["linear"], ["zoom"], 3, 8, 5, 12], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 2, "maxzoom": 10, "source": "versatiles-shortbread"}, {"id": "label-boundary-country-large", "type": "symbol", "source-layer": "boundary_labels", "filter": ["all", ["in", ["get", "admin_level"], ["literal", [2, "2"]]], [">=", ["get", "way_area"], 90000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "top", "text-offset": [0, 0.2], "text-padding": 0, "text-optional": true, "text-size": ["interpolate", ["linear"], ["zoom"], 2, 8, 5, 13], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 2, "maxzoom": 9, "source": "versatiles-shortbread"}], "sky": {"sky-color": "rgb(191,217,242)", "horizon-color": "rgb(255,255,255)", "fog-color": "rgb(255,255,255)", "sky-horizon-blend": 0.8, "horizon-fog-blend": 0.8, "fog-ground-blend": 0.5, "atmosphere-blend": 0}, "projection": {"type": "globe"}} \ No newline at end of file diff --git a/android-vectorstyle/src/androidTest/java/com/mapconductor/vectorstyle/VectorStyleRulesTest.kt b/android-vectorstyle/src/androidTest/java/com/mapconductor/vectorstyle/VectorStyleRulesTest.kt new file mode 100644 index 000000000..5324f92cf --- /dev/null +++ b/android-vectorstyle/src/androidTest/java/com/mapconductor/vectorstyle/VectorStyleRulesTest.kt @@ -0,0 +1,149 @@ +package com.mapconductor.vectorstyle + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.map.StyleMutation +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * The whole chain, on a device: Rust compiler, JNI, Kotlin. + * + * What is being checked is not the compiler — that has its own tests and + * golden files in Rust — but that this binding carries the answer across + * unchanged. The numbers asserted here are the ones + * `crates/mvt-style/tests/golden/versatiles-road-emphasis.json` records, so + * a binding that quietly loses or mangles something fails rather than + * producing a slightly different map. + * + * The same assertions exist in `bindings/js-style/test/compile.test.mjs` + * and in `VectorStyleRulesTests` on iOS. + */ +@RunWith(AndroidJUnit4::class) +class VectorStyleRulesTest { + private val style: String by lazy { + InstrumentationRegistry + .getInstrumentation() + .context.assets + .open("versatiles-colorful.json") + .use { it.readBytes().decodeToString() } + } + + private val roadEmphasis = + """ + { + "schemaVersion": 1, + "rules": [ + { "selector": "all", "patch": { "color": "#000000" } }, + { "selector": { "role": "label" }, "patch": { "visible": false } }, + { "selector": { "role": "road-casing" }, "patch": { "color": "#303030" } }, + { "selector": { "role": "road" }, "patch": { "color": "#ffffff", "widthScale": 1.3 } } + ] + } + """.trimIndent() + + @Test + fun adjustsARealStyleAndSaysWhatItDid() { + val compiled = VectorStyleRules.compile(style, roadEmphasis) + + assertEquals(StyleAffects.BOTH, compiled.affects) + assertTrue("this style has a background already", compiled.patchable) + // The same counts the Rust golden records, reached through JNI. + assertTrue( + compiled.diagnostics.joinToString("\n"), + compiled.diagnostics.any { it.contains("schema: shortbread") }, + ) + assertTrue( + compiled.diagnostics.joinToString("\n"), + compiled.diagnostics.any { it.contains("rule 3 matched 77 layers") }, + ) + + assertTrue("only ${compiled.mutations.size} mutations", compiled.mutations.size > 400) + // Every mutation carries what was there before, or nothing could be + // taken back when the rules change. + for (mutation in compiled.mutations.take(50)) { + assertNotNull(mutation.reversed()) + } + + val layers = JSONObject(compiled.styleJson).getJSONArray("layers") + assertEquals("no layer was added or lost", 280, layers.length()) + } + + @Test + fun leavesAloneWhatNoRuleNamed() { + val compiled = + VectorStyleRules.compile( + style, + """{"schemaVersion":1,"rules":[{"selector":{"role":"water"},"patch":{"color":"#000"}}]}""", + ) + val before = JSONObject(style) + val after = JSONObject(compiled.styleJson) + assertEquals(before.getJSONObject("sources").toString(), after.getJSONObject("sources").toString()) + assertEquals(before.optString("name"), after.optString("name")) + } + + @Test + fun describesWhatIsInAStyle() { + val layers = VectorStyleRules.describe(style) + assertEquals(280, layers.size) + val casing = layers.first { it.id.endsWith(":outline") && it.roles.contains("road") } + assertEquals(listOf("road", "road-casing"), casing.roles) + assertEquals("shortbread:streets", casing.evidence.first()) + } + + /** + * A rule set written for a newer build must be refused loudly, not + * applied in part. + */ + @Test + fun refusesARulesDocumentItDoesNotUnderstand() { + val error = + assertThrows(VectorStyleException::class.java) { + VectorStyleRules.compile(style, """{"schemaVersion":99,"rules":[]}""") + } + assertTrue(error.message, error.message!!.contains("schemaVersion")) + } + + @Test + fun refusesAStyleItCannotRead() { + assertThrows(VectorStyleException::class.java) { + VectorStyleRules.compile("{ not json", """{"schemaVersion":1,"rules":[]}""") + } + assertThrows(VectorStyleException::class.java) { + VectorStyleRules.describe("{ not json") + } + } + + @Test + fun reportsTheRulesVersionItWasBuiltWith() { + assertEquals(1, VectorStyleRules.schemaVersion) + } + + /** + * The mutations have to survive the trip through core's parser with + * their values intact — a colour that lost its quotes is a colour no + * renderer can read back. + */ + @Test + fun mutationsArriveAsCoreTypesWithTheirValues() { + val compiled = + VectorStyleRules.compile( + style, + """{"schemaVersion":1,"rules":[{"selector":{"layerId":"background"},"patch":{"color":"#010203"}}]}""", + ) + val paint = compiled.mutations.filterIsInstance().single() + assertEquals("background", paint.layerId) + assertEquals("background-color", paint.key) + assertEquals("\"#010203\"", paint.value) + // The document says `rgb(248,244,240)`; what comes back is the same + // colour written the one way every renderer can read. MapLibre on + // iOS parses the colour itself, so the compiler canonicalises every + // one that crosses the boundary. + assertEquals("\"#f8f4f0\"", paint.previous) + } +} diff --git a/android-vectorstyle/src/androidTest/java/com/mapconductor/vectorstyle/VectorStyleTest.kt b/android-vectorstyle/src/androidTest/java/com/mapconductor/vectorstyle/VectorStyleTest.kt new file mode 100644 index 000000000..f6dce69d7 --- /dev/null +++ b/android-vectorstyle/src/androidTest/java/com/mapconductor/vectorstyle/VectorStyleTest.kt @@ -0,0 +1,431 @@ +package com.mapconductor.vectorstyle + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.map.AttributionRule +import com.mapconductor.core.map.MapServiceRegistry +import com.mapconductor.core.map.MapStyleHost +import com.mapconductor.core.map.MapStyleInstallation +import com.mapconductor.core.map.MutableMapServiceRegistry +import com.mapconductor.core.map.StyleMutation +import com.mapconductor.core.map.StyleMutationStore +import com.mapconductor.core.map.VectorStyleMutationSupportKey +import com.mapconductor.core.map.VectorStyleSupport +import com.mapconductor.core.map.VectorStyleSupportKey +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.tileserver.LocalTileServer +import com.mapconductor.core.tileserver.TileServerRegistry +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 org.junit.runner.RunWith +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +/** + * What [VectorStyle] does to a map, against a map that is only a recorder. + * + * No provider is involved on purpose. What is being checked is the contract + * every provider will be held to — which route a backend's capabilities put + * it on, that changing the rules does not reload anything, and that + * disposing leaves nothing behind — and a fake host is the only way to check + * all of those without three real maps. + */ +@RunWith(AndroidJUnit4::class) +class VectorStyleTest { + private val style = + """ + {"version":8,"name":"test", + "sources":{"s":{"type":"vector","tiles":["https://x/{z}/{x}/{y}"],"attribution":"© Someone"}}, + "layers":[ + {"id":"bg","type":"background","paint":{"background-color":"#f8f4f0"}}, + {"id":"water","type":"fill","source":"s","source-layer":"water","paint":{"fill-color":"#a0c8f0"}}, + {"id":"roads","type":"line","source":"s","source-layer":"transportation", + "paint":{"line-color":"#888","line-width":2}}, + {"id":"labels","type":"symbol","source":"s","source-layer":"place","paint":{"text-color":"#333"}} + ]} + """.trimIndent() + + private fun rules(color: String) = + StyleRules.parse("""{"schemaVersion":1,"rules":[{"selector":{"role":"road"},"patch":{"color":"$color"}}]}""") + + // ---- the fake map ------------------------------------------------ + + private class Host( + vector: Boolean, + mutations: Boolean, + override val vectorStyleUrl: String? = null, + ) : MapStyleHost { + val registry = MutableMapServiceRegistry() + val shownStyles = mutableListOf() + val applied = mutableListOf>() + val rasters = mutableListOf() + val diagnostics = mutableListOf() + + /** Set to fail the mutations whose key matches, as iOS MapLibre does. */ + var refuse: (StyleMutation) -> Boolean = { false } + + val store = + StyleMutationStore { list -> + applied += list + list.filter(refuse) + } + + init { + if (vector) { + registry.put( + VectorStyleSupportKey, + object : VectorStyleSupport { + override fun showStyle( + styleUrl: String, + attributionRules: List, + ) { + shownStyles += styleUrl + credited += attributionRules.map { it.attribution } + } + + override fun clearStyle() { + shownStyles += null + } + }, + ) + } + if (mutations) registry.put(VectorStyleMutationSupportKey, store) + } + + val credited = mutableListOf() + var styleLoadedBlock: (() -> Unit)? = null + + override val serviceRegistry: MapServiceRegistry get() = registry + override val tileServer: LocalTileServer get() = TileServerRegistry.get() + + override fun onStyleLoaded(block: () -> Unit): MapStyleInstallation { + styleLoadedBlock = block + return MapStyleInstallation.of { styleLoadedBlock = null } + } + + override fun upsertRaster(state: RasterLayerState) { + rasters += state.id + } + + override fun removeRaster(id: String) { + rasters -= id + } + + override fun report(diagnostics: List) { + this.diagnostics += diagnostics + } + } + + private class Rasteriser : VectorStyleRasteriser { + val installed = mutableListOf() + val restyled = mutableListOf() + var disposals = 0 + + override fun install( + host: MapStyleHost, + styleJson: String, + affects: StyleAffects, + ): VectorStyleRasterisation { + installed += styleJson + return object : VectorStyleRasterisation { + override fun restyle( + styleJson: String, + affects: StyleAffects, + ) { + restyled += styleJson + } + + override fun dispose() { + disposals += 1 + } + } + } + } + + /** The work happens on a worker; wait for it to land rather than guess. */ + private fun settle( + host: Host, + until: () -> Boolean, + ) { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (!until() && System.nanoTime() < deadline) Thread.sleep(10) + assertTrue("nothing happened: ${host.diagnostics}", until()) + } + + // ---- the routes -------------------------------------------------- + + /** + * A map that reads styles and takes patches gets the author's document + * and the differences on top -- not the adjusted document. The next rule + * change produces differences against the original, and a map holding an + * already-adjusted document would read them as something else. + */ + @Test + fun aMapThatReadsStylesIsGivenTheOriginalAndTheDifferences() { + val host = Host(vector = true, mutations = true) + val installation = + VectorStyle(document = VectorStyleSource.Text(style), rules = rules("#ffffff")) + .install(host) + try { + settle(host) { host.applied.isNotEmpty() } + + assertEquals(1, host.shownStyles.size) + val served = host.tileServer.let { _ -> host.shownStyles.single()!! } + assertTrue("expected a served document, got $served", served.contains("/docs/")) + val paint = + host.applied + .flatten() + .filterIsInstance() + .single() + assertEquals("roads", paint.layerId) + assertEquals("\"#ffffff\"", paint.value) + // The document says `#888`; what comes back is the same colour + // in the one form every renderer can read. MapLibre on iOS + // parses the colour itself, so the compiler canonicalises every + // one that crosses the boundary. + assertEquals("\"#888888\"", paint.previous) + assertTrue("the style's credit was not carried", host.credited.contains("© Someone")) + } finally { + installation.dispose() + } + } + + /** + * The point of the whole design: moving a slider sends new differences + * and the map is never handed a document again. + */ + @Test + fun changingTheRulesDoesNotReloadAnything() { + val host = Host(vector = true, mutations = true) + val first = VectorStyle(document = VectorStyleSource.Text(style), rules = rules("#ffffff")) + val installation = first.install(host) + try { + settle(host) { host.applied.isNotEmpty() } + val servedOnce = host.shownStyles.size + + val again = VectorStyle(document = VectorStyleSource.Text(style), rules = rules("#ff0000")) + assertTrue("the installed style refused an adjustment-only change", installation.update(again)) + settle(host) { host.applied.size > 1 } + + assertEquals("the map was handed a document again", servedOnce, host.shownStyles.size) + val last = + host.applied + .last() + .filterIsInstance() + .single() + assertEquals("\"#ff0000\"", last.value) + assertEquals("still relative to the author's style", "\"#888888\"", last.previous) + } finally { + installation.dispose() + } + } + + /** A different document is a different style, so the view has to redo it. */ + @Test + fun aDifferentDocumentIsNotAnUpdate() { + val host = Host(vector = true, mutations = true) + val installation = + VectorStyle(document = VectorStyleSource.Text(style), rules = rules("#ffffff")).install(host) + try { + settle(host) { host.applied.isNotEmpty() } + assertFalse( + installation.update( + VectorStyle(document = VectorStyleSource.Url("https://example.test/s.json")), + ), + ) + } finally { + installation.dispose() + } + } + + /** + * A map that reads styles but cannot be patched has only one way to show + * an adjustment: the adjusted document. Every rule change reloads, which + * is why the capability is worth implementing. + */ + @Test + fun aMapThatCannotBePatchedIsGivenTheAdjustedDocument() { + val host = Host(vector = true, mutations = false) + val installation = + VectorStyle(document = VectorStyleSource.Text(style), rules = rules("#ffffff")).install(host) + try { + settle(host) { host.shownStyles.isNotEmpty() } + assertTrue(host.applied.isEmpty()) + // What was served is the adjusted document, not the original. + val body = fetchServed(host.shownStyles.single()!!) + assertTrue("the original was served instead: $body", body.contains("\"#ffffff\"")) + } finally { + installation.dispose() + } + } + + @Test + fun aMapThatCannotReadStylesGoesThroughTheRasteriser() { + val host = Host(vector = false, mutations = false) + val rasteriser = Rasteriser() + val installation = + VectorStyle( + document = VectorStyleSource.Text(style), + rules = rules("#ffffff"), + rasteriser = rasteriser, + ).install(host) + try { + settle(host) { rasteriser.installed.isNotEmpty() } + assertTrue(rasteriser.installed.single().contains("\"#ffffff\"")) + assertTrue("the map was handed a style it cannot read", host.shownStyles.isEmpty()) + + // A rule change re-rasterises; it does not install again. + assertTrue( + installation.update( + VectorStyle( + document = VectorStyleSource.Text(style), + rules = rules("#ff0000"), + rasteriser = rasteriser, + ), + ), + ) + settle(host) { rasteriser.restyled.isNotEmpty() } + assertEquals(1, rasteriser.installed.size) + assertTrue(rasteriser.restyled.single().contains("\"#ff0000\"")) + } finally { + installation.dispose() + assertEquals(1, rasteriser.disposals) + } + } + + /** + * A backend that can do neither is told so. Left to itself it would show + * an ordinary map and the adjustments would simply not be there, which + * is the failure this whole design is built against. + */ + @Test + fun aMapWithNeitherIsToldSoRatherThanLeftBlank() { + val host = Host(vector = false, mutations = false) + val installation = VectorStyle(document = VectorStyleSource.Text(style)).install(host) + try { + settle(host) { host.diagnostics.any { it.contains("no rasteriser") } } + } finally { + installation.dispose() + } + } + + /** Adjusting "whatever is showing" needs something to be showing. */ + @Test + fun adjustingTheCurrentDesignNeedsAStyleToAdjust() { + val host = Host(vector = true, mutations = true, vectorStyleUrl = null) + val installation = VectorStyle(rules = rules("#ffffff")).install(host) + try { + settle(host) { host.diagnostics.any { it.contains("not drawing a vector style") } } + assertTrue(host.applied.isEmpty()) + } finally { + installation.dispose() + } + } + + // ---- what the map would not take --------------------------------- + + @Test + fun whatTheMapRefusesIsReportedAndTheRestStays() { + val host = Host(vector = true, mutations = true) + host.refuse = { true } + val installation = + VectorStyle(document = VectorStyleSource.Text(style), rules = rules("#ffffff")).install(host) + try { + settle(host) { host.diagnostics.any { it.contains("were not applied") } } + // REPORT is the default, so the document was not re-served. + assertEquals(1, host.shownStyles.size) + } finally { + installation.dispose() + } + } + + @Test + fun reloadPolicyHandsOverTheAdjustedDocumentInstead() { + val host = Host(vector = true, mutations = true) + host.refuse = { true } + val installation = + VectorStyle( + document = VectorStyleSource.Text(style), + rules = rules("#ffffff"), + onUnsupported = UnsupportedPolicy.RELOAD, + ).install(host) + try { + settle(host) { host.shownStyles.size >= 2 } + val body = fetchServed(host.shownStyles.last()!!) + assertTrue("the adjusted document was not served: $body", body.contains("\"#ffffff\"")) + } finally { + installation.dispose() + } + } + + // ---- taking it off again ----------------------------------------- + + @Test + fun disposingLeavesTheMapAsItWasFound() { + val host = Host(vector = true, mutations = true) + val installation = + VectorStyle(document = VectorStyleSource.Text(style), rules = rules("#ffffff")).install(host) + settle(host) { host.applied.isNotEmpty() } + val served = host.shownStyles.single()!! + + installation.dispose() + + assertTrue("the style was not cleared", host.shownStyles.contains(null)) + assertTrue("the adjustments were not taken off", host.store.applied.isEmpty()) + assertNull("the document is still being served", fetchServedOrNull(served)) + assertNull("the style-loaded hook is still attached", host.styleLoadedBlock) + } + + /** Disposing twice is what a view does on a fast remount. */ + @Test + fun disposingTwiceIsHarmless() { + val host = Host(vector = true, mutations = true) + val installation = + VectorStyle(document = VectorStyleSource.Text(style), rules = rules("#ffffff")).install(host) + settle(host) { host.applied.isNotEmpty() } + installation.dispose() + installation.dispose() + assertEquals(1, host.shownStyles.count { it == null }) + } + + @Test + fun theDiagnosticsAlwaysSayWhatTheRulesMatched() { + val host = Host(vector = true, mutations = true) + val heard = mutableListOf() + val latch = CountDownLatch(1) + val installation = + VectorStyle( + document = VectorStyleSource.Text(style), + rules = rules("#ffffff"), + onDiagnostics = { + heard += it + latch.countDown() + }, + ).install(host) + try { + assertTrue(latch.await(10, TimeUnit.SECONDS)) + assertNotNull(heard.firstOrNull { it.contains("matched 1 layers") }) + } finally { + installation.dispose() + } + } + + // ---- helpers ----------------------------------------------------- + + private fun fetchServed(url: String): String = fetchServedOrNull(url) ?: error("nothing served at $url") + + private fun fetchServedOrNull(url: String): String? = + runCatching { + (java.net.URL(url).openConnection() as java.net.HttpURLConnection).run { + try { + if (responseCode !in 200..299) return null + inputStream.use { it.readBytes().decodeToString() } + } finally { + disconnect() + } + } + }.getOrNull() +} diff --git a/android-vectorstyle/src/androidTest/res/xml/network_security_config.xml b/android-vectorstyle/src/androidTest/res/xml/network_security_config.xml new file mode 100644 index 000000000..f82269d45 --- /dev/null +++ b/android-vectorstyle/src/androidTest/res/xml/network_security_config.xml @@ -0,0 +1,12 @@ + + + + + 127.0.0.1 + localhost + + diff --git a/android-vectorstyle/src/main/AndroidManifest.xml b/android-vectorstyle/src/main/AndroidManifest.xml new file mode 100644 index 000000000..bfcdde2ad --- /dev/null +++ b/android-vectorstyle/src/main/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/NativeStyleCompiler.kt b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/NativeStyleCompiler.kt new file mode 100644 index 000000000..a474160dc --- /dev/null +++ b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/NativeStyleCompiler.kt @@ -0,0 +1,44 @@ +package com.mapconductor.vectorstyle + +/** + * The JNI surface of the vector style compiler. + * + * Owned by the `mapconductor-vectortile` repository and copied here by its + * `scripts/sync-sdk.sh`. **Do not edit this file in the SDK**: the next sync + * puts the upstream copy back, silently, and the change goes with it. + * + * Two calls, both JSON in and JSON out. The whole surface is this small + * because the compiler holds no state -- a style and a rule set go in, an + * adjusted style and the deltas come out -- so there is no handle to open or + * free, and no thread the calls have to be made on. + */ +internal object NativeStyleCompiler { + init { + System.loadLibrary("mvt_style_jni") + } + + /** + * The compiled result as JSON: the adjusted style, the mutations, what + * they affect and the diagnostics -- or `{"error": "..."}` when a + * document could not be read. + * + * A document that cannot be read is answered, not thrown: a rule set + * from a server or a style that failed to load is an ordinary thing to + * handle, not an exceptional one. Only a panic becomes an exception. + */ + external fun nativeCompile( + styleJson: String, + rulesJson: String, + ): String + + /** The style's layers and the role each would be given, as a JSON array. */ + external fun nativeDescribe(styleJson: String): String + + /** + * The rules document version this library understands. + * + * Read when the Kotlin side writes a rules document, so the two can + * never disagree about the shape they are exchanging. + */ + external fun nativeSchemaVersion(): Int +} diff --git a/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/StyleRules.kt b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/StyleRules.kt new file mode 100644 index 000000000..e375a307f --- /dev/null +++ b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/StyleRules.kt @@ -0,0 +1,395 @@ +package com.mapconductor.vectorstyle + +import androidx.compose.ui.graphics.Color + +/** + * What to change about a style, and where. + * + * ```kotlin + * val rules = StyleRules.build { + * all { color = Color.Black } + * role(LayerRole.LABEL) { visible = false } + * role(LayerRole.ROAD_CASING) { color = Color(0xFF303030) } + * role(LayerRole.ROAD) { color = Color.White; widthScale = 1.3f } + * } + * ``` + * + * Rules apply in order and override each other property by property, the way + * CSS does: the last rule to name a colour wins, and a rule that says nothing + * about width leaves the width alone. Reordering the two road rules above + * gives a different map, which is the point — only the app knows whether the + * casings should keep their own colour. + * + * ## It is JSON underneath, on purpose + * + * [json] is the real definition, not a serialisation of the builder. The same + * text is what the compiler reads on Android, iOS and the web, so a rule set + * can be written by hand, stored, shipped from a server, or diffed between + * two versions of an app — and [parse] takes it straight back. The builder is + * sugar over that, there so the common case is checked by the compiler rather + * than by a typo. + * + * Nothing is validated here. A rule set is checked when it is compiled + * against a style, which is the only place that can tell whether + * `role("road")` means anything. + */ +class StyleRules private constructor( + /** The canonical form. */ + val json: String, +) { + override fun equals(other: Any?): Boolean = other is StyleRules && other.json == json + + override fun hashCode(): Int = json.hashCode() + + override fun toString(): String = json + + companion object { + /** No adjustments: the style as its author wrote it. */ + @JvmField + val NONE: StyleRules = StyleRules("""{"schemaVersion":1,"rules":[]}""") + + /** + * Takes a rules document as it stands. + * + * Not checked here — a document is checked when it is compiled + * against a style, and [VectorStyleRules.compile] throws then. + */ + @JvmStatic + fun parse(json: String): StyleRules = StyleRules(json) + + /** Writes a rules document with the compiler checking the shape. */ + @JvmStatic + fun build(block: StyleRulesBuilder.() -> Unit): StyleRules = + StyleRules(StyleRulesBuilder().apply(block).toJson()) + } +} + +/** + * The roles the built-in schema profiles assign. + * + * Strings rather than an enum: a style cut to a schema nobody here has heard + * of can name its own roles through [StyleRulesBuilder.schema], and adding a + * role to the built-in tables must not be a breaking change on three + * platforms. + */ +object LayerRole { + const val BACKGROUND = "background" + const val WATER = "water" + const val WATERWAY = "waterway" + const val LAND = "land" + const val LANDUSE = "landuse" + const val PARK = "park" + const val BUILDING = "building" + const val ROAD = "road" + + /** + * The wide dark line drawn under a road to give it an edge. + * + * A style draws every road twice, and "make roads white" applied to both + * halves gives a white slab rather than a road. Nothing in the tile + * distinguishes them — only the layer's name does — so this is the one + * role decided by a naming convention, and the compiler reports how many + * layers it found. + */ + const val ROAD_CASING = "road-casing" + const val RAIL = "rail" + const val TRANSIT = "transit" + const val BOUNDARY = "boundary" + const val AEROWAY = "aeroway" + const val LABEL = "label" + const val POI = "poi" +} + +/** A style layer's `type`, for [StyleSelector.Kind]. */ +enum class StyleLayerKind( + internal val wire: String, +) { + BACKGROUND("background"), + FILL("fill"), + LINE("line"), + CIRCLE("circle"), + SYMBOL("symbol"), + + /** Everything else: raster, hillshade, heatmap, fill-extrusion, sky. */ + OTHER("other"), +} + +/** Which layers a rule reaches. */ +sealed interface StyleSelector { + /** Every layer in the style, including the background. */ + object All : StyleSelector + + /** What the layer *is*, across schemas that name their sources differently. */ + data class Role( + val role: String, + ) : StyleSelector + + /** The layer's `id`, as a glob: `*` for any run, `?` for one character. */ + data class LayerId( + val glob: String, + ) : StyleSelector + + data class SourceLayer( + val name: String, + ) : StyleSelector + + data class Kind( + val kind: StyleLayerKind, + ) : StyleSelector + + data class AnyOf( + val of: List, + ) : StyleSelector + + data class AllOf( + val of: List, + ) : StyleSelector + + data class Not( + val of: StyleSelector, + ) : StyleSelector +} + +/** Builds the `rules` array. */ +class StyleRulesBuilder internal constructor() { + /** + * Which tile schema the style's `source-layer` names come from. + * + * Left alone it is worked out from the style, which is right for + * OpenMapTiles, Shortbread and Mapbox Streets. Name one to be sure, or + * supply [customSchema] for a schema the compiler has never seen. + */ + var schema: String? = null + + private var custom: Map>? = null + private val rules = mutableListOf() + + /** + * Teaches the compiler a schema of your own: role name to the + * `source-layer` names that carry it. + */ + fun customSchema(roles: Map>) { + custom = roles + } + + fun all(patch: StylePatchBuilder.() -> Unit) = where(StyleSelector.All, patch) + + fun role( + role: String, + patch: StylePatchBuilder.() -> Unit, + ) = where(StyleSelector.Role(role), patch) + + fun layerId( + glob: String, + patch: StylePatchBuilder.() -> Unit, + ) = where(StyleSelector.LayerId(glob), patch) + + fun sourceLayer( + name: String, + patch: StylePatchBuilder.() -> Unit, + ) = where(StyleSelector.SourceLayer(name), patch) + + fun kind( + kind: StyleLayerKind, + patch: StylePatchBuilder.() -> Unit, + ) = where(StyleSelector.Kind(kind), patch) + + /** For a selector built by hand: [StyleSelector.AllOf], [StyleSelector.Not] and friends. */ + fun where( + selector: StyleSelector, + patch: StylePatchBuilder.() -> Unit, + ) { + val body = StylePatchBuilder().apply(patch).toJson() + rules += """{"selector":${selector.toJson()},"patch":$body}""" + } + + internal fun toJson(): String = + buildString { + append("""{"schemaVersion":1""") + custom?.let { roles -> + append(""","schema":{"roles":{""") + append( + roles.entries.joinToString(",") { (role, layers) -> + """${quote(role)}:[${layers.joinToString(",") { quote(it) }}]""" + }, + ) + append("}}") + } ?: schema?.let { append(""","schema":${quote(it)}""") } + append(""","rules":[""") + append(rules.joinToString(",")) + append("]}") + } +} + +/** Builds one rule's `patch`. */ +class StylePatchBuilder internal constructor() { + private val fields = mutableListOf() + private val properties = mutableListOf() + + /** `layout.visibility`. */ + var visible: Boolean? = null + set(value) { + field = value + value?.let { fields += """"visible":$it""" } + } + + /** + * The layer's colour, whichever property that is for its type: + * `fill-color` on a fill, `line-color` on a line, `text-color` and + * `icon-color` on a symbol, `background-color` on the background. + */ + var color: Color? = null + set(value) { + field = value + value?.let { fields += """"color":${quote(it.toStyleText())}""" } + } + + /** `*-opacity`, 0 to 1. */ + var opacity: Float? = null + set(value) { + field = value + value?.let { fields += """"opacity":$it""" } + } + + /** + * Multiplies how fat the layer is drawn: `line-width` on a line, + * `circle-radius` on a circle. + * + * A multiplier rather than a value because the width is almost always an + * expression over zoom, and replacing it with a number would throw that + * curve away. + */ + var widthScale: Float? = null + set(value) { + field = value + value?.let { fields += """"widthScale":$it""" } + } + + var minZoom: Float? = null + set(value) { + field = value + value?.let { fields += """"minZoom":$it""" } + } + + var maxZoom: Float? = null + set(value) { + field = value + value?.let { fields += """"maxZoom":$it""" } + } + + /** Drains the colour the style chose, 0 to 1. */ + fun desaturate(amount: Float) { + fields += """"colorFilter":{"desaturate":$amount}""" + } + + fun darken(amount: Float) { + fields += """"colorFilter":{"darken":$amount}""" + } + + fun lighten(amount: Float) { + fields += """"colorFilter":{"lighten":$amount}""" + } + + /** + * Flips how light each colour is and keeps its hue: the cheapest way to + * get a dark basemap out of a light one without naming a single colour. + */ + fun invertLightness() { + fields += """"colorFilter":{"invertLightness":true}""" + } + + /** Blends what is there towards [target]. */ + fun mix( + target: Color, + amount: Float = 0.5f, + ) { + fields += """"colorFilter":{"mix":{"color":${quote(target.toStyleText())},"amount":$amount}}""" + } + + /** Replaces the layer's filter, as a MapLibre filter expression in JSON. */ + fun filter(json: String) { + fields += """"filter":$json""" + } + + /** + * Any style-spec property by name, as JSON. The last word: applied after + * everything above, including over a [color] in the same rule. + * + * The escape hatch for what the fields above do not name — + * `text-field`, `fill-pattern`, `line-dasharray`, a `fill-extrusion` + * height. Note that a property the SDK's own rasteriser cannot draw will + * show only on a map that renders the style itself; the compiler says so + * in its diagnostics. + */ + fun property( + key: String, + valueJson: String, + ) { + properties += """${quote(key)}:$valueJson""" + } + + /** [property] for a plain text value, quoted for you. */ + fun propertyText( + key: String, + value: String, + ) = property(key, quote(value)) + + internal fun toJson(): String { + val all = fields.toMutableList() + if (properties.isNotEmpty()) all += """"properties":{${properties.joinToString(",")}}""" + return "{${all.joinToString(",")}}" + } +} + +internal fun StyleSelector.toJson(): String = + when (this) { + StyleSelector.All -> "\"all\"" + is StyleSelector.Role -> """{"role":${quote(role)}}""" + is StyleSelector.LayerId -> """{"layerId":${quote(glob)}}""" + is StyleSelector.SourceLayer -> """{"sourceLayer":${quote(name)}}""" + is StyleSelector.Kind -> """{"kind":${quote(kind.wire)}}""" + is StyleSelector.AnyOf -> """{"anyOf":[${of.joinToString(",") { it.toJson() }}]}""" + is StyleSelector.AllOf -> """{"allOf":[${of.joinToString(",") { it.toJson() }}]}""" + is StyleSelector.Not -> """{"not":${of.toJson()}}""" + } + +/** + * `#rrggbb`, or `rgba(...)` when it is not fully opaque. + * + * Compose keeps its channels as floats in whatever colour space the caller + * used; a style wants eight-bit sRGB, so the conversion happens here rather + * than being left to whoever reads the JSON. + */ +internal fun Color.toStyleText(): String { + val srgb = convert(androidx.compose.ui.graphics.colorspace.ColorSpaces.Srgb) + val r = (srgb.red * 255f).toInt().coerceIn(0, 255) + val g = (srgb.green * 255f).toInt().coerceIn(0, 255) + val b = (srgb.blue * 255f).toInt().coerceIn(0, 255) + return if (srgb.alpha >= 1f) { + String.format("#%02x%02x%02x", r, g, b) + } else { + "rgba($r,$g,$b,${"%.3f".format(srgb.alpha).trimEnd('0').trimEnd('.')})" + } +} + +/** + * A JSON string literal. + * + * Written here rather than through `org.json`, which is a throwing stub in + * JVM unit tests — the builder has to be testable without a device. + */ +internal fun quote(text: String): String = + buildString(text.length + 2) { + append('"') + for (c in text) { + when (c) { + '"' -> append("\\\"") + '\\' -> append("\\\\") + '\n' -> append("\\n") + '\r' -> append("\\r") + '\t' -> append("\\t") + else -> if (c < ' ') append("\\u%04x".format(c.code)) else append(c) + } + } + append('"') + } diff --git a/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/VectorStyle.kt b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/VectorStyle.kt new file mode 100644 index 000000000..ced8078b4 --- /dev/null +++ b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/VectorStyle.kt @@ -0,0 +1,401 @@ +package com.mapconductor.vectorstyle + +import com.mapconductor.core.map.AttributionRule +import com.mapconductor.core.map.MapStyleHost +import com.mapconductor.core.map.MapStyleInstallation +import com.mapconductor.core.map.MapViewStyle +import com.mapconductor.core.map.VectorStyleMutationSupportKey +import com.mapconductor.core.map.VectorStyleSupportKey +import java.net.HttpURLConnection +import java.net.URL +import android.os.Handler +import android.os.Looper +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicBoolean +import android.util.Log + +/** + * A vector style, with adjustments, as the map's appearance. + * + * ```kotlin + * MapLibreMapView( + * state = state, + * style = VectorStyle( + * rules = StyleRules.build { + * all { color = Color.Black } + * role(LayerRole.LABEL) { visible = false } + * role(LayerRole.ROAD) { color = Color.White } + * }, + * ), + * ) + * ``` + * + * What happens underneath depends on the backend, and the app does not have + * to know: + * + * - **A map that reads vector styles** (MapLibre, Mapbox, MapTiler) is given + * the document and told the per-layer differences. Changing the rules + * later sends new differences and **reloads nothing** — which is the whole + * reason the adjustments are compiled into deltas as well as a document. + * - **A map that cannot** (Google Maps, MapKit, HERE, ArcGIS...) is handed + * raster tiles drawn from the adjusted document, if the app passed a + * [rasteriser]. Changing the rules re-rasterises and refetches nothing. + * + * Either way the same rules produce the same map, because both paths start + * from one compilation of one style. + * + * ## What it reports + * + * Quietly doing nothing is the failure this design is built against, so + * [onDiagnostics] always hears how many layers each rule matched, which + * matched none, what this backend would not take, and what the rasteriser + * will not draw. A rule written for the wrong tile schema produces a + * perfectly good map with nothing changed on it; nothing else says so. + */ +class VectorStyle( + /** Which style to adjust. Defaults to whatever the map is already drawing. */ + val document: VectorStyleSource = VectorStyleSource.CurrentDesign, + val rules: StyleRules = StyleRules.NONE, + /** + * Draws the style for a backend that cannot read one. + * + * `com.mapconductor:vectortile` supplies one. Left out, a map without + * vector style support is told so in the diagnostics rather than left + * blank — there is nothing sensible this can do on its own. + * + * **Hold it, do not rebuild it.** Two styles count as the same one only + * if they name the same rasteriser *instance*, so constructing it inline + * makes every recomposition a different style — the map tears the old + * one down and installs a new one each time, and the result is tiles + * fetched forever with nothing drawn. `remember { VectorTileRasteriser() }`. + */ + val rasteriser: VectorStyleRasteriser? = null, + val onUnsupported: UnsupportedPolicy = UnsupportedPolicy.REPORT, + val onDiagnostics: ((List) -> Unit)? = null, +) : MapViewStyle { + override val key: String = "${document.key}|${rules.json.hashCode().toUInt()}" + + /** Whether [next] differs from this only in its adjustments. */ + internal fun sameStyleAs(next: VectorStyle): Boolean = + next.document == document && + next.rasteriser === rasteriser && + next.onUnsupported == onUnsupported + + override fun install(host: MapStyleHost): MapStyleInstallation = Installation(this, host).also { it.start() } + + /** + * One style's life on one map. + * + * Resolving the document can mean a network round trip, so the work + * starts on a worker and this is handed back at once; everything after + * that checks [disposed] before touching the map, because a view can be + * gone before its style arrives. + */ + private class Installation( + private var style: VectorStyle, + private val host: MapStyleHost, + ) : MapStyleInstallation { + private val disposed = AtomicBoolean(false) + + /** + * The id the document is served under, named after its content, or + * null while nothing is served. + * + * **Not a fresh id per installation**, which is the shape this used + * to have and which deadlocks a provider that rebuilds its view on a + * design change. MapTiler on Android keys its whole view on the + * design id: serving a document sets the design, that rebuilds the + * view, the rebuild reinstalls the style, a new id gives a new URL, + * which is a new design -- and the map never finishes coming up. + * + * Content-derived, the second install serves the same URL and + * `showStyle` sees the design it already set and does nothing. It + * also makes the other half right: when the adjusted document *is* + * what the map gets (a vector renderer that cannot be patched), a + * rules change produces different content, so the URL changes and the + * map reloads -- which under one fixed id it would not have done. + */ + private var servedId: String? = null + + /** The style as its author wrote it, kept so later rules compile against it. */ + private var base: String? = null + private var rasterisation: VectorStyleRasterisation? = null + private var styleLoaded: MapStyleInstallation? = null + + fun start() { + workers.execute { + val base = + runCatching { resolve(style.document) } + .getOrElse { error -> + report(listOf("the style could not be read: ${error.message}")) + return@execute + } + if (disposed.get()) return@execute + this.base = base + apply(style, firstTime = true) + } + } + + override fun update(next: com.mapconductor.core.map.MapViewStyle): Boolean { + val next = next as? VectorStyle ?: return false + // A different document is a different style, whatever else + // matches: it has to be fetched and the map has to be told. + if (!style.sameStyleAs(next)) return false + val base = base ?: return false + style = next + workers.execute { if (!disposed.get()) apply(next, firstTime = false) } + return true + } + + override fun dispose() { + if (!disposed.compareAndSet(false, true)) return + styleLoaded?.dispose() + styleLoaded = null + // Order matters: the mutations have to come off while the + // document they were applied to is still the one loaded. + host.serviceRegistry.get(VectorStyleMutationSupportKey)?.clear() + servedId?.let { id -> + host.serviceRegistry.get(VectorStyleSupportKey)?.clearStyle() + host.tileServer.unregisterDocument(id) + servedId = null + } + rasterisation?.dispose() + rasterisation = null + } + + /** Compiles on a worker, then routes on the main thread. */ + private fun apply( + style: VectorStyle, + firstTime: Boolean, + ) { + val base = base ?: return + val compiled = + runCatching { VectorStyleRules.compile(base, style.rules.json) } + .getOrElse { error -> + report(listOf("the rules could not be applied: ${error.message}")) + return + } + if (disposed.get()) return + report(compiled.diagnostics) + onMain { route(style, compiled, firstTime, base) } + } + + /** + * Hands the compiled result to the map. **Main thread only.** + * + * Every branch below touches the renderer, and a renderer is a UI + * object on all three platforms. MapLibre Android says so out loud -- + * `CalledFromWorkerThreadException: Method invoked from wrong thread + * is getLayer` -- and because `applyStyleMutations` catches what a + * mutation throws, all 506 of them came back as adjustments this map + * "cannot" make. The map still looked right, because the provider + * puts the whole set on again from the style-loaded callback, which + * does run here. So the symptom was a diagnostic that contradicted + * the picture, which is the hardest kind to believe. + */ + private fun route( + style: VectorStyle, + compiled: CompiledStyle, + firstTime: Boolean, + base: String, + ) { + if (disposed.get()) return + val registry = host.serviceRegistry + val vector = registry.get(VectorStyleSupportKey) + val mutation = registry.get(VectorStyleMutationSupportKey) + + when { + // The map draws styles itself and can be told differences: + // give it the author's document and the deltas on top. The + // compiled document is deliberately *not* what it is given -- + // the next rule change produces deltas against the original, + // and a map holding an already-adjusted document would take + // them to mean something else. + vector != null && mutation != null -> { + if (firstTime) serveDocument(vector, base) + val unapplied = mutation.apply(compiled.mutations) + if (unapplied.isNotEmpty()) handleUnapplied(unapplied, vector, compiled) + } + // It draws styles but cannot be patched: the adjusted + // document is the only way, and every rule change reloads. + vector != null -> serveDocument(vector, compiled.styleJson) + // It cannot read a style at all. + style.rasteriser != null -> { + val current = rasterisation + if (current == null) { + rasterisation = style.rasteriser.install(host, compiled.styleJson, compiled.affects) + } else { + current.restyle(compiled.styleJson, compiled.affects) + } + } + else -> + report( + listOf( + "this map cannot draw a vector style, and no rasteriser was given; " + + "pass `rasteriser = VectorTileRasteriser()` from com.mapconductor:vectortile", + ), + ) + } + + // Whatever was just applied is lost the moment the map loads a + // style again -- an app switching basemap, a provider rebuilding. + // The mutation store puts its own set back; the document has to + // be re-served here. + if (firstTime && styleLoaded == null) { + styleLoaded = host.onStyleLoaded { if (!disposed.get()) onStyleReloaded() } + } + } + + private fun onStyleReloaded() { + // The store re-applies the mutations by itself. Nothing else to + // do unless this was the side that served the document, in which + // case the map has just loaded something else and the style is + // no longer installed -- the app chose that, so it stands. + if (servedId != null) { + Log.d(TAG, "the map loaded another style; the adjustments went with it") + } + } + + private fun serveDocument( + vector: com.mapconductor.core.map.VectorStyleSupport, + json: String, + ) { + val id = "vectorstyle-${contentId(json)}" + val previous = servedId + host.tileServer.registerDocument(id, "application/json", json.toByteArray()) + servedId = id + vector.showStyle( + styleUrl = host.tileServer.documentUrl(id), + attributionRules = attributionsOf(json).map { AttributionRule(attribution = it) }, + ) + // The one it replaces, dropped only after the new one is up so + // the map is never pointed at an id that is no longer registered. + if (previous != null && previous != id) host.tileServer.unregisterDocument(previous) + } + + private fun handleUnapplied( + unapplied: List, + vector: com.mapconductor.core.map.VectorStyleSupport, + compiled: CompiledStyle, + ) { + // Named by property, not by layer. A backend with no property + // for a spec key fails that key on every layer that uses it, so + // a list of layers was hundreds of names for one cause -- and + // never said which property, which is the only part an app can + // act on. + val properties = unapplied.map { it.propertyName }.distinct().sorted() + val shown = properties.take(5) + val more = if (properties.size > shown.size) ", ..." else "" + val layers = unapplied.mapNotNull { it.layerId }.distinct().size + val message = + "${unapplied.size} adjustments were not applied: this map cannot set these " + + "properties by name (${shown.joinToString(", ")}$more) across $layers layers" + when (style.onUnsupported) { + UnsupportedPolicy.REPORT -> report(listOf(message)) + UnsupportedPolicy.RELOAD -> { + report(listOf("$message; handing the map the adjusted document instead")) + host.serviceRegistry.get(VectorStyleMutationSupportKey)?.clear() + serveDocument(vector, compiled.styleJson) + } + } + } + + private fun resolve(source: VectorStyleSource): String = + when (source) { + is VectorStyleSource.Text -> source.json + is VectorStyleSource.Url -> fetch(source.url, source.headers) + VectorStyleSource.CurrentDesign -> { + val url = + host.vectorStyleUrl + ?: throw IllegalStateException( + "this map is not drawing a vector style, so there is nothing to adjust; " + + "give `document` a style of your own", + ) + fetch(url, emptyMap()) + } + } + + private fun report(diagnostics: List) { + if (diagnostics.isEmpty()) return + host.report(diagnostics) + style.onDiagnostics?.invoke(diagnostics) + } + + private companion object { + const val TAG = "VectorStyle" + + /** + * A short, stable name for a document's content. + * + * FNV-1a rather than the platform's digest API: this only has to + * name content inside one process, and the three platforms carry + * the same ten lines instead of three different hashing APIs. + */ + fun contentId(text: String): String { + var hash = -0x340d631b7bdddcdbL // FNV-1a 64-bit offset basis + for (byte in text.toByteArray()) { + hash = hash xor (byte.toLong() and 0xff) + hash *= 0x100000001b3L // FNV prime + } + return hash.toULong().toString(16) + } + + /** + * Where a style is fetched and compiled. + * + * Daemon threads, and few: a map has one style, and the work is + * a round trip plus a parse. Shared across installations so a + * view churning through styles does not churn through threads. + */ + val workers = + Executors.newFixedThreadPool(2) { runnable -> + Thread(runnable, "mc-vectorstyle").apply { isDaemon = true } + } + + private val main = Handler(Looper.getMainLooper()) + + /** Runs now when already on the main thread, and posts otherwise. */ + private fun onMain(block: () -> Unit) { + if (Looper.myLooper() == Looper.getMainLooper()) block() else main.post(block) + } + + fun fetch( + url: String, + headers: Map, + ): String { + val connection = URL(url).openConnection() as HttpURLConnection + return try { + connection.connectTimeout = 15_000 + connection.readTimeout = 15_000 + headers.forEach(connection::setRequestProperty) + if (connection.responseCode !in 200..299) { + throw IllegalStateException("HTTP ${connection.responseCode} for $url") + } + connection.inputStream.use { it.readBytes().decodeToString() } + } finally { + connection.disconnect() + } + } + + /** + * The credits the style's sources ask for. + * + * Carried onto the design so the map's attribution overlay shows + * them for as long as the style is up. Nothing else about this + * can be wrong while still looking right: the map draws + * perfectly whether or not anyone is credited for the data. + */ + fun attributionsOf(json: String): List = + runCatching { + val sources = org.json.JSONObject(json).optJSONObject("sources") ?: return emptyList() + sources + .keys() + .asSequence() + .mapNotNull { sources.optJSONObject(it)?.optString("attribution") } + .filter { it.isNotEmpty() } + .distinct() + .toList() + }.getOrDefault(emptyList()) + } + } +} diff --git a/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/VectorStyleRules.kt b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/VectorStyleRules.kt new file mode 100644 index 000000000..ccd208e3c --- /dev/null +++ b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/VectorStyleRules.kt @@ -0,0 +1,172 @@ +package com.mapconductor.vectorstyle + +import com.mapconductor.core.map.StyleMutation +import org.json.JSONArray +import org.json.JSONObject + +/** + * Declarative adjustments to a MapLibre style. + * + * A map in this SDK is drawn one of two ways: by a renderer that takes a + * vector style directly (MapLibre, Mapbox, MapTiler), or by rasterising the + * style to PNG tiles on the device and handing those to a backend that + * cannot read a style at all (Google Maps, HERE, ArcGIS...). Both start from + * the same `style.json`, so adjusting the style belongs *before* that fork + * rather than on either side of it. + * + * [compile] is that step. From one pass over one style it produces both the + * adjusted document — for a renderer to read, or for the rasteriser to draw + * — and the per-layer deltas a live renderer can be told about without + * reloading anything. The two cannot disagree, because they come from the + * same evaluation. + * + * ```kotlin + * val compiled = VectorStyleRules.compile(styleJson, rules) + * compiled.diagnostics.forEach(::println) // what matched, and what did not + * ``` + * + * The rules themselves are JSON. That is the definition rather than a + * serialisation of something else: a rule set can be written by hand, stored, + * shipped from a server or diffed, and it is exactly what the compiler reads + * on all three platforms. + */ +object VectorStyleRules { + /** + * The rules document version this build understands. + * + * A document claiming another version is refused rather than partly + * applied — a rule that silently does nothing is the failure this whole + * design exists to avoid. + */ + @JvmStatic + val schemaVersion: Int by lazy { NativeStyleCompiler.nativeSchemaVersion() } + + /** + * Applies [rulesJson] to [styleJson]. + * + * @throws VectorStyleException when either document cannot be read: a + * style that is not JSON, a rules document from a newer build, a + * selector this version does not know. + */ + @JvmStatic + fun compile( + styleJson: String, + rulesJson: String, + ): CompiledStyle { + val answer = JSONObject(NativeStyleCompiler.nativeCompile(styleJson, rulesJson)) + answer.optString("error").takeIf { it.isNotEmpty() }?.let { throw VectorStyleException(it) } + return CompiledStyle( + styleJson = answer.getJSONObject("style").toString(), + mutations = StyleMutation.parseList(answer.optJSONArray("mutations")?.toString() ?: "[]"), + affects = StyleAffects.of(answer.optString("affects")), + patchable = answer.optBoolean("patchable", true), + diagnostics = answer.optJSONArray("diagnostics").toStringList(), + ) + } + + /** + * Every layer in the style, with the role this would give it. + * + * Rules are written against someone else's style, so being able to ask + * what is in it — and on what evidence a layer counts as a road — is not + * a debugging aid, it is how the rules get written in the first place. + * + * @throws VectorStyleException when the style cannot be read. + */ + @JvmStatic + fun describe(styleJson: String): List { + val text = NativeStyleCompiler.nativeDescribe(styleJson) + if (text.trimStart().startsWith("{")) { + throw VectorStyleException(JSONObject(text).optString("error", "the style could not be read")) + } + val array = JSONArray(text) + return (0 until array.length()).map { index -> + val entry = array.getJSONObject(index) + StyleLayerInfo( + id = entry.optString("id"), + kind = entry.optString("kind"), + sourceLayer = entry.optString("sourceLayer").takeIf { it.isNotEmpty() }, + roles = entry.optJSONArray("roles").toStringList(), + evidence = entry.optJSONArray("evidence").toStringList(), + ) + } + } + + private fun JSONArray?.toStringList(): List = + if (this == null) emptyList() else (0 until length()).map { optString(it) } +} + +/** What came out of [VectorStyleRules.compile]. */ +data class CompiledStyle( + /** The adjusted document, to hand to a renderer or to rasterise. */ + val styleJson: String, + /** + * The per-layer deltas, for a map that can change a loaded style in + * place rather than reading the document again. + */ + val mutations: List, + /** + * Which half of a split raster layer has to be redrawn. A rule that only + * recolours text need not invalidate every tile on screen. + */ + val affects: StyleAffects, + /** + * False when the mutations alone cannot reproduce the document — a rule + * added a layer — so a live map has to be given the document instead of + * being patched. + */ + val patchable: Boolean, + /** + * What the app should know: how many layers each rule matched, a rule + * that matched none, a change the rasteriser will not draw, an + * expression it cannot evaluate. + * + * Worth surfacing rather than keeping internal. A rule written against + * the wrong tile schema produces a perfectly good map with nothing + * changed on it, and nothing else says so. + */ + val diagnostics: List, +) + +/** Which half of a split raster layer a change reaches. */ +enum class StyleAffects { + NONE, + GROUND, + LABELS, + BOTH, + ; + + internal companion object { + fun of(name: String): StyleAffects = + when (name) { + "ground" -> GROUND + "labels" -> LABELS + "both" -> BOTH + else -> NONE + } + } +} + +/** One layer of a style, and the role the compiler would give it. */ +data class StyleLayerInfo( + val id: String, + /** The layer's `type`: `background`, `fill`, `line`, `circle`, `symbol`, or another. */ + val kind: String, + val sourceLayer: String?, + /** Most specific last: a road casing is both `road` and `road-casing`. */ + val roles: List, + /** + * How each role was decided, in the same order as [roles]: + * `shortbread:streets` from the schema's table, `id~*-casing` from the + * layer's name, `kind:symbol` from its type. + * + * The id heuristics are the part most likely to be wrong on a style + * nobody has tried yet, so what they decided is said out loud. + */ + val evidence: List, +) + +/** A style or a rules document that could not be read. */ +class VectorStyleException( + message: String, +) : IllegalArgumentException(message) diff --git a/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/VectorStyleSource.kt b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/VectorStyleSource.kt new file mode 100644 index 000000000..1ebe28118 --- /dev/null +++ b/android-vectorstyle/src/main/java/com/mapconductor/vectorstyle/VectorStyleSource.kt @@ -0,0 +1,112 @@ +package com.mapconductor.vectorstyle + +import com.mapconductor.core.map.MapStyleHost + +/** + * Which style the rules are applied to. + * + * A rule cannot be matched against anything until the style document is in + * hand: "roads" means whichever layers *this* style draws roads with, and + * only the document says. So every path here ends in text, and the one that + * has to go and get it says so. + */ +sealed interface VectorStyleSource { + /** What identifies this source, for deciding whether a style changed. */ + val key: String + + /** The document itself. The app already has it. */ + data class Text( + val json: String, + ) : VectorStyleSource { + override val key: String get() = "text:${json.hashCode().toUInt()}" + } + + /** + * A `style.json` to fetch. + * + * Fetched by this module rather than by the map, because the rules have + * to be compiled against it before the map is given anything. + */ + data class Url( + val url: String, + /** Sent with the request — an API key, usually. */ + val headers: Map = emptyMap(), + ) : VectorStyleSource { + override val key: String get() = "url:$url" + } + + /** + * Whatever the map is already drawing. + * + * For adjusting a basemap the app did not supply: a MapLibre, Mapbox or + * MapTiler design. The module reads the design's style URL from + * [MapStyleHost.vectorStyleUrl] and fetches it; a backend that has no + * such thing cannot be adjusted this way and says so. + */ + data object CurrentDesign : VectorStyleSource { + override val key: String get() = "current" + } +} + +/** + * What to do about an adjustment the map would not take. + * + * Only MapLibre on iOS reaches this today: it exposes paint properties as + * typed expressions rather than by name, so a raw style-spec key it has no + * mapping for cannot be set. + */ +enum class UnsupportedPolicy { + /** + * Say so and leave the rest applied. The default, because the + * alternative makes the map reload — and not reloading is the point. + */ + REPORT, + + /** + * Hand the map the adjusted document instead, so everything applies. + * + * Correct, and expensive: the renderer drops its tiles, re-reads the + * document and the app's overlays are rebuilt. + */ + RELOAD, +} + +/** + * Draws a style the map cannot read itself. + * + * The seam between this module and the rasteriser. Declared here and + * implemented in `com.mapconductor:vectortile`, which is what keeps an app + * using only MapLibre from linking a megabyte of renderer it will never + * call. An app that also targets Google Maps, MapKit, HERE or ArcGIS passes + * one in; one that does not, does not, and is told so rather than shown a + * blank map. + */ +interface VectorStyleRasteriser { + /** + * Starts drawing [styleJson] as raster tiles on [host]. + * + * @param affects which half of the split tile layers the adjustments + * reached, so a change to labels alone need not redraw the ground. + */ + fun install( + host: MapStyleHost, + styleJson: String, + affects: StyleAffects, + ): VectorStyleRasterisation +} + +/** A rasteriser's work in progress. */ +interface VectorStyleRasterisation { + /** + * Draws a different style with the same tiles. + * + * The geometry has not changed, only the paint over it, so this costs a + * re-rasterise and no network. + */ + fun restyle( + styleJson: String, + affects: StyleAffects, + ) + + fun dispose() +} diff --git a/android-vectorstyle/src/main/jniLibs/arm64-v8a/libmvt_style_jni.so b/android-vectorstyle/src/main/jniLibs/arm64-v8a/libmvt_style_jni.so new file mode 100755 index 000000000..9517c7be6 Binary files /dev/null and b/android-vectorstyle/src/main/jniLibs/arm64-v8a/libmvt_style_jni.so differ diff --git a/android-vectorstyle/src/main/jniLibs/armeabi-v7a/libmvt_style_jni.so b/android-vectorstyle/src/main/jniLibs/armeabi-v7a/libmvt_style_jni.so new file mode 100755 index 000000000..33082c8b2 Binary files /dev/null and b/android-vectorstyle/src/main/jniLibs/armeabi-v7a/libmvt_style_jni.so differ diff --git a/android-vectorstyle/src/main/jniLibs/x86_64/libmvt_style_jni.so b/android-vectorstyle/src/main/jniLibs/x86_64/libmvt_style_jni.so new file mode 100755 index 000000000..b6597e222 Binary files /dev/null and b/android-vectorstyle/src/main/jniLibs/x86_64/libmvt_style_jni.so differ diff --git a/android-vectorstyle/src/test/java/com/mapconductor/vectorstyle/StyleRulesBuilderTest.kt b/android-vectorstyle/src/test/java/com/mapconductor/vectorstyle/StyleRulesBuilderTest.kt new file mode 100644 index 000000000..a295e9acc --- /dev/null +++ b/android-vectorstyle/src/test/java/com/mapconductor/vectorstyle/StyleRulesBuilderTest.kt @@ -0,0 +1,154 @@ +package com.mapconductor.vectorstyle + +import androidx.compose.ui.graphics.Color +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * The builder writes the canonical JSON, exactly. + * + * Asserted as text rather than through a parser on purpose: the text *is* + * the contract, the compiler on three platforms reads it, and a stray comma + * or an unquoted colour is the kind of thing a round-trip through a lenient + * parser would hide. + */ +class StyleRulesBuilderTest { + @Test + fun writesTheExampleTheDesignWasArguedFrom() { + val rules = + StyleRules.build { + all { color = Color.Black } + role(LayerRole.LABEL) { visible = false } + role(LayerRole.ROAD_CASING) { color = Color(0xFF303030) } + role(LayerRole.ROAD) { + color = Color.White + widthScale = 1.3f + } + } + + assertEquals( + """{"schemaVersion":1,"rules":[""" + + """{"selector":"all","patch":{"color":"#000000"}},""" + + """{"selector":{"role":"label"},"patch":{"visible":false}},""" + + """{"selector":{"role":"road-casing"},"patch":{"color":"#303030"}},""" + + """{"selector":{"role":"road"},"patch":{"color":"#ffffff","widthScale":1.3}}""" + + """]}""", + rules.json, + ) + } + + @Test + fun writesNoRulesAtAll() { + assertEquals("""{"schemaVersion":1,"rules":[]}""", StyleRules.build { }.json) + assertEquals(StyleRules.NONE.json, StyleRules.build { }.json) + } + + @Test + fun carriesAlphaThroughAsRgba() { + val rules = StyleRules.build { all { color = Color(0x80112233) } } + assertEquals( + """{"schemaVersion":1,"rules":[{"selector":"all","patch":{"color":"rgba(17,34,51,0.502)"}}]}""", + rules.json, + ) + } + + @Test + fun composesSelectors() { + val rules = + StyleRules.build { + where( + StyleSelector.AllOf( + listOf( + StyleSelector.Role(LayerRole.ROAD), + StyleSelector.Not(StyleSelector.Role(LayerRole.ROAD_CASING)), + ), + ), + ) { color = Color.White } + where( + StyleSelector.AnyOf( + listOf(StyleSelector.Kind(StyleLayerKind.SYMBOL), StyleSelector.LayerId("poi-*")), + ), + ) { visible = false } + } + + assertEquals( + """{"schemaVersion":1,"rules":[""" + + """{"selector":{"allOf":[{"role":"road"},{"not":{"role":"road-casing"}}]},""" + + """"patch":{"color":"#ffffff"}},""" + + """{"selector":{"anyOf":[{"kind":"symbol"},{"layerId":"poi-*"}]},""" + + """"patch":{"visible":false}}""" + + """]}""", + rules.json, + ) + } + + @Test + fun writesTheColourFilters() { + val rules = + StyleRules.build { + all { invertLightness() } + role(LayerRole.LABEL) { desaturate(0.5f) } + role(LayerRole.WATER) { mix(Color.Black, amount = 0.25f) } + } + assertEquals( + """{"schemaVersion":1,"rules":[""" + + """{"selector":"all","patch":{"colorFilter":{"invertLightness":true}}},""" + + """{"selector":{"role":"label"},"patch":{"colorFilter":{"desaturate":0.5}}},""" + + """{"selector":{"role":"water"},""" + + """"patch":{"colorFilter":{"mix":{"color":"#000000","amount":0.25}}}}""" + + """]}""", + rules.json, + ) + } + + /** + * The escape hatch has to produce usable JSON for both an expression and + * a plain string — a `text-field` that lost its quotes is a style no + * renderer can read. + */ + @Test + fun writesRawPropertiesEitherWay() { + val rules = + StyleRules.build { + kind(StyleLayerKind.SYMBOL) { + property("text-field", """["get","name:ja"]""") + propertyText("text-transform", "uppercase") + } + } + assertEquals( + """{"schemaVersion":1,"rules":[{"selector":{"kind":"symbol"},"patch":{"properties":{""" + + """"text-field":["get","name:ja"],"text-transform":"uppercase"}}}]}""", + rules.json, + ) + } + + @Test + fun namesASchemaWhenToldTo() { + val named = StyleRules.build { schema = "openmaptiles" } + assertEquals("""{"schemaVersion":1,"schema":"openmaptiles","rules":[]}""", named.json) + + val own = StyleRules.build { customSchema(mapOf("parcel" to listOf("zoning", "lots"))) } + assertEquals( + """{"schemaVersion":1,"schema":{"roles":{"parcel":["zoning","lots"]}},"rules":[]}""", + own.json, + ) + } + + /** A layer id with a quote in it must not end the JSON string. */ + @Test + fun escapesWhatItIsGiven() { + val rules = StyleRules.build { layerId("""say "hi"\n""") { visible = true } } + assertEquals( + """{"schemaVersion":1,"rules":[{"selector":{"layerId":"say \"hi\"\\n"},""" + + """"patch":{"visible":true}}]}""", + rules.json, + ) + } + + @Test + fun parseKeepsWhatItWasGiven() { + val text = """{"schemaVersion":1,"rules":[{"selector":"all","patch":{}}]}""" + assertEquals(text, StyleRules.parse(text).json) + assertEquals(StyleRules.parse(text), StyleRules.parse(text)) + } +} diff --git a/android-vectortile/.gitignore b/android-vectortile/.gitignore new file mode 100644 index 000000000..567609b12 --- /dev/null +++ b/android-vectortile/.gitignore @@ -0,0 +1 @@ +build/ diff --git a/android-vectortile/LICENSE b/android-vectortile/LICENSE new file mode 100644 index 000000000..443828753 --- /dev/null +++ b/android-vectortile/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Masashi Katsumata + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/android-vectortile/README.md b/android-vectortile/README.md new file mode 100644 index 000000000..538caad34 --- /dev/null +++ b/android-vectortile/README.md @@ -0,0 +1,150 @@ +# MapConductor Vector Tile + +## Description + +MapConductor Vector Tile draws a MapLibre vector style on **any** map implementation, by rasterising the style to tiles on the device and serving them through the SDK's local tile server. + +The backend only ever sees an ordinary raster layer. That is what makes it work on Google Maps, MapKit, HERE, ArcGIS, TomTom and the rest — none of which can render a vector style themselves. + +The renderer is a Rust core shared with the iOS and web modules, so the same style and the same source tile produce a byte-identical PNG on all three platforms. + +## Setup + +https://mapconductor.com/setup/ + +------------------------------------------------------------------------ + +## Requirement: cleartext traffic to loopback + +Tiles are served over plain HTTP on `127.0.0.1`. Without a network security config permitting it, **the layer simply stays blank** — no error, no crash. + +```xml + + + + 127.0.0.1 + localhost + + +``` + +This is not specific to this module — every tile-server-backed layer in the SDK needs it, which is why `example-app` already carries one. + +------------------------------------------------------------------------ + +## Usage + +### Basic VectorTileLayer + +Place `VectorTileLayer` inside any `XxxMapView` content block: + +```kotlin +XxxMapView(...) { + VectorTileLayer( + styleJson = styleJson, + opacity = 0.9f, + ) +} +``` + +`styleJson` is the text of a `style.json`. Fetching it is the caller's job — the layer does not decide how your app does network I/O. + +### Keeping tiles across launches + +```kotlin +val cacheDir = remember { context.cacheDir.resolve("vectortile") } + +XxxMapView(...) { + VectorTileLayer( + styleJson = styleJson, + diskCacheDir = cacheDir, + ) +} +``` + +Deliberately the caller's choice rather than something the module digs out of a `Context`: apps have their own opinions about cache location and lifetime. + +It does not make the first view faster — the tiles still have to be fetched and rasterised once. On a Pixel 5a a second launch served all seven visible tiles from disk with zero renders, against roughly 1 s of fetch plus 1 s of rasterising each on the first. + +### Choosing a rasteriser + +```kotlin +VectorTileLayer( + styleJson = styleJson, + renderMode = VectorTileProvider.RenderMode.GPU, +) +``` + +The default probes for an OpenGL ES context and falls back to the CPU when there is none. + +### Reporting what a style will not draw + +```kotlin +var diagnostics by remember { mutableStateOf>(emptyList()) } + +VectorTileLayer( + styleJson = styleJson, + onDiagnostics = { diagnostics = it }, +) +``` + +### Without Compose + +`VectorTileProvider` is the layer's engine and can be used on its own — register it with `TileServerRegistry` and point a `RasterLayerState` at the resulting URL template. `VectorTileLayer` is that wiring plus the lifecycle. + +------------------------------------------------------------------------ + +## How it draws + +The layer mounts **two** raster layers, not one: + +- the **ground** — fills, lines and circles, the half no font arriving can change +- a transparent **label overlay** above it, replaced on its own when glyph ranges land + +To the map and the user they read as one layer. The split is what stops a late glyph range forcing a redraw of the whole style, and it lets the two halves render in parallel. + +Attribution is handled for you: the credits the style's sources ask for are fed to the map's attribution overlay through `AttributionRule`, on both halves. + +------------------------------------------------------------------------ + +## API Reference + +### VectorTileLayer + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `styleJson` | `String` | — | The text of a `style.json` | +| `tileSize` | `Int` | `512` | Output tile size in pixels | +| `opacity` | `Float` | `1.0f` | Layer opacity (0.0–1.0) | +| `visible` | `Boolean` | `true` | | +| `maxZoom` | `Int` | `22` | | +| `headers` | `Map` | empty | Sent with every source tile request — auth tokens, API keys | +| `renderMode` | `VectorTileProvider.RenderMode` | `AUTO` | Which rasteriser to use | +| `diskCacheDir` | `File?` | `null` | Where to keep rendered tiles between launches; null disables it | +| `onDiagnostics` | `((List) -> Unit)?` | `null` | Reasons the style may not render as intended | + +### VectorTileProvider.RenderMode + +| Value | Description | +|---|---| +| `CPU` | `tiny-skia`, on the calling thread. Always available. | +| `GPU` | OpenGL ES. Roughly 3x faster on a mid-range device and, more to the point, moves the drawing off the CPU that the map SDK and the app are already competing for. | +| `AUTO` | `GPU` where a context can be created, otherwise `CPU`. | + +`GPU` output is not bit-identical to `CPU`: anti-aliasing comes from MSAA rather than analytic coverage, which measured at 0.39% of pixels differing on a dense street tile, all of it on thin-line edges. + +### VectorTileProvider constants + +| Constant | Value | +|---|---| +| `DEFAULT_TILE_SIZE` | `512` | +| `DEFAULT_CACHE_BYTES` | 48 MiB | +| `DEFAULT_DISK_CACHE_BYTES` | 64 MiB | +| `DEFAULT_GLYPH_CACHE_BYTES` | 32 MiB | +| `DEFAULT_SPRITE_CACHE_BYTES` | 4 MiB | + +------------------------------------------------------------------------ + +## License + +Apache License 2.0. See [LICENSE](./LICENSE). diff --git a/android-vectortile/api/android-vectortile.api b/android-vectortile/api/android-vectortile.api new file mode 100644 index 000000000..a8cb70e6a --- /dev/null +++ b/android-vectortile/api/android-vectortile.api @@ -0,0 +1,345 @@ +public final class com.mapconductor.vectortile.EglOffscreen implements java.io.Closeable { + public static final com.mapconductor.vectortile.EglOffscreen$Companion Companion; + public final int getEsVersion(); + public final int getActiveSamples(); + public final void prepare(int, int); + public final void bindDrawTarget(); + public final void resolve(); + public final java.nio.ByteBuffer readPixels(java.nio.ByteBuffer); + public final void finish(); + public void close(); + public com.mapconductor.vectortile.EglOffscreen(android.opengl.EGLDisplay, android.opengl.EGLContext, android.opengl.EGLSurface, int, kotlin.jvm.internal.DefaultConstructorMarker); +} +public final class com.mapconductor.vectortile.EglOffscreen$Companion { + public final com.mapconductor.vectortile.EglOffscreen create(boolean); +} +final class com.mapconductor.vectortile.EglOffscreen$EGLExt { + public static final com.mapconductor.vectortile.EglOffscreen$EGLExt INSTANCE; + public static final int EGL_OPENGL_ES3_BIT; +} +public final class com.mapconductor.vectortile.GpuTileRasterizer implements java.io.Closeable { + public static final com.mapconductor.vectortile.GpuTileRasterizer$Companion Companion; + public com.mapconductor.vectortile.GpuTileRasterizer(int); + public final java.lang.String describe(); + public final byte[] renderPng(com.mapconductor.vectortile.TessellatedTile, kotlin.jvm.functions.Function1); + public void close(); +} +public final class com.mapconductor.vectortile.GpuTileRasterizer$Companion { + public final com.mapconductor.vectortile.GpuTileRasterizer createOrNull(int); +} +public final class com.mapconductor.vectortile.NativeLabelPixels implements java.io.Closeable { + public com.mapconductor.vectortile.NativeLabelPixels(java.nio.ByteBuffer, int); + public final java.nio.ByteBuffer getBuffer(); + public final int getPlaced(); + public void close(); +} +public final class com.mapconductor.vectortile.NativeRenderer { + public static final com.mapconductor.vectortile.NativeRenderer INSTANCE; + public final native long nativeNew(java.lang.String, int); + public final native void nativeFree(long); + public final native void nativeSetStyle(long, java.lang.String); + public final native java.lang.String nativePlan(long, int, int, int); + public final native byte[] nativeRender(long, int, int, int, int, byte[], int[], int); + public final native java.lang.String nativeGlyphsUrlTemplate(long); + public final native java.lang.String nativeNeededGlyphs(long, int, int, int, byte[], int[]); + public final native java.lang.String nativeSpriteUrls(long, int); + public final native int nativeNeedsSprite(long); + public final native int nativeNeedsCpu(long, int, byte[], int[]); + public final native int nativeAddSprite(long, java.lang.String, byte[]); + public final native int nativeAddGlyphs(long, byte[]); + public final native int nativeDrawLabels(long, int, int, int, int, byte[], byte[], int[]); + public final native java.nio.ByteBuffer nativeRenderLabels(long, int, int, int, int, byte[], int[], int[]); + public final native void nativeFreeLabelPixels(java.nio.ByteBuffer); + public final native java.lang.String nativeUnsupportedLayerTypes(long); + public final native java.lang.String nativeAttributions(long); + public final native java.lang.String nativeDiagnostics(long); + public final native java.nio.ByteBuffer nativeTessellate(long, int, int, int, int, byte[], int[]); + public final native void nativeFreeTessellation(java.nio.ByteBuffer); +} +public final class com.mapconductor.vectortile.OfflinePackage { + public static final com.mapconductor.vectortile.OfflinePackage$Companion Companion; + public static final int FORMAT_VERSION; + public static final java.lang.String MANIFEST_FILE; + public static final java.lang.String STYLE_FILE; + public static final java.lang.String INDEX_FILE; + public static final java.lang.String TILES_DIR; + public static final java.lang.String GLYPHS_DIR; + public static final java.lang.String SPRITE_FILE; + public final java.io.File getDirectory(); + public final com.mapconductor.vectortile.OfflinePackage$Manifest getManifest(); + public final java.lang.String getStyleJson(); + public final byte[] bytes(java.lang.String); + public final boolean contains(java.lang.String); + public final java.lang.String upstreamUrl(java.lang.String); + public final java.lang.String styleServedBy(java.lang.String); + public static final com.mapconductor.vectortile.OfflinePackage open(java.io.File); + public static final boolean delete(java.io.File); + public com.mapconductor.vectortile.OfflinePackage(java.io.File, com.mapconductor.vectortile.OfflinePackage$Manifest, java.util.Map, kotlin.jvm.internal.DefaultConstructorMarker); +} +public final class com.mapconductor.vectortile.OfflinePackage$Bounds { + public static final com.mapconductor.vectortile.OfflinePackage$Bounds$Companion Companion; + public final double getSouth(); + public final double getWest(); + public final double getNorth(); + public final double getEast(); + public final org.json.JSONObject toJson(); +} +public final class com.mapconductor.vectortile.OfflinePackage$Bounds$Companion { + public final com.mapconductor.vectortile.OfflinePackage$Bounds fromJson(org.json.JSONObject); +} +public final class com.mapconductor.vectortile.OfflinePackage$Companion { + public final com.mapconductor.vectortile.OfflinePackage open(java.io.File); + public final boolean delete(java.io.File); +} +final class com.mapconductor.vectortile.OfflinePackage$Counters { + public final java.util.concurrent.atomic.AtomicLong getPackageHits(); + public final java.util.concurrent.atomic.AtomicLong getNetworkFetches(); + public final java.util.concurrent.atomic.AtomicLong getBlocked(); + public final com.mapconductor.vectortile.OfflinePackage$Stats snapshot(); +} +public final class com.mapconductor.vectortile.OfflinePackage$Fetcher implements kotlin.jvm.functions.Function1 { + public final boolean getOnline(); + public final void setOnline(boolean); + public final com.mapconductor.vectortile.OfflinePackage$Stats getStats(); + public byte[] invoke(java.lang.String); + public java.lang.Object invoke(java.lang.Object); +} +public final class com.mapconductor.vectortile.OfflinePackage$Manifest { + public static final com.mapconductor.vectortile.OfflinePackage$Manifest$Companion Companion; + public final com.mapconductor.vectortile.OfflinePackage$Bounds getBounds(); + public final int getMinZoom(); + public final int getMaxZoom(); + public final java.lang.String getStyleDigest(); + public final long getCreatedAt(); + public final int getTiles(); + public final int getGlyphs(); + public final int getSprites(); + public final long getBytes(); + public final java.util.Map getSources(); + public final java.lang.String getGlyphsTemplate(); + public final java.lang.String getSpriteBase(); + public final org.json.JSONObject toJson(); +} +public final class com.mapconductor.vectortile.OfflinePackage$Manifest$Companion { + public final com.mapconductor.vectortile.OfflinePackage$Manifest fromJson(org.json.JSONObject); +} +public final class com.mapconductor.vectortile.OfflinePackage$Stats { + public final long getPackageHits(); + public final long getNetworkFetches(); + public final long getBlocked(); + public java.lang.String toString(); + public final long component1(); + public final long component2(); + public final long component3(); + public final com.mapconductor.vectortile.OfflinePackage$Stats copy(long, long, long); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectortile.OfflinePackageDownloader { + public static final com.mapconductor.vectortile.OfflinePackageDownloader INSTANCE; + public static final int MAX_TILES; + public static final java.lang.Object download(java.lang.String, com.mapconductor.vectortile.OfflinePackage$Bounds, int, int, java.io.File, java.util.Map, int, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.coroutines.Continuation); +} +abstract class com.mapconductor.vectortile.OfflinePackageDownloader$FetchResult { +} +public final class com.mapconductor.vectortile.OfflinePackageDownloader$FetchResult$NotFound extends com.mapconductor.vectortile.OfflinePackageDownloader$FetchResult { + public static final com.mapconductor.vectortile.OfflinePackageDownloader$FetchResult$NotFound INSTANCE; +} +public final class com.mapconductor.vectortile.OfflinePackageDownloader$FetchResult$Success extends com.mapconductor.vectortile.OfflinePackageDownloader$FetchResult { + public final byte[] getData(); +} +public final class com.mapconductor.vectortile.OfflinePackageDownloader$FetchResult$TemporaryFailure extends com.mapconductor.vectortile.OfflinePackageDownloader$FetchResult { + public final java.lang.String getUrl(); + public final java.lang.Throwable getCause(); + public final java.lang.Integer getStatus(); + public final java.io.IOException toIOException(); +} +public final class com.mapconductor.vectortile.OfflinePackageDownloader$Phase extends java.lang.Enum { + public static final com.mapconductor.vectortile.OfflinePackageDownloader$Phase PLANNING; + public static final com.mapconductor.vectortile.OfflinePackageDownloader$Phase TILES; + public static final com.mapconductor.vectortile.OfflinePackageDownloader$Phase GLYPHS; + public static final com.mapconductor.vectortile.OfflinePackageDownloader$Phase SPRITE; + public static final com.mapconductor.vectortile.OfflinePackageDownloader$Phase DONE; + public static com.mapconductor.vectortile.OfflinePackageDownloader$Phase[] values(); + public static com.mapconductor.vectortile.OfflinePackageDownloader$Phase valueOf(java.lang.String); + public static kotlin.enums.EnumEntries getEntries(); +} +public final class com.mapconductor.vectortile.OfflinePackageDownloader$Progress { + public final com.mapconductor.vectortile.OfflinePackageDownloader$Phase getPhase(); + public final int getDone(); + public final int getTotal(); + public java.lang.String toString(); +} +public final class com.mapconductor.vectortile.OfflinePackageDownloader$download$3$DisplayTile { + public final int getZ(); + public final int getX(); + public final int getY(); + public final java.util.List getUrls(); +} +public final class com.mapconductor.vectortile.OfflineUnavailableException extends java.lang.RuntimeException { + public com.mapconductor.vectortile.OfflineUnavailableException(java.lang.String); +} +public final class com.mapconductor.vectortile.SolidBatchRenderer implements java.io.Closeable { + public static final com.mapconductor.vectortile.SolidBatchRenderer$Companion Companion; + public static final int VERTEX_STRIDE; + public static final java.lang.String VERTEX_SHADER; + public static final java.lang.String FRAGMENT_SHADER; + public com.mapconductor.vectortile.SolidBatchRenderer(); + public final void initialise(); + public final void upload(java.nio.FloatBuffer, int, int); + public final void clear(float, float, float, float); + public final void draw(java.util.List, float); + public void close(); +} +public final class com.mapconductor.vectortile.SolidBatchRenderer$Batch { + public final int getVertexOffset(); + public final int getVertexCount(); + public final int component1(); + public final int component2(); + public final com.mapconductor.vectortile.SolidBatchRenderer$Batch copy(int, int); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.vectortile.SolidBatchRenderer$Companion { +} +public final class com.mapconductor.vectortile.StyleAssetCache { + public static final com.mapconductor.vectortile.StyleAssetCache$Companion Companion; + public com.mapconductor.vectortile.StyleAssetCache(java.io.File, long); + public final byte[] get(java.lang.String); + public final void put(java.lang.String, byte[]); + public final int warm(kotlin.jvm.functions.Function1); + public final void clear(); +} +public final class com.mapconductor.vectortile.StyleAssetCache$Companion { +} +public final class com.mapconductor.vectortile.TessellatedTile implements java.io.Closeable { + public com.mapconductor.vectortile.TessellatedTile(java.nio.ByteBuffer); + public final java.nio.FloatBuffer getPacked(); + public final float getExtent(); + public final float[] getBackground(); + public final java.util.List getBatches(); + public final int getVertexOffset(); + public final int getVertexFloatCount(); + public final float getDecodeMs(); + public final float getTessellateMs(); + public final float getFilterMs(); + public final float getFillMs(); + public final float getLineMs(); + public final float getFeatureLoopMs(); + public final int getTriangleCount(); + public void close(); +} +public final class com.mapconductor.vectortile.TileDiskCache { + public static final com.mapconductor.vectortile.TileDiskCache$Companion Companion; + public com.mapconductor.vectortile.TileDiskCache(java.io.File, long); + public final byte[] get(java.lang.String); + public final void put(java.lang.String, byte[]); + public final void clear(); +} +public final class com.mapconductor.vectortile.TileDiskCache$Companion { + public final java.lang.String digest(java.lang.String...); +} +public final class com.mapconductor.vectortile.VectorTileLayerKt { + public static final void VectorTileLayer(com.mapconductor.compose.MapViewScope, java.lang.String, com.mapconductor.vectorstyle.StyleRules, java.lang.Integer, float, boolean, int, java.util.Map, com.mapconductor.vectortile.VectorTileProvider$RenderMode, java.lang.Integer, java.io.File, kotlin.jvm.functions.Function1, kotlin.Unit>, boolean, com.mapconductor.vectortile.OfflinePackage, boolean, kotlin.jvm.functions.Function1, androidx.compose.runtime.Composer, int, int, int); +} +public final class com.mapconductor.vectortile.VectorTileProvider implements com.mapconductor.core.tileserver.TileProviderInterface,java.io.Closeable { + public static final com.mapconductor.vectortile.VectorTileProvider$Companion Companion; + public static final int DEFAULT_TILE_SIZE; + public static final int DEFAULT_CACHE_BYTES; + public static final long DEFAULT_DISK_CACHE_BYTES; + public static final long DEFAULT_GLYPH_CACHE_BYTES; + public static final long DEFAULT_SPRITE_CACHE_BYTES; + public final com.mapconductor.vectortile.VectorTileProvider$RenderMode getRenderMode(); + public final kotlin.jvm.functions.Function0 getOnGlyphsLoaded(); + public final void setOnGlyphsLoaded(kotlin.jvm.functions.Function0); + public final long getGpuRenders(); + public final long getGpuFallbacks(); + public final java.util.List attributions(); + public final java.util.List diagnostics(); + public final java.lang.String rendererDescription(); + public final void setStyle(java.lang.String); + public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest); + public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest, kotlin.jvm.functions.Function0); + public final com.mapconductor.core.tileserver.TileProviderInterface getGeometryTiles(); + public final com.mapconductor.core.tileserver.TileProviderInterface getLabelTiles(); + public final void closeAsync(); + public void close(); + public static final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File, long, com.mapconductor.vectortile.VectorTileProvider$RenderMode, java.lang.Integer, kotlin.jvm.functions.Function1); + public static final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File, long, com.mapconductor.vectortile.VectorTileProvider$RenderMode, java.lang.Integer); + public static final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File, long, com.mapconductor.vectortile.VectorTileProvider$RenderMode); + public static final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File, long); + public static final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File); + public static final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int); + public static final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map); + public static final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int); + public static final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String); + public com.mapconductor.vectortile.VectorTileProvider(com.mapconductor.vectortile.VectorTileRenderer, int, int, java.util.Map, kotlin.jvm.functions.Function1, int, com.mapconductor.vectortile.TileDiskCache, com.mapconductor.vectortile.StyleAssetCache, com.mapconductor.vectortile.StyleAssetCache, java.lang.String, com.mapconductor.vectortile.GpuTileRasterizer, kotlin.jvm.internal.DefaultConstructorMarker); +} +public final class com.mapconductor.vectortile.VectorTileProvider$Companion { + public final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File, long, com.mapconductor.vectortile.VectorTileProvider$RenderMode, java.lang.Integer, kotlin.jvm.functions.Function1); + public final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File, long, com.mapconductor.vectortile.VectorTileProvider$RenderMode, java.lang.Integer); + public final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File, long, com.mapconductor.vectortile.VectorTileProvider$RenderMode); + public final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File, long); + public final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int, java.io.File); + public final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map, int); + public final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int, java.util.Map); + public final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String, int); + public final com.mapconductor.vectortile.VectorTileProvider create(java.lang.String); +} +final class com.mapconductor.vectortile.VectorTileProvider$Content extends java.lang.Enum { + public static final com.mapconductor.vectortile.VectorTileProvider$Content FULL; + public static final com.mapconductor.vectortile.VectorTileProvider$Content GEOMETRY; + public static final com.mapconductor.vectortile.VectorTileProvider$Content LABELS; + public static com.mapconductor.vectortile.VectorTileProvider$Content[] values(); + public static com.mapconductor.vectortile.VectorTileProvider$Content valueOf(java.lang.String); + public static kotlin.enums.EnumEntries getEntries(); +} +public final class com.mapconductor.vectortile.VectorTileProvider$RenderMode extends java.lang.Enum { + public static final com.mapconductor.vectortile.VectorTileProvider$RenderMode CPU; + public static final com.mapconductor.vectortile.VectorTileProvider$RenderMode GPU; + public static final com.mapconductor.vectortile.VectorTileProvider$RenderMode AUTO; + public static com.mapconductor.vectortile.VectorTileProvider$RenderMode[] values(); + public static com.mapconductor.vectortile.VectorTileProvider$RenderMode valueOf(java.lang.String); + public static kotlin.enums.EnumEntries getEntries(); +} +public final class com.mapconductor.vectortile.VectorTileRasteriser implements com.mapconductor.vectorstyle.VectorStyleRasteriser { + public com.mapconductor.vectortile.VectorTileRasteriser(java.lang.Integer, java.util.Map, java.io.File, com.mapconductor.vectortile.VectorTileProvider$RenderMode, java.lang.Integer); + public com.mapconductor.vectortile.VectorTileRasteriser(java.lang.Integer, java.util.Map, java.io.File, com.mapconductor.vectortile.VectorTileProvider$RenderMode, java.lang.Integer, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.vectorstyle.VectorStyleRasterisation install(com.mapconductor.core.map.MapStyleHost, java.lang.String, com.mapconductor.vectorstyle.StyleAffects); + public com.mapconductor.vectortile.VectorTileRasteriser(); +} +final class com.mapconductor.vectortile.VectorTileRasteriser$Rasterisation implements com.mapconductor.vectorstyle.VectorStyleRasterisation { + public static final int MAX_ZOOM; + public final void start(java.lang.String); + public void restyle(java.lang.String, com.mapconductor.vectorstyle.StyleAffects); + public void dispose(); +} +final class com.mapconductor.vectortile.VectorTileRasteriser$Rasterisation$Companion { + public final java.util.concurrent.ExecutorService getWorkers(); +} +public final class com.mapconductor.vectortile.VectorTileRenderer implements java.io.Closeable { + public static final com.mapconductor.vectortile.VectorTileRenderer$Companion Companion; + public static final int DEFAULT_TILE_SIZE; + public static final int OUTPUT_VERSION; + public final java.lang.String plan(int, int, int); + public final java.lang.String glyphsUrlTemplate(); + public final java.util.List neededGlyphs(int, int, int, java.util.List); + public final int addGlyphs(byte[]); + public final java.util.List spriteUrls(int); + public final boolean needsCpu(int, java.util.List); + public final boolean needsSprite(); + public final int addSprite(java.lang.String, byte[]); + public final int drawLabels(int, int, int, int, byte[], java.util.List); + public final byte[] render(int, int, int, int, java.util.List, boolean); + public final void setStyle(java.lang.String); + public final java.lang.String unsupportedLayerTypes(); + public final java.lang.String attributions(); + public final java.lang.String diagnostics(); + public void close(); + public static final com.mapconductor.vectortile.VectorTileRenderer create(java.lang.String, int); + public com.mapconductor.vectortile.VectorTileRenderer(long, kotlin.jvm.internal.DefaultConstructorMarker); +} +public final class com.mapconductor.vectortile.VectorTileRenderer$Companion { + public final com.mapconductor.vectortile.VectorTileRenderer create(java.lang.String, int); +} diff --git a/android-vectortile/build.gradle.kts b/android-vectortile/build.gradle.kts new file mode 100644 index 000000000..1b65852c4 --- /dev/null +++ b/android-vectortile/build.gradle.kts @@ -0,0 +1,89 @@ +plugins { + alias(libs.plugins.android.library) + alias(libs.plugins.kotlin.compose) + id("org.jlleitschuh.gradle.ktlint") version "14.2.0" + id("maven-publish") + id("signing") + id("com.gradleup.nmcp") version "1.5.0" +} + +ktlint { + android.set(true) + reporters { + reporter(org.jlleitschuh.gradle.ktlint.reporter.ReporterType.PLAIN) + reporter(org.jlleitschuh.gradle.ktlint.reporter.ReporterType.CHECKSTYLE) + } +} + +android { + namespace = "com.mapconductor.vectortile" + compileSdk = project.property("compileSdk").toString().toInt() + + defaultConfig { + minSdk = project.property("minSdk").toString().toInt() + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles("consumer-rules.pro") + aarMetadata { + minCompileSdk = project.property("compileSdk").toString().toInt() + } + // Only arm64 is prebuilt today; adding ABIs is a matter of adding + // targets to mapconductor-vectortile/scripts/build-android.sh. + ndk { abiFilters += "arm64-v8a" } + } + + buildFeatures { + compose = true + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro", + ) + } + } + + compileOptions { + sourceCompatibility = JavaVersion.toVersion(project.property("javaVersion").toString()) + targetCompatibility = JavaVersion.toVersion(project.property("javaVersion").toString()) + } + + publishing { + singleVariant("release") { + withSourcesJar() + } + } +} + +dependencies { + if (findProject(":android-sdk-compose") != null) { + implementation(project(":android-sdk-compose")) + } else { + implementation("com.mapconductor:compose:${project.findProperty("coreLibraryVersion") as String? ?: "1.0.0"}") + } + + // `VectorStyleRasteriser` はあちらが宣言し、こちらが実装する + // (`VectorTileRasteriser`)。依存の向きはこの一方向だけ。 + if (findProject(":android-vectorstyle") != null) { + api(project(":android-vectorstyle")) + } else { + api("com.mapconductor:vectorstyle:${project.findProperty("coreLibraryVersion") as String? ?: "1.0.0"}") + } + + implementation(libs.kotlinx.coroutines.android) + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.runtime) + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + // The marker tile cost benchmark measures android-sdk-core's renderer + // against this module's Rust PNG encoder, so the test source set needs + // core on its compile classpath directly. + androidTestImplementation(project(":android-sdk-core")) + // The street tree benchmark builds its own MarkerIconInterface, whose + // members are Compose geometry types. + androidTestImplementation(libs.androidx.ui) +} diff --git a/android-vectortile/consumer-rules.pro b/android-vectortile/consumer-rules.pro new file mode 100644 index 000000000..e69de29bb diff --git a/android-vectortile/proguard-rules.pro b/android-vectortile/proguard-rules.pro new file mode 100644 index 000000000..03ee1bcc0 --- /dev/null +++ b/android-vectortile/proguard-rules.pro @@ -0,0 +1,5 @@ +# The JNI entry points are resolved by name from native code, so R8 must not +# rename or strip them. +-keepclasseswithmembernames class com.mapconductor.vectortile.NativeRenderer { + native ; +} diff --git a/android-vectortile/src/androidTest/AndroidManifest.xml b/android-vectortile/src/androidTest/AndroidManifest.xml new file mode 100644 index 000000000..68f484a43 --- /dev/null +++ b/android-vectortile/src/androidTest/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/android-vectortile/src/androidTest/assets/demo-style.json b/android-vectortile/src/androidTest/assets/demo-style.json new file mode 100644 index 000000000..2cad3c2b4 --- /dev/null +++ b/android-vectortile/src/androidTest/assets/demo-style.json @@ -0,0 +1 @@ +{"id": "43f36e14-e3f5-43c1-84c0-50a9c80dc5c7", "name": "MapLibre", "zoom": 0.8619833357855968, "pitch": 0, "center": [17.65431710431244, 32.954120326746775], "glyphs": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf", "layers": [{"id": "background", "type": "background", "paint": {"background-color": "#D8F2FF"}, "filter": ["all"], "layout": {"visibility": "visible"}, "maxzoom": 24}, {"id": "coastline", "type": "line", "paint": {"line-blur": 0.5, "line-color": "#198EC8", "line-width": {"stops": [[0, 2], [6, 6], [14, 9], [22, 18]]}}, "filter": ["all"], "layout": {"line-cap": "round", "line-join": "round", "visibility": "visible"}, "source": "maplibre", "maxzoom": 24, "minzoom": 0, "source-layer": "countries"}, {"id": "countries-fill", "type": "fill", "paint": {"fill-color": ["match", ["get", "ADM0_A3"], ["ARM", "ATG", "AUS", "BTN", "CAN", "COG", "CZE", "GHA", "GIN", "HTI", "ISL", "JOR", "KHM", "KOR", "LVA", "MLT", "MNE", "MOZ", "PER", "SAH", "SGP", "SLV", "SOM", "TJK", "TUV", "UKR", "WSM"], "#D6C7FF", ["AZE", "BGD", "CHL", "CMR", "CSI", "DEU", "DJI", "GUY", "HUN", "IOA", "JAM", "LBN", "LBY", "LSO", "MDG", "MKD", "MNG", "MRT", "NIU", "NZL", "PCN", "PYF", "SAU", "SHN", "STP", "TTO", "UGA", "UZB", "ZMB"], "#EBCA8A", ["AGO", "ASM", "ATF", "BDI", "BFA", "BGR", "BLZ", "BRA", "CHN", "CRI", "ESP", "HKG", "HRV", "IDN", "IRN", "ISR", "KNA", "LBR", "LCA", "MAC", "MUS", "NOR", "PLW", "POL", "PRI", "SDN", "TUN", "UMI", "USA", "USG", "VIR", "VUT"], "#C1E599", ["ARE", "ARG", "BHS", "CIV", "CLP", "DMA", "ETH", "GAB", "GRD", "HMD", "IND", "IOT", "IRL", "IRQ", "ITA", "KOS", "LUX", "MEX", "NAM", "NER", "PHL", "PRT", "RUS", "SEN", "SUR", "TZA", "VAT"], "#E7E58F", ["AUT", "BEL", "BHR", "BMU", "BRB", "CYN", "DZA", "EST", "FLK", "GMB", "GUM", "HND", "JEY", "KGZ", "LIE", "MAF", "MDA", "NGA", "NRU", "SLB", "SOL", "SRB", "SWZ", "THA", "TUR", "VEN", "VGB"], "#98DDA1", ["AIA", "BIH", "BLM", "BRN", "CAF", "CHE", "COM", "CPV", "CUB", "ECU", "ESB", "FSM", "GAZ", "GBR", "GEO", "KEN", "LTU", "MAR", "MCO", "MDV", "NFK", "NPL", "PNG", "PRY", "QAT", "SLE", "SPM", "SYC", "TCA", "TKM", "TLS", "VNM", "WEB", "WSB", "YEM", "ZWE"], "#83D5F4", ["ABW", "ALB", "AND", "ATC", "BOL", "COD", "CUW", "CYM", "CYP", "EGY", "FJI", "GGY", "IMN", "KAB", "KAZ", "KWT", "LAO", "MLI", "MNP", "MSR", "MYS", "NIC", "NLD", "PAK", "PAN", "PRK", "ROU", "SGS", "SVN", "SWE", "TGO", "TWN", "VCT", "ZAF"], "#B1BBF9", ["ATA", "GRL"], "#FFFFFF", "#EAB38F"]}, "filter": ["all"], "layout": {"visibility": "visible"}, "source": "maplibre", "maxzoom": 24, "source-layer": "countries"}, {"id": "countries-boundary", "type": "line", "paint": {"line-color": "rgba(255, 255, 255, 1)", "line-width": {"stops": [[1, 1], [6, 2], [14, 6], [22, 12]]}, "line-opacity": {"stops": [[3, 0.5], [6, 1]]}}, "layout": {"line-cap": "round", "line-join": "round", "visibility": "visible"}, "source": "maplibre", "maxzoom": 24, "source-layer": "countries"}, {"id": "geolines", "type": "line", "paint": {"line-color": "#1077B0", "line-opacity": 1, "line-dasharray": [3, 3]}, "filter": ["all", ["!=", "name", "International Date Line"]], "layout": {"visibility": "visible"}, "source": "maplibre", "maxzoom": 24, "source-layer": "geolines"}, {"id": "geolines-label", "type": "symbol", "paint": {"text-color": "#1077B0", "text-halo-blur": 1, "text-halo-color": "rgba(255, 255, 255, 1)", "text-halo-width": 1}, "filter": ["all", ["!=", "name", "International Date Line"]], "layout": {"text-font": ["Open Sans Semibold"], "text-size": {"stops": [[2, 12], [6, 16]]}, "text-field": "{name}", "visibility": "visible", "symbol-placement": "line"}, "source": "maplibre", "maxzoom": 24, "minzoom": 1, "source-layer": "geolines"}, {"id": "countries-label", "type": "symbol", "paint": {"text-color": "rgba(8, 37, 77, 1)", "text-halo-blur": {"stops": [[2, 0.2], [6, 0]]}, "text-halo-color": "rgba(255, 255, 255, 1)", "text-halo-width": {"stops": [[2, 1], [6, 1.6]]}}, "filter": ["all"], "layout": {"text-font": ["Open Sans Semibold"], "text-size": {"stops": [[2, 10], [4, 12], [6, 16]]}, "text-field": {"stops": [[2, "{ABBREV}"], [4, "{NAME}"]]}, "visibility": "visible", "text-max-width": 10, "text-transform": {"stops": [[0, "uppercase"], [2, "none"]]}}, "source": "maplibre", "maxzoom": 24, "minzoom": 2, "source-layer": "centroids"}, {"id": "crimea-fill", "type": "fill", "source": "crimea", "paint": {"fill-color": "#D6C7FF"}}], "bearing": 0, "sources": {"maplibre": {"type": "vector", "tiles": ["https://demotiles.maplibre.org/tiles/{z}/{x}/{y}.pbf"], "minzoom": 0, "maxzoom": 6}, "crimea": {"type": "geojson", "data": {"type": "Feature", "geometry": {"type": "Polygon", "coordinates": [[[34.00905273547181, 46.55925987559425], [33.64325260204026, 46.34533545368038], [33.628682598560204, 46.12569762665683], [33.64292861730951, 46.10476396128129], [33.648473474905984, 46.09033047763651], [33.63876482059936, 46.077976784785335], [33.62782672238245, 46.06747935719011], [33.62911357645072, 46.05708111413949], [33.642686868727424, 46.02192963417187], [33.6429723910654, 46.01521185644708], [33.636224138774026, 46.006705833212465], [33.63052626465907, 45.99692992186792], [33.63193836679693, 45.988472992911284], [33.64276684834442, 45.984575360297384], [33.646928693041986, 45.97981936210982], [33.638745893564305, 45.96829769147004], [33.61958133326394, 45.951176418494185], [33.63181380398527, 45.9445404758078], [33.638921676216, 45.94737012930554], [33.64561542516918, 45.95403251372139], [33.65666403976448, 45.95687114427736], [33.6825817382811, 45.95878100879199], [33.738791807037614, 45.94836945227263], [33.758180142697, 45.94072970008301], [33.77735917288169, 45.92923970233858], [33.75927796793485, 45.92241179584471], [33.72529865009221, 45.91587363154565], [33.70875012326826, 45.91008760988058], [33.69378857293381, 45.91480850795665], [33.69092650243843, 45.89657370898402], [33.693592356906805, 45.87271465766318], [33.69226765972388, 45.86041392418218], [33.6704813511748, 45.8584273836251], [33.65936345808916, 45.85944682601249], [33.653870582376726, 45.86425922279372], [33.65107345584843, 45.87089907254003], [33.63067378180233, 45.88040685247182], [33.61945300059696, 45.88147266102649], [33.60987421595539, 45.88048951126686], [33.59906957603934, 45.877610457390375], [33.57828877687868, 45.86810261756233], [33.55357394560386, 45.84700625141778], [33.530220674480375, 45.84221983655459], [33.5192297395441, 45.84121682367507], [33.50832088442496, 45.84313067048083], [33.48901101848409, 45.85268298292175], [33.482152996405716, 45.854578171799005], [33.46719955896293, 45.849912739405056], [33.42447496599681, 45.83075886348303], [33.40940172404095, 45.82691953557702], [33.37918350072067, 45.802867525073566], [33.37362145339398, 45.79619281922518], [33.33805543634864, 45.78577808972071], [33.26498872665803, 45.75410774187094], [33.22887541283427, 45.75131270772724], [33.19548267281132, 45.7644887297206], [33.1789202379222, 45.78010311364778], [33.1688456078636, 45.78470227904205], [33.161012432811674, 45.77921593899549], [33.15951585299757, 45.76864464913777], [33.165962301438725, 45.762685940125465], [33.1750888126426, 45.759218220695715], [33.181464829753, 45.75490447884948], [33.17613930782352, 45.7437961960276], [33.16369168844906, 45.735912015025065], [32.93692665480876, 45.662114646778264], [32.86839112407645, 45.63044340698664], [32.83803944575723, 45.60834075026611], [32.82702772424804, 45.59576101516498], [32.82433467080986, 45.58705137380335], [32.82563941622885, 45.579605763895614], [32.82993674258438, 45.56978311819469], [32.82851940940563, 45.56227808675749], [32.813310142795274, 45.55930933158257], [32.80213583657516, 45.560145780074464], [32.78258622159436, 45.565158335073846], [32.77333922465823, 45.56689313356526], [32.758306734735356, 45.565030173463356], [32.750177256846115, 45.55943726334968], [32.74340732630185, 45.55261895849793], [32.73524549539499, 45.54598788110354], [32.72031700779701, 45.53735927760957], [32.70536040418847, 45.53169142131733], [32.68589438933773, 45.52663379187257], [32.66370583186284, 45.52563107058867], [32.64312077736798, 45.52188979044979], [32.525284074162556, 45.45838108691365], [32.49490411219156, 45.43524910229854], [32.48107654411925, 45.408986638827514], [32.48514589713025, 45.39458067125969], [32.51256939517424, 45.34060655033625], [32.535915460470335, 45.33777248012882], [32.57027153843481, 45.32510892683359], [32.590830644991826, 45.32038723212662], [32.66380378113439, 45.320421746458976], [32.67760722618917, 45.32609231279554], [32.71316246802607, 45.353283572618125], [32.72817188836078, 45.36074681043402], [32.750518060251466, 45.36371725645313], [32.89973931692998, 45.35412322462227], [32.941197846443885, 45.34245505845169], [32.97701667405008, 45.32596743563991], [33.04296090827762, 45.2853982930032], [33.05274355585479, 45.28154273654923], [33.06850284417635, 45.27703461892352], [33.07825272648239, 45.272210805127315], [33.089426322403455, 45.25656353201492], [33.09897492343546, 45.247820101667884], [33.12384611720435, 45.238235755071685], [33.15767197859745, 45.20755227709648], [33.172959979330074, 45.19681657531794], [33.21837666514142, 45.187878368659824], [33.24017433636709, 45.180191106261134], [33.248571989896675, 45.16588271012458], [33.259649216030766, 45.155918961282026], [33.28309785485047, 45.16064860772312], [33.31767999550894, 45.17535522412791], [33.35458473323109, 45.18598673360148], [33.39725661527919, 45.18973663076909], [33.41344561756824, 45.18490731877088], [33.468468576977216, 45.149132412229676], [33.537128652906205, 45.11719769268973], [33.56161328289443, 45.094099022711475], [33.57837628774928, 45.053145935448015], [33.58247744978442, 45.027377243150454], [33.5851414316958, 45.01816461606674], [33.6031021265521, 44.993103583251695], [33.605922209331794, 44.986905272229734], [33.60843524291815, 44.97039962759274], [33.61943161357851, 44.93184946652454], [33.619484500808824, 44.90819321920554], [33.61549738593425, 44.88894092276257], [33.608561183117274, 44.871288478948514], [33.59889474705494, 44.859790298912856], [33.55904244709464, 44.850057575124595], [33.54667558363471, 44.83724531175508], [33.53701832136994, 44.81871953508235], [33.5303157846202, 44.798338017069625], [33.5249116915937, 44.78918633101301], [33.51669091675143, 44.784809980590666], [33.524785531609865, 44.77183212449111], [33.5302902535075, 44.75724515985675], [33.53710734694323, 44.73034290771247], [33.54650992495621, 44.70989226909535], [33.5481286806762, 44.699106546699085], [33.543995566510915, 44.68230506537358], [33.53580273994743, 44.6726082589706], [33.52337411931097, 44.661863083605255], [33.515320778874354, 44.6491266698327], [33.516377841582795, 44.63464990118433], [33.52466971637648, 44.62863961572572], [33.557474298027785, 44.62473000923737], [33.5710648827386, 44.620853511273225], [33.55105839203679, 44.61506440493406], [33.499905706797676, 44.61452599304897], [33.48451102966331, 44.60992438254493], [33.47658499621011, 44.60714391514574], [33.46705078205747, 44.60616254193252], [33.44476599234898, 44.607062134677875], [33.4353466482458, 44.60509936890821], [33.413591053005575, 44.593500212748125], [33.40543527945235, 44.59055535193136], [33.37510958624222, 44.58564691897425], [33.37074452434078, 44.58851022190515], [33.372237834990756, 44.576810695127364], [33.37913003799301, 44.56412673079859], [33.48759131590526, 44.51024086451031], [33.50011215135888, 44.50041002882833], [33.517917009115365, 44.49074142372788], [33.53836387802215, 44.49164280212756], [33.56041892763031, 44.4966411022441], [33.57822378538677, 44.497542389459795], [33.59062975079095, 44.48975808594983], [33.619577003408466, 44.46229988129974], [33.62635433636015, 44.45336293328907], [33.63175322871038, 44.434828756313124], [33.645537634715026, 44.42498521035591], [33.721007257593925, 44.39946630464436], [33.74168386660085, 44.39560878121904], [33.80727466517129, 44.39454176175843], [33.81841706002561, 44.39552670349164], [33.83909366903248, 44.40143600575672], [33.85149963444792, 44.40143600575945], [33.91467816197718, 44.38387049706651], [33.938111652185, 44.38083293528811], [33.957065210440874, 44.38272116790142], [34.06614966692763, 44.42019923628979], [34.088893936836286, 44.42200415824283], [34.10279321289039, 44.42487551014821], [34.135933345669, 44.44163597968952], [34.14696087047267, 44.44959070749778], [34.16058918507403, 44.466287285335795], [34.170123399227776, 44.48186111741296], [34.182759104731986, 44.49267838558103], [34.22923417224524, 44.49949719774551], [34.24301857824986, 44.50744404277697], [34.263903954150294, 44.53186886058606], [34.26631622520165, 44.53555362837611], [34.26631622520165, 44.54153064468656], [34.27033667695244, 44.545378535987936], [34.2757355693048, 44.54644280144541], [34.285384653508004, 44.54562413743594], [34.299973149863405, 44.54554227040174], [34.32260254971496, 44.543577427039224], [34.3308731933177, 44.54546040325087], [34.340292537420794, 44.55798473830754], [34.38042135640006, 44.631830317636684], [34.41495238900856, 44.673669777529994], [34.424193090575585, 44.68239452736094], [34.42959198292681, 44.68884644523774], [34.469399167794535, 44.730194532749294], [34.47376422969597, 44.73011292571252], [34.47376422969597, 44.72635887754967], [34.475142670296464, 44.723502373339585], [34.499724861011515, 44.74292382044041], [34.532800295801195, 44.752620844929055], [34.61217550038418, 44.76534519537847], [34.65065696715081, 44.777088262503725], [34.72084256772871, 44.811080759265764], [34.756796893391225, 44.82094054159748], [34.82646979041766, 44.81208604604609], [34.84289620758207, 44.816893835303176], [34.856910353686715, 44.82373813182468], [34.889648317948144, 44.817871641692506], [34.90733830566026, 44.820886440346584], [34.922960632465504, 44.83050015059965], [34.92950822531711, 44.83652826953224], [34.94179932067178, 44.84019370922482], [34.95282684547897, 44.841415470643284], [34.98567967978991, 44.840275160795755], [35.0053224583441, 44.83538786296728], [35.017958163849414, 44.82219008824552], [35.02703289780189, 44.80890779582285], [35.037933245998005, 44.79869792240089], [35.08073333784134, 44.793525442788905], [35.1080207326404, 44.824553365795765], [35.130368105574235, 44.86879838545747], [35.15485200090768, 44.90071251697748], [35.17111229780758, 44.90746386008772], [35.21522068940149, 44.91421441031795], [35.233163085981715, 44.925728224907715], [35.25636688416236, 44.95896657181197], [35.27300098099195, 44.96690119386028], [35.29748487632534, 44.95605693543271], [35.30496087491386, 44.96121482614441], [35.315240372954605, 44.965711070514175], [35.31935217217088, 44.96941359539801], [35.36757236298112, 44.94362319076086], [35.36103086422793, 44.97364475976596], [35.362152264014156, 44.98593980935419], [35.374674561627444, 44.997835734117416], [35.389439658813274, 45.00180049366759], [35.42270785247763, 45.00087540764923], [35.43504325012745, 45.00470780964241], [35.43504325012745, 45.011446929213974], [35.40631957913584, 45.02015821022701], [35.40089948016896, 45.025046135473445], [35.39790908073891, 45.03482073400548], [35.40052568024015, 45.042216617888045], [35.40631957913584, 45.051328088783805], [35.40744097892215, 45.06294640963205], [35.41734667704213, 45.0708666385693], [35.469304867139925, 45.10068964922732], [35.5070260597534, 45.113341616151644], [35.54758335202416, 45.12019982412133], [35.59019654390909, 45.11993606213795], [35.63411803553862, 45.11439677872579], [35.70669729572677, 45.09480210570922], [35.771782422456766, 45.06572995732262], [35.78430472007, 45.057941041321754], [35.81250040352472, 45.031852200991295], [35.81941570220667, 45.021152336906454], [35.82763930064016, 44.99895365027004], [35.848198296721705, 44.99208088455586], [35.916977483614176, 45.00172895661731], [35.99360646900681, 44.997896355361604], [36.00893226608571, 45.00926125333629], [36.02539976723364, 45.03288661039673], [36.047827762958946, 45.048074065419456], [36.078666257082034, 45.03883000769565], [36.079137312377895, 45.046610970582435], [36.135020401727616, 45.02125162210126], [36.2241716847341, 45.00751061631556], [36.24398308095806, 45.011474706353084], [36.24828178013877, 45.01649549321965], [36.25332807917695, 45.03247980324494], [36.25743987839326, 45.03842324279259], [36.267158676549116, 45.043573724415154], [36.2783726744118, 45.04555455542638], [36.36740852558336, 45.04833265291825], [36.44029951169139, 45.06787222615526], [36.45375630913995, 45.07631970334319], [36.455251508854985, 45.09202341204062], [36.44142091149291, 45.10709638287736], [36.41432041665814, 45.12872568311289], [36.40852651776157, 45.149160473330085], [36.409997342308856, 45.171615955386955], [36.418312796420764, 45.23001671705953], [36.42672329481775, 45.25186253492981], [36.43756477765089, 45.27227491599612], [36.4497132753354, 45.28542626329343], [36.45905827355429, 45.28753019598713], [36.4814862692796, 45.28845064200263], [36.4909554290368, 45.29213135137758], [36.49637552800283, 45.300940007322055], [36.49394582846682, 45.305015191082816], [36.48871262946426, 45.30935296803605], [36.48460083024801, 45.315924724862185], [36.489647129296515, 45.336413860372005], [36.502169426909745, 45.34731734941451], [36.52104632331191, 45.35033842661815], [36.544281237819945, 45.34731734942025], [36.57455903204905, 45.33601971904315], [36.585399229982954, 45.333917585593355], [36.59810088537549, 45.334837278577254], [36.630808379142394, 45.34048649352954], [36.637536777859964, 45.3511265071989], [36.63099527910589, 45.3741073632589], [36.61359545390113, 45.40895280985421], [36.59845655678569, 45.421547717459106], [36.58331765967199, 45.42731944465129], [36.566309762912795, 45.42548305000767], [36.54836736633254, 45.41210180010589], [36.53285466928139, 45.4090840212946], [36.51565987255873, 45.41957994832251], [36.49117597722616, 45.44279525429408], [36.47043008117939, 45.4458112314303], [36.411182792482634, 45.43610707766504], [36.391371396258705, 45.43991025572652], [36.35959840231365, 45.45407156049933], [36.33960010612526, 45.45695583486963], [36.33025510790637, 45.454464879327446], [36.32053630976225, 45.44856480887407], [36.31156511147125, 45.4438443081136], [36.29885591389362, 45.442795254299995], [36.3072664122906, 45.46115087970253], [36.30016421364425, 45.47320989503609], [36.283717016779036, 45.476355300848866], [36.267082919949445, 45.46704963343626], [36.25213092279836, 45.46115087970253], [36.13681364478941, 45.46219959214511], [36.11700224855986, 45.45721803432335], [36.097003952371466, 45.441483909606006], [36.06952965760803, 45.43046741078453], [36.0655449627526, 45.42553028973455], [36.05134056545904, 45.39535242162091], [36.022557970944945, 45.368441166003805], [35.986486277818386, 45.362926059418186], [35.94723728529826, 45.372380198658874], [35.87220216002379, 45.404075760536614], [35.85388596351393, 45.413916621802144], [35.84715756479628, 45.426379251448395], [35.8524047739447, 45.44386497541683], [35.85950697259193, 45.45933624762881], [35.857824872912545, 45.469953901705], [35.83278027768503, 45.47087138287168], [35.8167068807486, 45.46392436820739], [35.80362388324218, 45.44963442058864], [35.79469305616038, 45.42980210462429], [35.791889556694684, 45.41209230278156], [35.772265060435046, 45.39214572935421], [35.767405661361295, 45.38873311015669], [35.75189296431793, 45.386632934388984], [35.7481549650407, 45.379938103368545], [35.746846665290036, 45.369960021421576], [35.74423006578874, 45.36076812520648], [35.71619507113218, 45.34040932557082], [35.69451467527287, 45.32989869277279], [35.51720627467216, 45.29506847418358], [35.48038698168983, 45.2979608697527], [35.33194061536096, 45.371562726652314], [35.04491375777232, 45.669545248704424], [35.00230056589345, 45.7290693869553], [34.70631294999043, 46.024929846739866], [34.35868883309806, 46.106725558140795], [34.00905273547181, 46.55925987559425]]]}}}}, "version": 8, "metadata": {"maptiler:copyright": "This style was generated on MapTiler Cloud. Usage is governed by the license terms in https://github.com/maplibre/demotiles/blob/gh-pages/LICENSE", "openmaptiles:version": "3.x"}} \ No newline at end of file diff --git a/android-vectortile/src/androidTest/assets/road-resolution-experiment/11-1808-807.mvt b/android-vectortile/src/androidTest/assets/road-resolution-experiment/11-1808-807.mvt new file mode 100644 index 000000000..4099caac9 Binary files /dev/null and b/android-vectortile/src/androidTest/assets/road-resolution-experiment/11-1808-807.mvt differ diff --git a/android-vectortile/src/androidTest/assets/road-resolution-experiment/README.md b/android-vectortile/src/androidTest/assets/road-resolution-experiment/README.md new file mode 100644 index 000000000..28756c188 --- /dev/null +++ b/android-vectortile/src/androidTest/assets/road-resolution-experiment/README.md @@ -0,0 +1,30 @@ +# Road raster resolution experiment + +Actual Shortbread tile 11/1808/807 from the Pixel 5a cache, captured 2026-10-07: +https://vector.openstreetmap.org/shortbread_v1/11/1808/807.mvt + +© OpenStreetMap contributors: https://www.openstreetmap.org/copyright +Style: https://tiles.versatiles.org/assets/styles/colorful/style.json +Sources are rewritten as in the example app. + +RoadResolutionExperimentTest decodes/tessellates once and renders the exact same +vertex buffer, style, extent and batches at 512 and 1024 pixels. Both use ES3 and +4x MSAA. These fixtures and tests are not included in the production library. + +Pixel 5a results: median draw+MSAA resolve+readback of seven samples: +512: 4.37ms; 1024: 9.81ms. Timing includes readback buffer allocation; production +uses a buffer pool. Upload/tessellation, framebuffer creation and PNG encoding +are excluded. Larger buffers and MSAA attachments cost approximately 4x memory. + +The 512 image was pixel-identical to the example app's cached geometry PNG. +The 1024 image shows smoother road edges at the same display size. +This test is an isolated tile experiment. The online and offline example pages +now request 2x ground resolution on OMM and Google Maps. + +Run from android-sdk: + + ./gradlew :android-vectortile:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.mapconductor.vectortile.RoadResolutionExperimentTest + +To retrieve images, install the Android test APK and run instrumentation directly, +then pull Android/data/com.mapconductor.vectortile.test/files/road-resolution-experiment +from the device. The Gradle connected-test task uninstalls its temporary APK. diff --git a/android-vectortile/src/androidTest/assets/road-resolution-experiment/style.json b/android-vectortile/src/androidTest/assets/road-resolution-experiment/style.json new file mode 100644 index 000000000..c7bd8d750 --- /dev/null +++ b/android-vectortile/src/androidTest/assets/road-resolution-experiment/style.json @@ -0,0 +1 @@ +{"version": 8, "name": "versatiles-colorful", "metadata": {"license": "https://creativecommons.org/publicdomain/zero/1.0/"}, "glyphs": "https://tiles.versatiles.org/assets/glyphs/{fontstack}/{range}.pbf", "sprite": [{"id": "base", "url": "https://tiles.versatiles.org/assets/sprites/base"}], "sources": {"versatiles-shortbread": {"type": "vector", "tiles": ["https://vector.openstreetmap.org/shortbread_v1/{z}/{x}/{y}.mvt"], "minzoom": 0, "maxzoom": 14}}, "layers": [{"id": "background", "type": "background", "paint": {"background-color": "rgb(248,244,240)"}}, {"id": "slot-below-fills", "type": "background", "paint": {"background-opacity": 0}}, {"id": "water-ocean", "type": "fill", "source-layer": "ocean", "paint": {"fill-color": "rgb(191,217,242)"}, "source": "versatiles-shortbread"}, {"id": "land-glacier", "type": "fill", "source-layer": "water_polygons", "filter": ["==", ["get", "kind"], "glacier"], "paint": {"fill-color": "rgb(255,255,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "land-commercial", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["commercial", "retail"]]], "paint": {"fill-color": "rgb(248,238,239)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-industrial", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["industrial", "quarry", "railway"]]], "paint": {"fill-color": "rgb(250,244,225)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-residential", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["garages", "residential"]]], "paint": {"fill-color": "rgb(245,241,237)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-agriculture", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["farmland", "farmyard", "greenhouse_horticulture", "orchard", "plant_nursery", "vineyard"]]], "paint": {"fill-color": "rgb(233,242,206)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-waste", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["landfill"]]], "paint": {"fill-color": "rgb(219,214,189)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-park", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["park", "village_green", "recreation_ground"]]], "paint": {"fill-color": "rgba(205,217,169,0.5)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-garden", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["allotments", "garden"]]], "paint": {"fill-color": "rgb(205,217,169)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-burial", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["cemetery", "grave_yard"]]], "paint": {"fill-color": "rgb(224,228,221)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "land-leisure", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["miniature_golf", "playground", "golf_course"]]], "paint": {"fill-color": "rgb(231,237,222)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-rock", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["bare_rock", "scree", "shingle"]]], "paint": {"fill-color": "rgb(242,242,230)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-forest", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["forest"]]], "paint": {"fill-color": "rgb(203,229,184)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 1]}, "minzoom": 7, "source": "versatiles-shortbread"}, {"id": "land-grass", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["grass", "grassland", "meadow", "wet_meadow"]]], "paint": {"fill-color": "rgb(209,229,195)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-vegetation", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["heath", "scrub"]]], "paint": {"fill-color": "rgb(230,238,199)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "land-sand", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["beach", "sand"]]], "paint": {"fill-color": "rgb(242,242,206)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "land-wetland", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["bog", "marsh", "string_bog", "swamp"]]], "paint": {"fill-color": "rgb(211,230,219)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "site-dangerarea", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "danger_area"], "paint": {"fill-color": "rgb(255,0,0)", "fill-outline-color": "rgb(255,0,0)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.302], "fill-pattern": "base:pattern-hatched"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-sportscentre", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "sports_centre"], "paint": {"fill-color": "rgba(246,243,238,0.149)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-education", "type": "fill", "source-layer": "sites", "filter": ["any", ["==", ["get", "kind"], "university"], ["==", ["get", "kind"], "college"], ["==", ["get", "kind"], "school"]], "paint": {"fill-color": "rgba(255,255,128,0.125)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-hospital", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "hospital"], "paint": {"fill-color": "rgba(255,102,102,0.102)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-prison", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "prison"], "paint": {"fill-color": "rgb(253,242,252)", "fill-pattern": "base:pattern-striped", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.102]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-parking", "type": "fill", "source-layer": "sites", "filter": ["any", ["==", ["get", "kind"], "parking"], ["==", ["get", "kind"], "bicycle_parking"]], "paint": {"fill-color": "rgb(235,232,230)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "site-construction", "type": "fill", "source-layer": "sites", "filter": ["==", ["get", "kind"], "construction"], "paint": {"fill-color": "rgb(169,169,169)", "fill-pattern": "base:pattern-hatched_thin", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.102]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "water-river", "type": "line", "source-layer": "water_lines", "filter": ["all", ["==", ["get", "kind"], "river"], ["!=", ["get", "tunnel"], true], ["!=", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,202,237)", "line-width": ["interpolate", ["exponential", 1.2], ["zoom"], 10, 0.8, 20, 6]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "water-canal", "type": "line", "source-layer": "water_lines", "filter": ["all", ["==", ["get", "kind"], "canal"], ["!=", ["get", "tunnel"], true], ["!=", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,202,237)", "line-width": ["interpolate", ["exponential", 1.3], ["zoom"], 13, 0.5, 20, 6]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "water-stream", "type": "line", "source-layer": "water_lines", "filter": ["all", ["==", ["get", "kind"], "stream"], ["!=", ["get", "tunnel"], true], ["!=", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,202,237)", "line-width": ["interpolate", ["exponential", 1.3], ["zoom"], 13, 0.5, 20, 6]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "water-ditch", "type": "line", "source-layer": "water_lines", "filter": ["all", ["==", ["get", "kind"], "ditch"], ["!=", ["get", "tunnel"], true], ["!=", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,202,237)", "line-width": ["interpolate", ["exponential", 1.3], ["zoom"], 13, 0.5, 20, 2]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "water-area", "type": "fill", "source-layer": "water_polygons", "filter": ["==", ["get", "kind"], "water"], "paint": {"fill-color": "rgb(191,217,242)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "water-area-river", "type": "fill", "source-layer": "water_polygons", "filter": ["==", ["get", "kind"], "river"], "paint": {"fill-color": "rgb(191,217,242)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "water-area-small", "type": "fill", "source-layer": "water_polygons", "filter": ["in", ["get", "kind"], ["literal", ["reservoir", "basin", "dock"]]], "paint": {"fill-color": "rgb(191,217,242)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "water-dam-area", "type": "fill", "source-layer": "dam_polygons", "filter": ["==", ["get", "kind"], "dam"], "paint": {"fill-color": "rgb(248,244,240)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "water-dam", "type": "line", "source-layer": "dam_lines", "filter": ["==", ["get", "kind"], "dam"], "paint": {"line-color": "rgb(191,217,242)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1, 16, 4, 18, 18, 20, 90]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "water-pier-area", "type": "fill", "source-layer": "pier_polygons", "filter": ["in", ["get", "kind"], ["literal", ["pier", "breakwater", "groyne"]]], "paint": {"fill-color": "rgb(248,244,240)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "water-pier", "type": "line", "source-layer": "pier_lines", "filter": ["in", ["get", "kind"], ["literal", ["pier", "breakwater", "groyne"]]], "paint": {"line-color": "rgb(248,244,240)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1, 16, 4, 18, 18, 20, 90]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "airport-area", "type": "fill", "source-layer": "street_polygons", "filter": ["in", ["get", "kind"], ["literal", ["runway", "taxiway"]]], "paint": {"fill-color": "rgb(255,255,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "airport-taxiway:outline", "type": "line", "source-layer": "streets", "filter": ["==", ["get", "kind"], "taxiway"], "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 2, 15, 10, 16, 14, 18, 20, 20, 40]}, "layout": {"line-cap": "butt", "line-join": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "airport-runway:outline", "type": "line", "source-layer": "streets", "filter": ["==", ["get", "kind"], "runway"], "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 6, 13, 9, 14, 16, 15, 24, 16, 40, 17, 100, 18, 160, 20, 300]}, "layout": {"line-cap": "butt", "line-join": "round"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "airport-taxiway", "type": "line", "source-layer": "streets", "filter": ["==", ["get", "kind"], "taxiway"], "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1, 15, 8, 16, 12, 18, 18, 20, 36]}, "layout": {"line-cap": "butt", "line-join": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "airport-runway", "type": "line", "source-layer": "streets", "filter": ["==", ["get", "kind"], "runway"], "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 5, 13, 8, 14, 14, 15, 22, 16, 38, 17, 98, 18, 158, 20, 298], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "layout": {"line-cap": "butt", "line-join": "round"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "building:outline", "type": "fill", "source-layer": "buildings", "paint": {"fill-color": "rgb(223,219,215)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "building", "type": "fill", "source-layer": "buildings", "paint": {"fill-color": "rgb(242,234,226)", "fill-translate": [-2, -2], "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "slot-below-streets", "type": "background", "paint": {"background-opacity": 0}}, {"id": "tunnel-street-pedestrian-zone", "type": "fill", "source-layer": "street_polygons", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "pedestrian"]], "paint": {"fill-color": "rgb(255,255,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-way-footway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(239,231,241)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-steps:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(239,231,241)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-path:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(239,231,241)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-cycleway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(233,238,241)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-track:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 2, 16, 4, 18, 18, 19, 48, 20, 96], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-pedestrian:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(237,236,235)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-livingstreet:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-minor:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-bus:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(237,236,235)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-tertiary-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-arterial-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-trunk-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-motorway-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-tertiary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(229,228,226)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "tunnel-street-secondary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 2, 14, 5, 16, 8, 18, 30, 19, 68, 20, 138], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "tunnel-street-primary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "tunnel-street-trunk:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "tunnel-street-motorway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(243,209,180)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 2, 10, 5, 14, 5, 16, 14, 18, 38, 19, 84, 20, 168], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "tunnel-way-footway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(253,244,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-steps", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(253,244,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-path", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(253,244,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-way-cycleway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(246,252,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-track", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 16, 19, 44, 20, 88], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-pedestrian", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(253,244,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(251,251,251)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-livingstreet", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-minor", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-bus", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(251,251,251)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-pedestrian-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bicycle"], "designated"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(246,252,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-minor-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["living_street", "residential", "unclassified"]]], ["==", ["get", "bicycle"], "designated"], ["==", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(246,252,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-tertiary-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-arterial-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-trunk-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "tunnel-street-motorway-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,227,190)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "tunnel-street-tertiary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "tunnel-street-secondary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 1, 14, 4, 16, 6, 18, 28, 19, 64, 20, 130], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "tunnel-street-primary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "tunnel-street-trunk", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,246,208)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "tunnel-street-motorway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,227,190)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1, 10, 4, 14, 4, 16, 12, 18, 36, 19, 80, 20, 160], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-rail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 0.5]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-rail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-lightrail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 0.5]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-lightrail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-subway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(206,216,224)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 3, 16, 3, 18, 6, 19, 8, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 0.5]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-minorrail:outline", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["==", ["get", "tunnel"], true]]], "paint": {"line-color": "rgb(212,218,223)", "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 5, 18, 7, 20, 20], "line-dasharray": [0.1, 0.5], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-rail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(225,229,232)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.5]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-rail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(225,229,232)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-lightrail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(225,229,232)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.5]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-lightrail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(225,229,232)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10], "line-opacity": 0.5}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-subway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(221,228,233)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 2, 16, 2, 18, 5, 19, 6, 20, 8], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.5]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "tunnel-transport-minorrail", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["==", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["==", ["get", "tunnel"], true]]], "paint": {"line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 1, 17, 2, 18, 3, 20, 5], "line-color": "rgb(212,218,223)", "line-opacity": 0.5}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge", "type": "fill", "source-layer": "bridges", "paint": {"fill-color": "rgb(243,239,235)", "fill-antialias": true, "fill-opacity": 0.8}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-pedestrian-zone", "type": "fill", "source-layer": "street_polygons", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "pedestrian"]], "paint": {"fill-color": "rgb(251,235,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 0.25]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "way-footway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-steps:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-path:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-cycleway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(215,224,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-track:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 2, 16, 4, 18, 18, 19, 48, 20, 96], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-pedestrian:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(221,220,218)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-livingstreet:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-minor:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-bus:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(221,220,218)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-tertiary-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-arterial-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-trunk-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-motorway-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-tertiary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(207,205,202)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "street-secondary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 2, 14, 5, 16, 8, 18, 30, 19, 68, 20, 138], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "street-primary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "street-trunk:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "street-motorway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 2, 10, 5, 14, 5, 16, 14, 18, 38, 19, 84, 20, 168], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "way-footway", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-steps", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-path", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "way-cycleway", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "round"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-track", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 16, 19, 44, 20, 88], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-pedestrian", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(247,247,247)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-livingstreet", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-minor", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-bus", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(247,247,247)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-pedestrian-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bicycle"], "designated"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-minor-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["living_street", "residential", "unclassified"]]], ["==", ["get", "bicycle"], "designated"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-tertiary-link", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-arterial-link", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-trunk-link", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "street-motorway-link", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,204,136)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "street-tertiary", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "street-secondary", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 1, 14, 4, 16, 6, 18, 28, 19, 64, 20, 130], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "street-primary", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "street-trunk", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "street-motorway", "type": "line", "source-layer": "streets", "filter": ["all", ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "round"}, "paint": {"line-color": "rgb(255,204,136)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1, 10, 4, 14, 4, 16, 12, 18, 36, 19, 80, 20, 160], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "transport-rail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "transport-rail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-lightrail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "transport-lightrail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-subway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(166,184,199)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 3, 16, 3, 18, 6, 19, 8, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "transport-minorrail:outline", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 5, 18, 7, 20, 20], "line-dasharray": [0.1, 0.5]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "aerialway:outline", "type": "line", "source-layer": "aerialways", "filter": ["any", ["==", ["get", "kind"], "cable_car"], ["==", ["get", "kind"], "gondola"], ["==", ["get", "kind"], "goods"], ["==", ["get", "kind"], "chair_lift"], ["==", ["get", "kind"], "drag_lift"], ["==", ["get", "kind"], "t-bar"], ["==", ["get", "kind"], "j-bar"], ["==", ["get", "kind"], "platter"], ["==", ["get", "kind"], "rope-tow"]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["exponential", 1], ["zoom"], 11, 1, 19, 2.5]}, "minzoom": 13, "layout": {"line-cap": "round"}, "source": "versatiles-shortbread"}, {"id": "transport-rail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-rail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-lightrail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-lightrail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-subway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], "paint": {"line-color": "rgb(193,205,216)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 2, 16, 2, 18, 5, 19, 6, 20, 8], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "transport-minorrail", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["!=", ["get", "bridge"], true], ["!=", ["get", "tunnel"], true]]], "paint": {"line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 1, 17, 2, 18, 3, 20, 5], "line-color": "rgb(177,187,196)"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "aerialway", "type": "line", "source-layer": "aerialways", "filter": ["any", ["==", ["get", "kind"], "cable_car"], ["==", ["get", "kind"], "gondola"], ["==", ["get", "kind"], "goods"], ["==", ["get", "kind"], "chair_lift"], ["==", ["get", "kind"], "drag_lift"], ["==", ["get", "kind"], "t-bar"], ["==", ["get", "kind"], "j-bar"], ["==", ["get", "kind"], "platter"], ["==", ["get", "kind"], "rope-tow"]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["exponential", 1], ["zoom"], 11, 3, 19, 5.5], "line-dasharray": [2, 3]}, "minzoom": 13, "layout": {"line-cap": "round"}, "source": "versatiles-shortbread"}, {"id": "transport-ferry", "type": "line", "source-layer": "ferries", "minzoom": 10, "paint": {"line-color": "rgb(125,152,179)", "line-width": 1.1, "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1], "line-dasharray": [2, 2]}, "layout": {"line-join": "round"}, "source": "versatiles-shortbread"}, {"id": "bridge-way-footway:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "footway"]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 7, 18, 10, 19, 17, 20, 31]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-way-steps:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "steps"]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 7, 18, 10, 19, 17, 20, 31]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-way-paths:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["in", ["get", "kind"], ["literal", ["path", "cycleway"]]]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 7, 18, 10, 19, 17, 20, 31]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-street-track:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "bridge"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 3, 16, 6, 18, 25, 19, 67, 20, 134]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bridge"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 8, 18, 36, 19, 90, 20, 179]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-service:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "bridge"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 3, 16, 6, 18, 25, 19, 67, 20, 134]}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-street-minor:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["living_street", "residential", "unclassified"]]], ["==", ["get", "bridge"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 8, 18, 36, 19, 90, 20, 179]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary-link:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 8, 18, 36, 19, 90, 20, 179]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-arterial-link:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 10, 18, 20, 20, 56]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk-link:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 10, 18, 20, 20, 56]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway-link:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 10, 18, 20, 20, 56]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 12, 3, 14, 4, 16, 8, 18, 36, 19, 90, 20, 179]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-secondary:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1], "line-width": ["interpolate", ["linear"], ["zoom"], 11, 3, 14, 7, 16, 11, 18, 42, 19, 95, 20, 193]}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "bridge-street-primary:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1, 10, 6, 14, 8, 16, 17, 18, 50, 19, 104, 20, 202]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 3, 10, 6, 14, 8, 16, 17, 18, 50, 19, 104, 20, 202]}, "minzoom": 7, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway:bridge", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-cap": "butt", "line-join": "round"}, "paint": {"line-color": "rgb(243,239,235)", "line-opacity": 0.5, "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 3, 10, 7, 14, 7, 16, 20, 18, 53, 19, 118, 20, 235]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian-zone", "type": "fill", "source-layer": "street_polygons", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "pedestrian"]], "paint": {"fill-color": "rgb(255,255,255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-way-footway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-steps:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-path:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(226,212,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-cycleway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(215,224,230)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 5, 18, 7, 19, 12, 20, 22]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-track:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 2, 16, 4, 18, 18, 19, 48, 20, 96], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(221,220,218)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-livingstreet:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-minor:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-bus:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(221,220,218)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 12, 19, 32, 20, 48], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-arterial-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway-link:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 7, 18, 14, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(217,217,217)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 2, 14, 3, 16, 6, 18, 26, 19, 64, 20, 128], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "bridge-street-secondary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 2, 14, 5, 16, 8, 18, 30, 19, 68, 20, 138], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "bridge-street-primary:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 2, 10, 4, 14, 6, 16, 12, 18, 36, 19, 74, 20, 144], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(233,172,119)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 2, 10, 5, 14, 5, 16, 14, 18, 38, 19, 84, 20, 168], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "bridge-way-footway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "footway"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-steps", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "steps"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-path", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "path"]], "paint": {"line-color": "rgb(251,235,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-way-cycleway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "cycleway"]], "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 4, 18, 6, 19, 10, 20, 20]}, "layout": {"line-join": "round", "line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-track", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "track"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 3, 18, 16, 19, 44, 20, 88], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "service"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(247,247,247)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-livingstreet", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "living_street"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-minor", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["residential", "unclassified"]]], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-bus", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["busway", "bus_guideway"]]], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(247,247,247)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 1, 16, 2, 18, 10, 19, 28, 20, 40], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-pedestrian-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "pedestrian"], ["==", ["get", "bicycle"], "designated"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-minor-bicycle", "type": "line", "source-layer": "streets", "filter": ["all", ["in", ["get", "kind"], ["literal", ["living_street", "residential", "unclassified"]]], ["==", ["get", "bicycle"], "designated"], ["==", ["get", "bridge"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(239,249,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-arterial-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["in", ["get", "kind"], ["literal", ["secondary", "primary"]]], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 14, 1]}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway-link", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["==", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,204,136)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 12, 20, 38], "line-opacity": ["interpolate", ["linear"], ["zoom"], 12, 0, 13, 1]}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "bridge-street-tertiary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "tertiary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,255,255)", "line-width": ["interpolate", ["linear"], ["zoom"], 12, 1, 14, 2, 16, 5, 18, 24, 19, 60, 20, 120], "line-opacity": ["interpolate", ["linear"], ["zoom"], 10, 0, 11, 1]}, "minzoom": 10, "source": "versatiles-shortbread"}, {"id": "bridge-street-secondary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "secondary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 1, 14, 4, 16, 6, 18, 28, 19, 64, 20, 130], "line-opacity": ["interpolate", ["linear"], ["zoom"], 9, 0, 10, 1]}, "minzoom": 9, "source": "versatiles-shortbread"}, {"id": "bridge-street-primary", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "primary"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1]}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "bridge-street-trunk", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "trunk"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,238,170)", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1, 10, 3, 14, 5, 16, 10, 18, 34, 19, 70, 20, 140], "line-opacity": ["interpolate", ["linear"], ["zoom"], 6, 0, 7, 1]}, "minzoom": 6, "source": "versatiles-shortbread"}, {"id": "bridge-street-motorway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "bridge"], true], ["==", ["get", "kind"], "motorway"], ["!=", ["get", "link"], true]], "layout": {"line-join": "round", "line-cap": "butt"}, "paint": {"line-color": "rgb(255,204,136)", "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1, 10, 4, 14, 4, 16, 12, 18, 36, 19, 80, 20, 160], "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 1]}, "minzoom": 5, "source": "versatiles-shortbread"}, {"id": "bridge-transport-rail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "bridge-transport-rail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-lightrail:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 1, 13, 1, 15, 1, 20, 14], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "bridge-transport-lightrail-service:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 16, 1, 20, 14]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-subway:outline", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(166,184,199)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 3, 16, 3, 18, 6, 19, 8, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "bridge-transport-minorrail:outline", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["==", ["get", "bridge"], true]]], "paint": {"line-color": "rgb(177,187,196)", "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 5, 18, 7, 20, 20], "line-dasharray": [0.1, 0.5]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-rail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-rail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "rail"], ["has", "service"], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-lightrail", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1, 20, 10], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-lightrail-service", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "light_rail"], ["has", "service"], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(200,207,214)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1, 20, 10]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-subway", "type": "line", "source-layer": "streets", "filter": ["all", ["==", ["get", "kind"], "subway"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], "paint": {"line-color": "rgb(193,205,216)", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1, 15, 2, 16, 2, 18, 5, 19, 6, 20, 8], "line-opacity": ["interpolate", ["linear"], ["zoom"], 14, 0, 15, 1]}, "layout": {"line-cap": "butt"}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "bridge-transport-minorrail", "type": "line", "source-layer": "streets", "filter": ["any", ["all", ["==", ["get", "kind"], "narrow_gauge"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "tram"], ["!", ["has", "service"]], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "funicular"], ["==", ["get", "bridge"], true]], ["all", ["==", ["get", "kind"], "monorail"], ["==", ["get", "bridge"], true]]], "paint": {"line-width": ["interpolate", ["linear"], ["zoom"], 13, 0, 16, 1, 17, 2, 18, 3, 20, 5], "line-color": "rgb(177,187,196)"}, "layout": {"line-cap": "butt"}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "slot-below-symbols", "type": "background", "paint": {"background-opacity": 0}}, {"id": "boundary-country:outline", "type": "line", "source-layer": "boundaries", "filter": ["any", ["all", ["==", ["get", "admin_level"], 2], ["!=", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], ["all", ["==", ["get", "admin_level"], 2], ["==", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]]], "paint": {"line-color": "rgb(248,244,240)", "line-opacity": 0.75, "line-width": ["interpolate", ["linear"], ["zoom"], 0, 0, 3, 2, 10, 8]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 0, "source": "versatiles-shortbread"}, {"id": "boundary-state:outline", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 4], ["!=", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], "paint": {"line-color": "rgb(248,244,240)", "line-opacity": 0.75, "line-width": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 2, 10, 4]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 7, "source": "versatiles-shortbread"}, {"id": "boundary-country", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 2], ["!=", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], "paint": {"line-color": "rgb(166,166,200)", "line-width": ["interpolate", ["linear"], ["zoom"], 0, 0, 3, 1, 10, 4]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 0, "source": "versatiles-shortbread"}, {"id": "boundary-country-disputed", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 2], ["==", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], "paint": {"line-color": "rgb(190,188,207)", "line-width": ["interpolate", ["linear"], ["zoom"], 0, 0, 3, 1, 10, 4], "line-dasharray": [2, 1]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 0, "source": "versatiles-shortbread"}, {"id": "boundary-state", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 4], ["!=", ["get", "disputed"], true], ["!=", ["get", "maritime"], true]], "paint": {"line-color": "rgb(166,166,200)", "line-width": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 1, 10, 2], "line-opacity": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 1]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 7, "source": "versatiles-shortbread"}, {"id": "boundary-country-maritime", "type": "line", "source-layer": "boundaries", "filter": ["all", ["==", ["get", "admin_level"], 2], ["==", ["get", "maritime"], true], ["!=", ["get", "disputed"], true]], "paint": {"line-color": "rgb(185,210,235)", "line-width": ["interpolate", ["linear"], ["zoom"], 0, 0, 3, 1, 10, 4], "line-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1]}, "layout": {"line-cap": "round", "line-join": "round"}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "label-address-housenumber", "type": "symbol", "source-layer": "addresses", "filter": ["has", "housenumber"], "layout": {"text-field": ["case", ["has", "unit"], ["concat", ["get", "housenumber"], "/", ["get", "unit"]], ["get", "housenumber"]], "symbol-placement": "point", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 17, 8, 19, 10], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgba(15,11,7,0.302)", "text-color": "rgba(15,11,7,0.302)"}, "minzoom": 17, "source": "versatiles-shortbread"}, {"id": "marking-oneway", "type": "symbol", "source-layer": "streets", "filter": ["all", ["==", ["get", "oneway"], true], ["in", ["get", "kind"], ["literal", ["trunk", "primary", "secondary", "tertiary", "unclassified", "residential", "living_street"]]]], "layout": {"symbol-placement": "line", "symbol-spacing": 175, "icon-rotate": 90, "icon-rotation-alignment": "map", "icon-padding": 5, "symbol-avoid-edges": true, "icon-image": "base:marking-oneway"}, "minzoom": 14, "paint": {"icon-color": "rgb(0,0,0)", "text-color": "rgb(0,0,0)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4, 20, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4, 20, 0.4]}, "source": "versatiles-shortbread"}, {"id": "marking-oneway-reverse", "type": "symbol", "source-layer": "streets", "filter": ["all", ["==", ["get", "oneway_reverse"], true], ["in", ["get", "kind"], ["literal", ["trunk", "primary", "secondary", "tertiary", "unclassified", "residential", "living_street"]]]], "layout": {"symbol-placement": "line", "symbol-spacing": 75, "icon-rotate": -90, "icon-rotation-alignment": "map", "icon-padding": 5, "symbol-avoid-edges": true, "icon-image": "base:marking-oneway"}, "minzoom": 14, "paint": {"icon-color": "rgb(0,0,0)", "text-color": "rgb(0,0,0)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4, 20, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4, 20, 0.4]}, "source": "versatiles-shortbread"}, {"id": "poi-amenity", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "amenity"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "amenity"], "arts_centre", "base:icon-art_gallery", "clinic", "base:icon-doctor", "courthouse", "base:icon-justice", "food_court", "base:icon-restaurant", "public_building", "base:icon-town_hall", "university", "base:icon-college", "atm", "base:icon-atm", "bank", "base:icon-bank", "bar", "base:icon-bar", "bench", "base:icon-bench", "bicycle_rental", "base:icon-bicycle_share", "biergarten", "base:icon-beer_mug", "cafe", "base:icon-cafe", "car_rental", "base:icon-car_rental", "car_sharing", "base:icon-car_rental", "car_wash", "base:icon-car_wash", "cinema", "base:icon-cinema", "college", "base:icon-college", "community_centre", "base:icon-community", "dentist", "base:icon-dentist", "doctors", "base:icon-doctor", "drinking_water", "base:icon-drinking_water", "embassy", "base:icon-embassy", "fast_food", "base:icon-fast_food", "fire_station", "base:icon-fire_station", "fountain", "base:icon-fountain", "fuel", "base:icon-fuel_pump", "grave_yard", "base:icon-cemetery", "hospital", "base:icon-hospital", "hunting_stand", "base:icon-hunting_stand", "library", "base:icon-library", "marketplace", "base:icon-marketplace", "nightclub", "base:icon-nightclub", "nursing_home", "base:icon-nursing_home", "pharmacy", "base:icon-pill", "place_of_worship", ["match", ["get", "religion"], "christian", "base:icon-latin_cross", "muslim", "base:icon-star_and_crescent", "jewish", "base:icon-star_of_david", "buddhist", "base:icon-dharma_wheel", "hindu", "base:icon-om", "sikh", "base:icon-khanda", "taoist", "base:icon-yin_yang", "base:icon-person_kneeling_and_praying"], "police", "base:icon-police_officer", "post_box", "base:icon-postbox", "post_office", "base:icon-post", "prison", "base:icon-prison", "pub", "base:icon-pint_glass", "recycling", "base:icon-recycling", "restaurant", "base:icon-restaurant", "school", "base:icon-school", "shelter", "base:icon-shelter", "telephone", "base:icon-telephone", "theatre", "base:icon-theater", "toilets", "base:icon-restrooms", "townhall", "base:icon-town_hall", "vending_machine", "base:icon-vending_machine", "veterinary", "base:icon-veterinary", "waste_basket", "base:icon-waste_basket", "base:transport-information"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-leisure", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "leisure"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "leisure"], "dog_park", "base:icon-dog", "golf_course", "base:icon-golf", "ice_rink", "base:icon-ice_rink", "pitch", "base:icon-pitch", "playground", "base:icon-seesaw", "stadium", "base:icon-stadium", "swimming_pool", "base:icon-swimming", "water_park", "base:icon-water_park", "base:icon-sports"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-tourism", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "tourism"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "tourism"], "artwork", "base:icon-artwork", "alpine_hut", "base:icon-chalet", "bed_and_breakfast", "base:icon-lodging", "camp_site", "base:icon-campsite", "caravan_site", "base:icon-caravan", "guest_house", "base:icon-lodging", "hostel", "base:icon-lodging", "hotel", "base:icon-lodging", "motel", "base:icon-lodging", "theme_park", "base:icon-amusement_park", "chalet", "base:icon-chalet", "information", "base:transport-information", "picnic_site", "base:icon-picnic_site", "viewpoint", "base:icon-viewpoint", "zoo", "base:icon-zoo", "base:transport-information"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-shop", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "shop"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "shop"], "alcohol", "base:icon-alcohol_shop", "bakery", "base:icon-bakery", "beauty", "base:icon-beauty", "beverages", "base:icon-beverages", "books", "base:icon-books", "butcher", "base:icon-butcher", "chemist", "base:icon-tube_and_toothbrush", "clothes", "base:icon-clothes", "doityourself", "base:icon-do_it_yourself", "dry_cleaning", "base:icon-dry_cleaning", "florist", "base:icon-florist", "furniture", "base:icon-furniture", "garden_centre", "base:icon-garden_center", "general", "base:icon-shop", "gift", "base:icon-gift", "greengrocer", "base:icon-greengrocer", "hairdresser", "base:icon-scissors_and_comb", "hardware", "base:icon-hardware", "jewelry", "base:icon-ring", "kiosk", "base:icon-newspaper", "laundry", "base:icon-laundry", "newsagent", "base:icon-newsagent", "optician", "base:icon-optician", "outdoor", "base:icon-outdoor", "shoes", "base:icon-shoes", "sports", "base:icon-sports", "stationery", "base:icon-stationery", "toys", "base:icon-rocking_horse", "travel_agency", "base:icon-travel_agent", "video", "base:icon-video", "base:icon-shop"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-man_made", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "man_made"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "man_made"], "lighthouse", "base:icon-lighthouse", "wastewater_plant", "base:icon-wastewater", "water_well", "base:icon-drinking_water", "water_works", "base:icon-waterworks", "surveillance", "base:icon-surveillance", "tower", "base:icon-observation_tower", "watermill", "base:icon-watermill", "windmill", "base:icon-windmill", "base:transport-information"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-historic", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "historic"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "historic"], "castle", "base:icon-castle", "monument", "base:icon-monument", "wayside_shrine", "base:icon-shrine", "base:icon-historic"], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-emergency", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "emergency"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "emergency"], "defibrillator", "base:icon-defibrillator", "fire_hydrant", "base:icon-hydrant", "phone", "base:icon-emergency_phone", ""], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-highway", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "highway"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "highway"], "emergency_access_point", "base:icon-emergency_access", ""], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "poi-office", "type": "symbol", "source-layer": "pois", "filter": ["to-boolean", ["get", "office"]], "minzoom": 14, "layout": {"icon-size": ["interpolate", ["exponential", 2], ["zoom"], 16, 0.4, 20, 1.2], "text-field": ["get", "name"], "text-size": ["interpolate", ["linear"], ["zoom"], 17, 0, 18, 11, 22, 13], "text-anchor": "top", "text-offset": [0, 1.2], "text-optional": true, "symbol-placement": "point", "icon-optional": true, "icon-image": ["match", ["get", "office"], "diplomatic", "base:icon-embassy", ""], "text-font": ["noto_sans_bold"]}, "paint": {"icon-opacity": ["interpolate", ["linear"], ["zoom"], 16, 0, 17, 0.4], "text-opacity": ["interpolate", ["linear"], ["zoom"], 18, 0, 18.5, 0.4], "icon-color": "rgb(102,102,102)", "text-color": "rgb(102,102,102)", "text-halo-color": "rgb(255,255,255)", "text-halo-width": 0.5, "text-halo-blur": 0.5}, "source": "versatiles-shortbread"}, {"id": "slot-below-labels", "type": "background", "paint": {"background-opacity": 0}}, {"id": "label-motorway-exit", "type": "symbol", "source-layer": "street_labels_points", "filter": ["==", ["get", "kind"], "motorway_junction"], "layout": {"text-field": "{ref}", "symbol-placement": "point", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 9, 18, 11], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 1, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-motorway-shield", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "motorway"], "layout": {"text-field": "{ref}", "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 10, 18, 12, 20, 16], "text-font": ["noto_sans_bold"]}, "paint": {"icon-color": "rgb(255,255,255)", "text-color": "rgb(255,255,255)", "text-halo-color": "rgb(255,204,136)", "text-halo-width": 0.1, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-street-track", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "track"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-pedestrian", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "pedestrian"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-livingstreet", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "living_street"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-residential", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "residential"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-unclassified", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "unclassified"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-tertiary", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "tertiary"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-secondary", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "secondary"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-primary", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "primary"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-trunk", "type": "symbol", "source-layer": "street_labels", "filter": ["==", ["get", "kind"], "trunk"], "layout": {"text-field": ["get", "name"], "symbol-placement": "line", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-street-pedestrian-zone", "type": "symbol", "source-layer": "streets_polygons_labels", "filter": ["==", ["get", "kind"], "pedestrian"], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "text-anchor": "center", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 10, 17, 12], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-water-area-major", "type": "symbol", "source-layer": "water_polygons_labels", "filter": ["all", ["!=", ["get", "kind"], "glacier"], [">", ["get", "way_area"], 1000000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "point", "text-size": ["interpolate", ["linear"], ["zoom"], 4, 11, 10, 14], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1], "text-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0, 5, 1], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 4, "source": "versatiles-shortbread"}, {"id": "label-water-area-large", "type": "symbol", "source-layer": "water_polygons_labels", "filter": ["all", ["!=", ["get", "kind"], "glacier"], [">", ["get", "way_area"], 10000000], ["<=", ["get", "way_area"], 1000000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "point", "text-size": ["interpolate", ["linear"], ["zoom"], 8, 10, 12, 13], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1], "text-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 9, 1], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 8, "source": "versatiles-shortbread"}, {"id": "label-water-area-medium", "type": "symbol", "source-layer": "water_polygons_labels", "filter": ["all", ["!=", ["get", "kind"], "glacier"], [">", ["get", "way_area"], 100000], ["<=", ["get", "way_area"], 10000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "point", "text-size": ["interpolate", ["linear"], ["zoom"], 11, 10, 14, 12], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1], "text-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 12, 1], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 11, "source": "versatiles-shortbread"}, {"id": "label-water-area-small", "type": "symbol", "source-layer": "water_polygons_labels", "filter": ["all", ["!=", ["get", "kind"], "glacier"], [">", ["get", "way_area"], 0], ["<=", ["get", "way_area"], 100000]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "point", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 10, 17, 12], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1], "text-opacity": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-water-river", "type": "symbol", "source-layer": "water_lines_labels", "filter": ["in", ["get", "kind"], ["literal", ["river", "canal"]]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "line", "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 15, 12], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-water-stream", "type": "symbol", "source-layer": "water_lines_labels", "filter": ["in", ["get", "kind"], ["literal", ["stream", "ditch"]]], "layout": {"text-field": ["get", "name"], "text-anchor": "center", "symbol-placement": "line", "text-size": ["interpolate", ["linear"], ["zoom"], 14, 9, 17, 11], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(78,91,104)", "text-color": "rgb(78,91,104)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 14, "source": "versatiles-shortbread"}, {"id": "symbol-transit-bus", "type": "symbol", "source-layer": "public_transport", "filter": ["==", ["get", "kind"], "bus_stop"], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:icon-bus", "icon-size": ["interpolate", ["linear"], ["zoom"], 16, 0.5, 18, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 16, "source": "versatiles-shortbread"}, {"id": "symbol-transit-tram", "type": "symbol", "source-layer": "public_transport", "filter": ["==", ["get", "kind"], "tram_stop"], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:transport-tram", "icon-size": ["interpolate", ["linear"], ["zoom"], 15, 0.5, 17, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 15, "source": "versatiles-shortbread"}, {"id": "symbol-transit-station", "type": "symbol", "source-layer": "public_transport", "filter": ["in", ["get", "kind"], ["literal", ["station", "halt"]]], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:icon-rail", "icon-size": ["interpolate", ["linear"], ["zoom"], 13, 0.5, 15, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "symbol-transit-airfield", "type": "symbol", "source-layer": "public_transport", "filter": ["all", ["==", ["get", "kind"], "aerodrome"], ["!", ["has", "iata"]]], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:icon-airfield", "icon-size": ["interpolate", ["linear"], ["zoom"], 13, 0.5, 15, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 13, "source": "versatiles-shortbread"}, {"id": "symbol-transit-airport", "type": "symbol", "source-layer": "public_transport", "filter": ["all", ["==", ["get", "kind"], "aerodrome"], ["has", "iata"]], "layout": {"text-field": ["get", "name"], "symbol-placement": "point", "icon-keep-upright": true, "text-size": 10, "icon-anchor": "bottom", "text-anchor": "top", "icon-image": "base:icon-airport", "icon-size": ["interpolate", ["linear"], ["zoom"], 12, 0.5, 14, 1], "text-font": ["noto_sans_regular"]}, "paint": {"icon-opacity": 0.7, "icon-color": "rgb(102,98,106)", "text-color": "rgb(102,98,106)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-place-neighbourhood", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "neighbourhood"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": 12, "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 17, 1, 18, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 17, 1, 18, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 14, "maxzoom": 18, "source": "versatiles-shortbread"}, {"id": "label-place-quarter", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "quarter"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": 13, "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 15, 1, 16, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 15, 1, 16, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 13, "maxzoom": 16, "source": "versatiles-shortbread"}, {"id": "label-place-suburb", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "suburb"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 11, 11, 13, 14], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 14, 1, 15, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 14, 1, 15, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 10, "maxzoom": 15, "source": "versatiles-shortbread"}, {"id": "label-place-hamlet", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "hamlet"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 10, 11, 12, 14], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 17, 1, 18, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 17, 1, 18, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 13, "maxzoom": 18, "source": "versatiles-shortbread"}, {"id": "label-place-village", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "village"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 9, 11, 12, 14], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 15, 1, 16, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 15, 1, 16, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 10, "maxzoom": 16, "source": "versatiles-shortbread"}, {"id": "label-place-town", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "town"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 8, 11, 12, 14], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 14, 1, 15, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 14, 1, 15, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 7, "maxzoom": 15, "source": "versatiles-shortbread"}, {"id": "label-boundary-state", "type": "symbol", "source-layer": "boundary_labels", "filter": ["in", ["get", "admin_level"], ["literal", [4, "4"]]], "layout": {"text-field": ["get", "name"], "text-anchor": "top", "text-offset": [0, 0.2], "text-padding": 0, "text-optional": true, "text-size": ["interpolate", ["linear"], ["zoom"], 5, 8, 8, 12], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(61,61,77)", "text-color": "rgb(61,61,77)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 3, "maxzoom": 10, "source": "versatiles-shortbread"}, {"id": "label-place-city", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "city"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 7, 11, 10, 14], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 13, 1, 14, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 13, 1, 14, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 6, "maxzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-place-statecapital", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "state_capital"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 6, 11, 10, 15], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 13, 1, 14, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 13, 1, 14, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 4, "maxzoom": 14, "source": "versatiles-shortbread"}, {"id": "label-place-capital", "type": "symbol", "source-layer": "place_labels", "filter": ["==", ["get", "kind"], "capital"], "layout": {"text-field": ["get", "name"], "symbol-sort-key": ["-", ["to-number", ["get", "population"], 0]], "text-size": ["interpolate", ["linear"], ["zoom"], 5, 12, 10, 16], "text-font": ["noto_sans_regular"]}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "icon-opacity": ["interpolate", ["linear"], ["zoom"], 11, 1, 12, 0], "text-opacity": ["interpolate", ["linear"], ["zoom"], 11, 1, 12, 0], "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 4, "maxzoom": 12, "source": "versatiles-shortbread"}, {"id": "label-boundary-country-small", "type": "symbol", "source-layer": "boundary_labels", "filter": ["all", ["in", ["get", "admin_level"], ["literal", [2, "2"]]], ["<=", ["get", "way_area"], 10000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "top", "text-offset": [0, 0.2], "text-padding": 0, "text-optional": true, "text-size": ["interpolate", ["linear"], ["zoom"], 4, 8, 5, 11], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 4, "maxzoom": 10, "source": "versatiles-shortbread"}, {"id": "label-boundary-country-medium", "type": "symbol", "source-layer": "boundary_labels", "filter": ["all", ["in", ["get", "admin_level"], ["literal", [2, "2"]]], ["<", ["get", "way_area"], 90000000], [">", ["get", "way_area"], 10000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "top", "text-offset": [0, 0.2], "text-padding": 0, "text-optional": true, "text-size": ["interpolate", ["linear"], ["zoom"], 3, 8, 5, 12], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 2, "maxzoom": 10, "source": "versatiles-shortbread"}, {"id": "label-boundary-country-large", "type": "symbol", "source-layer": "boundary_labels", "filter": ["all", ["in", ["get", "admin_level"], ["literal", [2, "2"]]], [">=", ["get", "way_area"], 90000000]], "layout": {"text-field": ["get", "name"], "text-anchor": "top", "text-offset": [0, 0.2], "text-padding": 0, "text-optional": true, "text-size": ["interpolate", ["linear"], ["zoom"], 2, 8, 5, 13], "text-font": ["noto_sans_regular"], "text-transform": "uppercase"}, "paint": {"icon-color": "rgb(51,51,68)", "text-color": "rgb(51,51,68)", "text-halo-color": "rgba(255,255,255,0.8)", "text-halo-width": 2, "text-halo-blur": 1}, "minzoom": 2, "maxzoom": 9, "source": "versatiles-shortbread"}], "sky": {"sky-color": "rgb(191,217,242)", "horizon-color": "rgb(255,255,255)", "fog-color": "rgb(255,255,255)", "sky-horizon-blend": 0.8, "horizon-fog-blend": 0.8, "fog-ground-blend": 0.5, "atmosphere-blend": 0}, "projection": {"type": "globe"}} \ No newline at end of file diff --git a/android-vectortile/src/androidTest/assets/stencil-experiment/8-226-100.mvt b/android-vectortile/src/androidTest/assets/stencil-experiment/8-226-100.mvt new file mode 100644 index 000000000..c6e9a8369 Binary files /dev/null and b/android-vectortile/src/androidTest/assets/stencil-experiment/8-226-100.mvt differ diff --git a/android-vectortile/src/androidTest/assets/stencil-experiment/README.md b/android-vectortile/src/androidTest/assets/stencil-experiment/README.md new file mode 100644 index 000000000..8e9282e02 --- /dev/null +++ b/android-vectortile/src/androidTest/assets/stencil-experiment/README.md @@ -0,0 +1,75 @@ +# Pixel 5a GPU stencil experiment + +This reproduces the expensive forest in Shortbread 8/226/100. These are +instrumentation fixtures; they are not shipped in the SDK or example app. +No production renderer is switched by this experiment. + +Data: https://vector.openstreetmap.org/shortbread_v1/8/226/100.mvt +Captured from the Pixel source-tile cache on 2026-10-07. +© OpenStreetMap contributors: https://www.openstreetmap.org/copyright + +Style: https://tiles.versatiles.org/assets/styles/colorful/style.json +Only land-forest is retained; sources are rewritten as in VectorTileStyleLoader. + +## Files + +- 8-226-100.mvt: actual cached, decompressed tile. +- style.json: forest-only comparison style. +- forest-rings.bin.gzip: gzip of LE u32 extent, four float32 colour channels, + u32 ring count, then each ring's u32 vertex count and float32 xy pairs. +- forest-earcut.bin.gzip: gzip of float32-LE triangle vertices: x,y,r,g,b,a. + +There is one forest feature with 9,911 rings and 87,787 vertices. +Earcut produces 85,126 triangles; simple fans produce 67,965 triangles. +The device's native triangle output is checked against this reference. + +## Running + +From android-sdk with the Pixel connected: + + ./gradlew :android-vectortile:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.mapconductor.vectortile.GpuStencilExperimentTest + +The baseline takes tens of seconds. To preserve PNGs, run the test APK directly +(Gradle uninstalls its temporary test app): + + adb install -r android-vectortile/build/outputs/apk/androidTest/debug/android-vectortile-debug-androidTest.apk + adb shell am instrument -w -e class com.mapconductor.vectortile.GpuStencilExperimentTest com.mapconductor.vectortile.test/androidx.test.runner.AndroidJUnitRunner + adb pull /sdcard/Android/data/com.mapconductor.vectortile.test/files/stencil-experiment + +Add -e skipBaseline true to repeat the GPU measurements without slow native +triangle generation/reference validation. + +## Method and limitations + +The baseline measures the actual Android JNI decode + earcut on the original +MVT. Both images are GPU-rendered at 512x512 with 4x MSAA. No CPU rasterisation. + +The candidate packs simple fans linearly, draws them with colour writes off and +GL_INVERT into a one-bit stencil mask, then colours a covering rectangle. +All rings of this feature contribute to the same even-odd mask. +A D24S8 attachment adds approximately 4 MiB at this size/sample count. + +Seven interleaved reference/candidate GPU timings include upload, completion, +MSAA resolve and readback. glFinish runs before each sample. PNG saving is +outside these timings. + +Candidate preparation includes fixture read/decompression and fan packing. +Its rings are decoded offline, so it excludes MVT decode, production style/filter +processing and JNI transfer. These are stage comparisons, not full-app speedups. + +Four translated 256x256 quadrants are joined and must exactly match the single +512x512 stencil image, including coverage along tile boundaries. + +138 pixels differ in alpha from earcut (0.053%); mean absolute alpha difference +is 0.052 on a 0..255 scale. Some differences are fully opaque. They must not all +be described as antialiasing differences. The output is not pixel-identical. + +Adoption requires winding/overlapping-ring rules, separate features, style order, +paint variation, other sizes, ES2/driver support and pipeline integration tests. + +## Regenerating + +The native export_stencil_experiment example accepts a directory containing +the full example style.json and 8-226-100.mvt, and emits rings and triangles. +Compress the .bin files with gzip to .bin.gzip before copying them here. +The .gzip suffix avoids Android asset-merger special handling of .gz files. diff --git a/android-vectortile/src/androidTest/assets/stencil-experiment/forest-earcut.bin.gzip b/android-vectortile/src/androidTest/assets/stencil-experiment/forest-earcut.bin.gzip new file mode 100644 index 000000000..58b215402 Binary files /dev/null and b/android-vectortile/src/androidTest/assets/stencil-experiment/forest-earcut.bin.gzip differ diff --git a/android-vectortile/src/androidTest/assets/stencil-experiment/forest-rings.bin.gzip b/android-vectortile/src/androidTest/assets/stencil-experiment/forest-rings.bin.gzip new file mode 100644 index 000000000..71f921291 Binary files /dev/null and b/android-vectortile/src/androidTest/assets/stencil-experiment/forest-rings.bin.gzip differ diff --git a/android-vectortile/src/androidTest/assets/stencil-experiment/style.json b/android-vectortile/src/androidTest/assets/stencil-experiment/style.json new file mode 100644 index 000000000..09656e49c --- /dev/null +++ b/android-vectortile/src/androidTest/assets/stencil-experiment/style.json @@ -0,0 +1 @@ +{"version": 8, "name": "versatiles-colorful", "metadata": {"license": "https://creativecommons.org/publicdomain/zero/1.0/"}, "glyphs": "https://tiles.versatiles.org/assets/glyphs/{fontstack}/{range}.pbf", "sprite": [{"id": "base", "url": "https://tiles.versatiles.org/assets/sprites/base"}], "sources": {"versatiles-shortbread": {"type": "vector", "tiles": ["https://vector.openstreetmap.org/shortbread_v1/{z}/{x}/{y}.mvt"], "minzoom": 0, "maxzoom": 14}}, "layers": [{"id": "land-forest", "type": "fill", "source-layer": "land", "filter": ["in", ["get", "kind"], ["literal", ["forest"]]], "paint": {"fill-color": "rgb(203,229,184)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 1]}, "minzoom": 7, "source": "versatiles-shortbread"}], "sky": {"sky-color": "rgb(191,217,242)", "horizon-color": "rgb(255,255,255)", "fog-color": "rgb(255,255,255)", "sky-horizon-blend": 0.8, "horizon-fog-blend": 0.8, "fog-ground-blend": 0.5, "atmosphere-blend": 0}, "projection": {"type": "globe"}} \ No newline at end of file diff --git a/android-vectortile/src/androidTest/assets/tile-0-0-0.pbf b/android-vectortile/src/androidTest/assets/tile-0-0-0.pbf new file mode 100644 index 000000000..b8436405d Binary files /dev/null and b/android-vectortile/src/androidTest/assets/tile-0-0-0.pbf differ diff --git a/android-vectortile/src/androidTest/assets/tokyo-trees.bin b/android-vectortile/src/androidTest/assets/tokyo-trees.bin new file mode 100644 index 000000000..3448c1cb7 Binary files /dev/null and b/android-vectortile/src/androidTest/assets/tokyo-trees.bin differ diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/AttributionTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/AttributionTest.kt new file mode 100644 index 000000000..9f1c18ea5 --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/AttributionTest.kt @@ -0,0 +1,135 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.AttributionRule +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.resolveMapAttributions +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.raster.TileScheme +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * A style is data under someone's licence, and the credit has to survive the + * whole way: style JSON -> Rust -> JNI -> provider -> raster layer -> the map's + * attribution overlay. + * + * Worth a test of its own because this is the one thing about the layer that + * can be wrong while nothing looks wrong. The tiles draw perfectly whether or + * not anyone is credited for the data in them. + */ +@RunWith(AndroidJUnit4::class) +class AttributionTest { + private val osm = + "© OpenStreetMap contributors" + + private fun styleWith(sources: String) = + """ + { + "version": 8, + "sources": { $sources }, + "layers": [ + { "id": "bg", "type": "background", "paint": { "background-color": "#eee" } }, + { "id": "w", "type": "fill", "source": "osm", "source-layer": "water" } + ] + } + """.trimIndent() + + private fun vectorSource( + id: String, + attribution: String?, + ) = """ + "$id": { + "type": "vector", + "tiles": ["https://example.com/$id/{z}/{x}/{y}.pbf"], + "minzoom": 0, "maxzoom": 14 + ${attribution?.let { ""","attribution": "${it.replace("\"", "\\\"")}"""" } ?: ""} + } + """ + + private fun provider(styleJson: String) = + VectorTileProvider.create( + styleJson = styleJson, + tileSize = 512, + fetchTile = { ByteArray(0) }, + ) + + /** The credit reaches Kotlin with its HTML intact — it is a licence link. */ + @Test + fun carriesTheCreditOutOfTheStyle() { + provider(styleWith(vectorSource("osm", osm))).use { + assertEquals(listOf(osm), it.attributions()) + } + } + + /** A style whose sources ask for nothing must not invent a credit. */ + @Test + fun inventsNothingWhenTheStyleAsksForNothing() { + provider(styleWith(vectorSource("osm", null))).use { + assertTrue(it.attributions().toString(), it.attributions().isEmpty()) + } + } + + /** A source that no drawn layer references is not this map's to credit. */ + @Test + fun skipsASourceNothingDraws() { + val sources = vectorSource("osm", osm) + "," + vectorSource("unused", "© Nobody") + provider(styleWith(sources)).use { + assertEquals(listOf(osm), it.attributions()) + } + } + + /** The bundled demo style declares none, so the layer shows none. */ + @Test + fun theDemoStyleAsksForNothing() { + val assets = InstrumentationRegistry.getInstrumentation().context.assets + val demo = assets.open("demo-style.json").use { it.readBytes().decodeToString() } + provider(demo).use { + assertTrue(it.attributions().isEmpty()) + } + } + + /** + * The contract [VectorTileLayer] relies on: rules attached to the raster + * source are what the map's overlay reads. Both halves of the layer carry + * the same credit, and it must be printed once, not twice. + */ + @Test + fun theMapOverlayReadsWhatTheLayerAttaches() { + fun layer( + id: String, + rules: List, + ) = RasterLayerState( + id = id, + source = + RasterLayerSource.UrlTemplate( + template = "http://127.0.0.1:8080/$id/{z}/{x}/{y}.png", + tileSize = 512, + maxZoom = 22, + attributionRules = rules, + scheme = TileScheme.XYZ, + ), + ) + + val rules = listOf(AttributionRule(attribution = osm)) + val resolved = + resolveMapAttributions( + designRules = emptyList(), + rasterLayers = listOf(layer("geom", rules), layer("labels", rules)), + camera = + MapCameraPosition( + position = GeoPoint.fromLatLong(35.68, 139.76), + zoom = 16.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ), + ) + assertEquals(listOf(osm), resolved) + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GeometryNeighbourTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GeometryNeighbourTest.kt new file mode 100644 index 000000000..12bacf739 --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GeometryNeighbourTest.kt @@ -0,0 +1,75 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.tileserver.TileRequest +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.util.Collections + +@RunWith(AndroidJUnit4::class) +class GeometryNeighbourTest { + @Test + fun geometrySkipsNeighboursWithoutChangingPixelsOrLabelFetches() { + val assets = InstrumentationRegistry.getInstrumentation().context.assets + // Keep symbol layers (and therefore the neighbour plan), but do not + // fetch fonts: FULL then has the same pixels as GEOMETRY. + val style = JSONObject(assets.open("demo-style.json").bufferedReader().use { it.readText() }) + style.remove("glyphs") + val bytes = assets.open("tile-0-0-0.pbf").use { it.readBytes() } + for (mode in listOf(VectorTileProvider.RenderMode.CPU, VectorTileProvider.RenderMode.GPU)) { + for (request in listOf( + TileRequest(z = 4, x = 8, y = 6), + TileRequest(z = 14, x = 8000, y = 6000), + TileRequest(z = 2, x = 0, y = 1), + )) { + val fetched = Collections.synchronizedSet(HashSet()) + val plan = + VectorTileRenderer.create(style.toString(), VectorTileProvider.DEFAULT_TILE_SIZE).use { + JSONArray(it.plan(request.z, request.x, request.y)) + } + val entries = (0 until plan.length()).map { plan.getJSONObject(it) } + val central = entries.filter { !it.getBoolean("labelsOnly") }.map { it.getString("url") }.toSet() + val all = entries.map { it.getString("url") }.toSet() + if (request.z > 6) { + assertEquals("overzoom already uses only the parent", central, all) + } else { + assertTrue("fixture must include neighbours", all.size > central.size) + } + VectorTileProvider + .create( + styleJson = style.toString(), + renderMode = mode, + fetchTile = { url -> + fetched.add(url) + bytes + }, + ).use { provider -> + assertEquals(mode, provider.renderMode) + val geometry = provider.geometryTiles.renderTile(request) + assertNotNull(geometry) + assertEquals("geometry fetched label-only neighbours", central, fetched.toSet()) + // The independently served label route must still fetch + // the full ring, even after geometry filled its cache. + assertNotNull(provider.labelTiles.renderTile(request)) + assertEquals(all, fetched.toSet()) + assertArrayEquals( + "dropping neighbours changed geometry", + provider.renderTile(request), + geometry, + ) + if (mode == VectorTileProvider.RenderMode.GPU) { + assertEquals(2L, provider.gpuRenders) + assertEquals(0L, provider.gpuFallbacks) + } + } + } + } + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GpuRenderModeTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GpuRenderModeTest.kt new file mode 100644 index 000000000..8ee2ef5c6 --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GpuRenderModeTest.kt @@ -0,0 +1,279 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.tileserver.TileRequest +import com.mapconductor.core.tileserver.TileServerRegistry +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.net.HttpURLConnection +import java.net.URL +import java.util.concurrent.Callable +import java.util.concurrent.Executors +import android.graphics.Bitmap +import android.graphics.BitmapFactory + +/** + * Covers the GPU rendering mode as a *module* feature rather than an + * experiment: that it survives the tile server's thread pool, that it agrees + * with the CPU renderer, and that asking for it never costs a tile. + */ +@RunWith(AndroidJUnit4::class) +class GpuRenderModeTest { + private lateinit var styleJson: String + private lateinit var tileBytes: ByteArray + private val routeId = "vectortile-gpu-test" + private val providers = mutableListOf() + + @Before + fun setUp() { + val assets = InstrumentationRegistry.getInstrumentation().context.assets + styleJson = assets.open("demo-style.json").use { it.readBytes().decodeToString() } + tileBytes = assets.open("tile-0-0-0.pbf").use { it.readBytes() } + } + + @After + fun tearDown() { + TileServerRegistry.get().unregister(routeId) + providers.forEach { it.close() } + } + + private fun provider( + mode: VectorTileProvider.RenderMode, + tileSize: Int = 512, + ) = VectorTileProvider + .create( + styleJson = styleJson, + tileSize = tileSize, + renderMode = mode, + fetchTile = { tileBytes }, + ).also { providers.add(it) } + + private fun decode(png: ByteArray): Bitmap = BitmapFactory.decodeByteArray(png, 0, png.size)!! + + @Test + fun gpuModeIsAvailableAndReportsItself() { + val subject = provider(VectorTileProvider.RenderMode.GPU) + assertEquals(VectorTileProvider.RenderMode.GPU, subject.renderMode) + // e.g. "ES3 MSAA x4" + assertTrue( + "unexpected description: ${subject.rendererDescription()}", + subject.rendererDescription().startsWith("ES"), + ) + } + + @Test + fun cpuModeNeverProbesTheGpu() { + val subject = provider(VectorTileProvider.RenderMode.CPU) + assertEquals(VectorTileProvider.RenderMode.CPU, subject.renderMode) + assertEquals("cpu", subject.rendererDescription()) + } + + @Test + fun gpuModeActuallyDrawsOnTheGpu() { + // The guard the first version of this suite lacked. Every other GPU + // test passes just as well when the path falls back to the CPU on + // every tile, which is precisely the failure worth catching. + val subject = provider(VectorTileProvider.RenderMode.GPU) + // FULL reuses its cached ground after the first call. The geometry + // route renders every request here (no disk cache), so the assertion + // below really exercises three GPU draws. + repeat(3) { assertNotNull(subject.geometryTiles.renderTile(TileRequest(x = 0, y = 0, z = 0))) } + assertEquals("tiles fell back to the CPU", 0L, subject.gpuFallbacks) + assertEquals(3L, subject.gpuRenders) + } + + @Test + fun gpuAndCpuAgreeOnWhatTheTileLooksLike() { + val gpu = + decode( + provider(VectorTileProvider.RenderMode.GPU) + .renderTile(TileRequest(x = 0, y = 0, z = 0))!!, + ) + val cpu = + decode( + provider(VectorTileProvider.RenderMode.CPU) + .renderTile(TileRequest(x = 0, y = 0, z = 0))!!, + ) + assertEquals(cpu.width, gpu.width) + + // Compared as 8x8 block averages, not pixel by pixel. The two + // rasterisers genuinely differ on edges — MSAA against analytic + // coverage — and this test tile is a whole world at z0, which is + // almost entirely coastline: 3.4% of its pixels sit on an edge, while + // a normal street tile measures 0.05%. Averaging asks the question the + // claim actually makes, that no *region* disagrees. + val size = cpu.width + val block = 8 + val blocks = size / block + val gpuRow = IntArray(size) + val cpuRow = IntArray(size) + val gpuSums = Array(blocks) { IntArray(blocks * 3) } + val cpuSums = Array(blocks) { IntArray(blocks * 3) } + + for (y in 0 until size) { + gpu.getPixels(gpuRow, 0, size, 0, y, size, 1) + cpu.getPixels(cpuRow, 0, size, 0, y, size, 1) + val by = y / block + for (x in 0 until size) { + val bx = x / block + for (channel in 0..2) { + val shift = 16 - channel * 8 + gpuSums[by][bx * 3 + channel] += (gpuRow[x] shr shift) and 0xFF + cpuSums[by][bx * 3 + channel] += (cpuRow[x] shr shift) and 0xFF + } + } + } + + val pixelsPerBlock = block * block + var worstBlock = 0 + var differingBlocks = 0 + for (by in 0 until blocks) { + for (bx in 0 until blocks) { + var worstChannel = 0 + for (channel in 0..2) { + val a = gpuSums[by][bx * 3 + channel] / pixelsPerBlock + val b = cpuSums[by][bx * 3 + channel] / pixelsPerBlock + worstChannel = maxOf(worstChannel, Math.abs(a - b)) + } + if (worstChannel > 24) differingBlocks++ + worstBlock = maxOf(worstBlock, worstChannel) + } + } + val percent = differingBlocks * 100.0 / (blocks * blocks) + println("GPU_VS_CPU_BLOCKS=%.2f%% worst=%d".format(percent, worstBlock)) + assertTrue( + "%.2f%% of 8x8 blocks disagree (worst channel delta %d)".format(percent, worstBlock), + percent < 1.0, + ) + } + + @Test + fun gpuServesThroughTheTileServersThreadPool() { + // The EGL context is thread-bound; the server calls renderTile from a + // pool. This is the test that would fail if the GL work were not + // marshalled onto its own thread. + val server = TileServerRegistry.get() + val subject = provider(VectorTileProvider.RenderMode.GPU) + server.register(routeId, subject) + + val template = server.urlTemplate(routeId, 512) + val urls = + listOf(0 to 0, 1 to 0, 0 to 1, 1 to 1).map { (x, y) -> + template.replace("{z}", "1").replace("{x}", "$x").replace("{y}", "$y") + } + + val results = + urls.map { url -> + Thread { + val connection = URL(url).openConnection() as HttpURLConnection + try { + check(connection.responseCode == 200) { "status ${connection.responseCode}" } + val bytes = connection.inputStream.use { it.readBytes() } + check(bytes.size > 1_000) { "tiny tile: ${bytes.size}" } + } finally { + connection.disconnect() + } + } + } + results.forEach { it.start() } + results.forEach { it.join(30_000) } + results.forEach { assertTrue("a request thread never finished", !it.isAlive) } + } + + @Test + fun aClosedGpuProviderStopsCleanly() { + val subject = + VectorTileProvider.create( + styleJson = styleJson, + renderMode = VectorTileProvider.RenderMode.GPU, + fetchTile = { tileBytes }, + ) + assertNotNull(subject.renderTile(TileRequest(x = 0, y = 0, z = 0))) + subject.close() + subject.close() + assertEquals(null, subject.renderTile(TileRequest(x = 0, y = 0, z = 0))) + } + + @Test + fun reportsRelativeCostOfBothModes() { + val gpu = provider(VectorTileProvider.RenderMode.GPU) + val cpu = provider(VectorTileProvider.RenderMode.CPU) + + fun median(subject: VectorTileProvider): Double { + repeat(2) { subject.renderTile(TileRequest(x = 0, y = 0, z = 0)) } + val samples = + (1..7) + .map { + val started = System.nanoTime() + subject.renderTile(TileRequest(x = 0, y = 0, z = 0)) + (System.nanoTime() - started) / 1_000_000.0 + }.sorted() + return samples[samples.size / 2] + } + println("MODE_COST gpu=%.1fms cpu=%.1fms".format(median(gpu), median(cpu))) + } + + @Test + fun reportsFixedInputGpuConcurrency() { + val subject = provider(VectorTileProvider.RenderMode.GPU) + val requests = + listOf( + TileRequest(x = 6, y = 6, z = 4), + TileRequest(x = 7, y = 6, z = 4), + TileRequest(x = 8, y = 6, z = 4), + TileRequest(x = 9, y = 6, z = 4), + TileRequest(x = 6, y = 7, z = 4), + TileRequest(x = 7, y = 7, z = 4), + TileRequest(x = 8, y = 7, z = 4), + TileRequest(x = 9, y = 7, z = 4), + ) + + fun median(values: List): Double = values.sorted()[values.size / 2] + + assertNotNull(subject.geometryTiles.renderTile(requests[0])) + for (width in listOf(1, 2, 4, 8)) { + val executor = Executors.newFixedThreadPool(width) + try { + val walls = mutableListOf() + val latencies = mutableListOf() + repeat(7) { batch -> + val started = java.util.concurrent.CountDownLatch(1) + val tasks = + (0 until width).map { index -> + executor.submit( + Callable { + started.await() + val tileStarted = System.nanoTime() + val png = + subject.geometryTiles.renderTile( + requests[(batch + index) % requests.size], + ) + assertNotNull(png) + (System.nanoTime() - tileStarted) / 1_000_000.0 + }, + ) + } + val wallStarted = System.nanoTime() + started.countDown() + latencies += tasks.map { it.get() } + walls += (System.nanoTime() - wallStarted) / 1_000_000.0 + } + println( + "GPU_CONCURRENCY width=$width wall=%.1fms latency=%.1fms throughput=%.1f_tiles_s".format( + median(walls), + median(latencies), + width * 1_000.0 / median(walls), + ), + ) + } finally { + executor.shutdownNow() + } + } + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GpuStencilExperimentTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GpuStencilExperimentTest.kt new file mode 100644 index 000000000..ab7e609c5 --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GpuStencilExperimentTest.kt @@ -0,0 +1,281 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.json.JSONArray +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.FloatBuffer +import java.util.zip.GZIPInputStream +import android.graphics.Bitmap +import android.opengl.GLES20 +import android.opengl.GLES30 +import android.util.Log + +/** Real Shortbread forest: linear fan packing + GPU parity, compared to earcut. */ +@RunWith(AndroidJUnit4::class) +class GpuStencilExperimentTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + + private fun asset(name: String): ByteArray { + val path = "stencil-experiment/$name" + return instrumentation.context.assets.open(path).use { stream -> + if (name.endsWith(".gzip")) { + GZIPInputStream(stream).use { it.readBytes() } + } else { + stream.readBytes() + } + } + } + + private fun direct(bytes: ByteArray) = + ByteBuffer + .allocateDirect(bytes.size) + .order(ByteOrder.LITTLE_ENDIAN) + .apply { + put(bytes) + rewind() + } + + private fun ms(start: Long) = (System.nanoTime() - start) / 1_000_000.0 + + @Test + fun realForestWithStencilMatchesEarcutAndMeasuresDeviceCost() { + val output = File(instrumentation.targetContext.getExternalFilesDir(null), "stencil-experiment") + output.mkdirs() + var started = System.nanoTime() + if (InstrumentationRegistry.getArguments().getString("skipBaseline") != "true") { + val mvt = asset("8-226-100.mvt") + val native = VectorTileRenderer.create(asset("style.json").decodeToString(), 512) + val plan = JSONArray(native.plan(8, 226, 100)) + val lengths = + IntArray(plan.length()) { + if (plan.getJSONObject(it).optBoolean("labelsOnly", false)) 0 else mvt.size + } + started = System.nanoTime() + val baseline = TessellatedTile(native.tessellate(8, 226, 100, 512, mvt, lengths)) + val baselineMessage = + "native total=" + ms(started) + "ms decode=" + baseline.decodeMs + + "ms earcut=" + baseline.tessellateMs + "ms fill=" + baseline.fillMs + "ms" + Log.i("GpuStencilExperiment", baselineMessage) + File(output, "baseline.txt").writeText(baselineMessage) + try { + val golden = direct(asset("forest-earcut.bin.gzip")).asFloatBuffer() + assertEquals(golden.capacity(), baseline.vertexFloatCount) + var changed = 0 + for (i in 0 until golden.capacity()) { + if (golden.get(i) != baseline.packed.get(baseline.vertexOffset + i)) changed++ + } + assertEquals("desktop reference differs from device native triangles", 0, changed) + } finally { + baseline.close() + native.close() + } + } + + started = System.nanoTime() + val input = direct(asset("forest-rings.bin.gzip")) + val extent = input.int.toFloat() + val color = FloatArray(4) { input.float } + val rings = ArrayList() + var triangles = 0 + repeat(input.int) { + val count = input.int + rings.add(FloatArray(count * 2) { input.float }) + triangles += maxOf(0, count - 2) + } + val fans = + ByteBuffer + .allocateDirect(triangles * 18 * 4) + .order(ByteOrder.nativeOrder()) + .asFloatBuffer() + for (ring in rings) { + for (i in 1 until ring.size / 2 - 1) { + fans.put(ring[0]).put(ring[1]).put(color) + fans.put(ring[i * 2]).put(ring[i * 2 + 1]).put(color) + fans.put(ring[(i + 1) * 2]).put(ring[(i + 1) * 2 + 1]).put(color) + } + } + fans.rewind() + val packingMs = ms(started) + val reference = direct(asset("forest-earcut.bin.gzip")).asFloatBuffer() + val cover = + ByteBuffer + .allocateDirect(6 * 6 * 4) + .order(ByteOrder.nativeOrder()) + .asFloatBuffer() + for ((x, y) in listOf( + 0f to 0f, extent to 0f, 0f to extent, + 0f to extent, extent to 0f, extent to extent, + )) { + cover.put(x).put(y).put(color) + } + cover.rewind() + + EglOffscreen.create().use { context -> + assertEquals(3, context.esVersion) + context.prepare(512, 4) + val ids = IntArray(1) + GLES20.glGenRenderbuffers(1, ids, 0) + GLES20.glBindRenderbuffer(GLES20.GL_RENDERBUFFER, ids[0]) + if (context.activeSamples > 0) { + GLES30.glRenderbufferStorageMultisample( + GLES20.GL_RENDERBUFFER, + context.activeSamples, GLES30.GL_DEPTH24_STENCIL8, 512, 512, + ) + } else { + GLES20.glRenderbufferStorage( + GLES20.GL_RENDERBUFFER, + GLES30.GL_DEPTH24_STENCIL8, 512, 512, + ) + } + GLES20.glFramebufferRenderbuffer( + GLES20.GL_FRAMEBUFFER, GLES20.GL_STENCIL_ATTACHMENT, + GLES20.GL_RENDERBUFFER, ids[0], + ) + assertEquals( + GLES20.GL_FRAMEBUFFER_COMPLETE, + GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER), + ) + SolidBatchRenderer().use { renderer -> + renderer.initialise() + + fun draw( + stencil: Boolean, + geometry: FloatBuffer = if (stencil) fans else reference, + drawExtent: Float = extent, + viewport: Int = 512, + ): ByteBuffer { + context.bindDrawTarget() + GLES20.glViewport(0, 0, viewport, viewport) + GLES20.glDisable(GLES20.GL_CULL_FACE) + GLES20.glDisable(GLES20.GL_DEPTH_TEST) + GLES20.glDisable(GLES20.GL_STENCIL_TEST) + GLES20.glColorMask(true, true, true, true) + renderer.clear(0f, 0f, 0f, 0f) + val vertices = geometry + renderer.upload(vertices, 0, vertices.capacity()) + if (stencil) { + GLES20.glEnable(GLES20.GL_STENCIL_TEST) + GLES20.glStencilMask(1) + GLES20.glClearStencil(0) + GLES20.glClear(GLES20.GL_STENCIL_BUFFER_BIT) + GLES20.glStencilFunc(GLES20.GL_ALWAYS, 0, 1) + GLES20.glStencilOp(GLES20.GL_KEEP, GLES20.GL_KEEP, GLES20.GL_INVERT) + GLES20.glColorMask(false, false, false, false) + } + renderer.draw(listOf(SolidBatchRenderer.Batch(0, vertices.capacity() / 6)), drawExtent) + if (stencil) { + GLES20.glColorMask(true, true, true, true) + GLES20.glStencilFunc(GLES20.GL_EQUAL, 1, 1) + GLES20.glStencilOp(GLES20.GL_KEEP, GLES20.GL_KEEP, GLES20.GL_KEEP) + renderer.upload(cover, 0, cover.capacity()) + renderer.draw(listOf(SolidBatchRenderer.Batch(0, 6)), drawExtent) + GLES20.glDisable(GLES20.GL_STENCIL_TEST) + } + val pixels = context.readPixels() + assertEquals(GLES20.GL_NO_ERROR, GLES20.glGetError()) + return pixels + } + + fun save( + name: String, + pixels: ByteBuffer, + ) { + val bitmap = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888) + pixels.rewind() + bitmap.copyPixelsFromBuffer(pixels) + File(output, name).outputStream().use { + bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) + } + bitmap.recycle() + } + val referencePixels = draw(false) + save("earcut.png", referencePixels) + val candidatePixels = draw(true) + save("stencil.png", candidatePixels) + var seamPixels = 0 + val stitched = ByteBuffer.allocateDirect(512 * 512 * 4) + for (ty in 0..1) { + for (tx in 0..1) { + val shifted = + ByteBuffer + .allocateDirect(fans.capacity() * 4) + .order(ByteOrder.nativeOrder()) + .asFloatBuffer() + for (i in 0 until fans.capacity()) { + val shift = + when (i % 6) { + 0 -> tx * extent / 2 + 1 -> ty * extent / 2 + else -> 0f + } + shifted.put(fans.get(i) - shift) + } + shifted.rewind() + val tile = draw(true, shifted, extent / 2, 256) + for (y in 0 until 256) { + for (x in 0 until 256) { + for (c in 0..3) { + val src = (y * 512 + x) * 4 + c + val dst = ((y + ty * 256) * 512 + x + tx * 256) * 4 + c + stitched.put(dst, tile.get(src)) + } + } + } + } + } + for (i in 0 until 512 * 512) { + val offset = i * 4 + if ((0..3).any { stitched.get(offset + it) != candidatePixels.get(offset + it) }) { + seamPixels++ + } + } + save("stitched.png", stitched) + Log.i("GpuStencilExperiment", "four quadrants seamPixels=" + seamPixels) + assertEquals("tile cuts changed coverage", 0, seamPixels) + var different = 0 + var difference = 0L + for (i in 0 until 512 * 512) { + val a = referencePixels.get(i * 4 + 3).toInt() and 255 + val b = candidatePixels.get(i * 4 + 3).toInt() and 255 + if (a != b) different++ + difference += kotlin.math.abs(a - b) + } + val meanAlphaError = difference.toDouble() / (512 * 512) + val times = mutableListOf() + val referenceTimes = mutableListOf() + repeat(7) { + context.finish() + var start = System.nanoTime() + draw(false) + referenceTimes.add(ms(start)) + context.finish() + start = System.nanoTime() + draw(true) + times.add(ms(start)) + } + val message = + "MSAA=" + context.activeSamples + " packing=" + packingMs + + "ms stencil upload+GPU+read median=" + times.sorted()[3] + + "ms earcut prepared upload+GPU+read median=" + referenceTimes.sorted()[3] + + "ms differentPixels=" + different + " meanAlphaError=" + meanAlphaError + + " fanTriangles=" + triangles + " seamPixels=" + seamPixels + Log.i("GpuStencilExperiment", message) + File(output, "results.txt").writeText(message) + assertTrue("coverage differs: " + message, meanAlphaError < 1.0) + } + context.bindDrawTarget() + GLES20.glFramebufferRenderbuffer( + GLES20.GL_FRAMEBUFFER, + GLES20.GL_STENCIL_ATTACHMENT, GLES20.GL_RENDERBUFFER, 0, + ) + GLES20.glDeleteRenderbuffers(1, ids, 0) + } + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GridIndexPrototypeTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GridIndexPrototypeTest.kt new file mode 100644 index 000000000..70eb7476d --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GridIndexPrototypeTest.kt @@ -0,0 +1,210 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Test +import org.junit.runner.RunWith +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.Arrays + +/** + * A flat grid index against the hex-cell-plus-kd-tree one the SDK ships. + * + * Written outside the SDK on purpose: this is a question, not a change. What it + * asks is whether the cost of the current index is its arithmetic or its + * allocation. The hex index builds a HexCell object with a String id per + * marker, puts them in a ConcurrentHashMap and sorts a kd-tree over them; this + * builds one Long per marker and sorts a primitive array. + * + * The web SDK already indexes this way — GeoGridIndex, 0.02-degree cells — so + * the platforms have diverged and only one of them has been measured. + */ +@RunWith(AndroidJUnit4::class) +class GridIndexPrototypeTest { + /** + * Positions only. What is being compared is the index, not the marker + * objects around it — and 144k MarkerState objects are what makes the hex + * index run out of memory in the first place. + */ + private class Positions( + val lat: DoubleArray, + val lon: DoubleArray, + ) + + private fun loadPositions(): Positions { + val bytes = + InstrumentationRegistry + .getInstrumentation() + .context.assets + .open("tokyo-trees.bin") + .use { it.readBytes() } + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + val magic = ByteArray(5) + buffer.get(magic) + check(String(magic, Charsets.US_ASCII).startsWith("TREE")) + + fun skipNames() { + repeat(buffer.int) { + val length = buffer.short.toInt() + buffer.position(buffer.position() + length) + } + } + skipNames() // species + skipNames() // wards + skipNames() // roads + + val count = buffer.int + val lat = DoubleArray(count) + val lon = DoubleArray(count) + for (index in 0 until count) { + lat[index] = buffer.float.toDouble() + lon[index] = buffer.float.toDouble() + buffer.short + buffer.float + buffer.short + buffer.short + buffer.short + } + return Positions(lat, lon) + } + + /** + * A uniform lat/lng grid held as one sorted primitive array. + * + * Each entry packs its cell key and the marker's index into a single Long, + * so building the index is an arithmetic pass and a primitive sort: no + * objects, no hashing, no strings. A bounds query walks the cells it covers + * and binary-searches each one's run. + */ + private class GridIndex( + positions: Positions, + private val cellDegrees: Double, + ) { + private val packed: LongArray + + private fun cellKey( + lat: Double, + lon: Double, + ): Long { + // Offsets keep the keys positive so their ordering matches the + // numeric ordering the sort and the binary search rely on. + val latCell = Math.floor(lat / cellDegrees).toLong() + 262144 + val lonCell = Math.floor(lon / cellDegrees).toLong() + 524288 + return (latCell shl 20) or lonCell + } + + init { + packed = + LongArray(positions.lat.size) { index -> + (cellKey(positions.lat[index], positions.lon[index]) shl INDEX_BITS) or + index.toLong() + } + Arrays.sort(packed) + } + + /** Indices of every marker inside the box. */ + fun query( + south: Double, + north: Double, + west: Double, + east: Double, + ): IntArray { + var result = IntArray(64) + var found = 0 + val latFrom = Math.floor(south / cellDegrees).toLong() + val latTo = Math.floor(north / cellDegrees).toLong() + val lonFrom = Math.floor(west / cellDegrees).toLong() + val lonTo = Math.floor(east / cellDegrees).toLong() + + for (latCell in latFrom..latTo) { + for (lonCell in lonFrom..lonTo) { + val key = ((latCell + 262144) shl 20) or (lonCell + 524288) + var at = lowerBound(key shl INDEX_BITS) + val limit = (key + 1) shl INDEX_BITS + while (at < packed.size && packed[at] < limit) { + if (found == result.size) result = result.copyOf(result.size * 2) + result[found++] = (packed[at] and INDEX_MASK).toInt() + at++ + } + } + } + return result.copyOf(found) + } + + private fun lowerBound(target: Long): Int { + var low = 0 + var high = packed.size + while (low < high) { + val mid = (low + high) ushr 1 + if (packed[mid] < target) low = mid + 1 else high = mid + } + return low + } + + companion object { + // 24 bits of index, enough for 16.7M markers, under the cell key. + private const val INDEX_BITS = 24 + private const val INDEX_MASK = (1L shl INDEX_BITS) - 1 + } + } + + private fun median(values: List): Double = values.sorted()[values.size / 2] + + @Test + fun gridIndexAgainstBruteForce() { + val positions = loadPositions() + val count = positions.lat.size + + for (cellDegrees in listOf(0.02, 0.005, 0.001)) { + var index: GridIndex? = null + val build = + median( + (0 until 3).map { + val started = System.nanoTime() + index = GridIndex(positions, cellDegrees) + (System.nanoTime() - started) / 1_000_000.0 + }, + ) + + // A z14-sized box near Shinjuku, and a z9-sized one over all Tokyo. + for ((label, box) in listOf( + "tile-z14" to doubleArrayOf(35.688, 35.694, 139.695, 139.703), + "all-tokyo" to doubleArrayOf(35.50, 35.85, 139.55, 139.95), + )) { + var found = 0 + val query = + median( + (0 until 7).map { + val started = System.nanoTime() + found = index!!.query(box[0], box[1], box[2], box[3]).size + (System.nanoTime() - started) / 1_000_000.0 + }, + ) + var scanFound = 0 + val scan = + median( + (0 until 7).map { + val started = System.nanoTime() + var hits = 0 + for (i in 0 until count) { + val la = positions.lat[i] + val lo = positions.lon[i] + if (la >= box[0] && la <= box[1] && lo >= box[2] && lo <= box[3]) { + hits++ + } + } + scanFound = hits + (System.nanoTime() - started) / 1_000_000.0 + }, + ) + println( + "GRID n=%d cell=%.3f build=%.0fms %s query=%.2fms/%d scan=%.2fms/%d".format( + count, cellDegrees, build, label, query, found, scan, scanFound, + ), + ) + } + index = null + } + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GroundResolutionTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GroundResolutionTest.kt new file mode 100644 index 000000000..883277f54 --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/GroundResolutionTest.kt @@ -0,0 +1,75 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import android.graphics.BitmapFactory + +@RunWith(AndroidJUnit4::class) +class GroundResolutionTest { + /** + * The scale reaches the image and nothing else: same source tile, same + * geographic coverage, a separate cache entry, and a label overlay that + * never drops below 2x. + */ + @Test + fun higherResolutionUsesSeparateCacheAndPreservesSourceCoordinates() { + val context = InstrumentationRegistry.getInstrumentation().context + val style = context.assets.open("demo-style.json").use { it.readBytes().decodeToString() } + val tile = context.assets.open("tile-0-0-0.pbf").use { it.readBytes() } + val cache = File(context.cacheDir, "resolution-${System.nanoTime()}") + val urls = mutableListOf() + val request = TileRequest(x = 0, y = 0, z = 0) + try { + for (ratio in 1..3) { + val provider = + VectorTileProvider.create( + styleJson = style, + tileSize = 512, + renderMode = VectorTileProvider.RenderMode.GPU, + diskCacheDir = cache, + renderScale = ratio, + fetchTile = { url -> + urls.add(url) + tile + }, + ) + try { + val png = provider.geometryTiles.renderTile(request)!! + val bitmap = BitmapFactory.decodeByteArray(png, 0, png.size)!! + assertEquals(512 * ratio, bitmap.width) + assertEquals(512 * ratio, bitmap.height) + bitmap.recycle() + assertEquals(1L, provider.gpuRenders) + assertEquals(0L, provider.gpuFallbacks) + // The labels follow the display too, but never go below 2x: + // text is where a tile's grain is seen. + val labels = provider.labelTiles.renderTile(request)!! + val overlay = BitmapFactory.decodeByteArray(labels, 0, labels.size)!! + val expected = 512 * maxOf(ratio, 2) + assertEquals(expected, overlay.width) + assertEquals(expected, overlay.height) + overlay.recycle() + if (ratio == 2) { + repeat(2) { + val full = provider.renderTile(request)!! + val decoded = BitmapFactory.decodeByteArray(full, 0, full.size)!! + assertEquals(1024, decoded.width) + decoded.recycle() + } + assertEquals(0L, provider.gpuFallbacks) + } + } finally { + provider.close() + } + } + assertEquals(1, urls.distinct().size) + } finally { + cache.deleteRecursively() + } + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/IconSizeProbeTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/IconSizeProbeTest.kt new file mode 100644 index 000000000..e8d638325 --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/IconSizeProbeTest.kt @@ -0,0 +1,118 @@ +package com.mapconductor.vectortile + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.marker.BitmapIcon +import com.mapconductor.core.marker.MarkerEntity +import com.mapconductor.core.marker.MarkerIconInterface +import com.mapconductor.core.marker.MarkerManager +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTileRenderer +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint + +/** + * アイコンが実際に何ピクセルで描かれるかを、出来上がったタイルから数える。 + * + * ios-sdk-core の `IconSizeProbeTests` と対になっていて、同じ 14 単位の円を + * 同じ zoom・同じ iconScaleCallback で描いて比べる。計算で追うと前提を一つ + * 間違えるだけで答えが変わるので、描いた結果を測る。 + */ +@RunWith(AndroidJUnit4::class) +class IconSizeProbeTest { + /** サンプルの TreeDotIcon と同じ形。 */ + private class DotIcon( + private val bitmap: Bitmap, + private val sizePx: Float, + ) : MarkerIconInterface { + override val scale: Float = 1.0f + override val anchor: Offset = Offset(0.5f, 0.5f) + override val iconSize: Dp = sizePx.dp + override val infoAnchor: Offset = Offset(0.5f, 0.0f) + override val debug: Boolean = false + + override fun toBitmapIcon(): BitmapIcon = + BitmapIcon(bitmap = bitmap, size = Size(sizePx, sizePx), anchor = anchor) + } + + @Test + fun drawnIconSize() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val density = context.resources.displayMetrics.density + val callbackScale = 1.4 // サンプルの zoom > 15 の帯 + val tileSize = 256 // プロバイダが渡す値(GoogleMapMarkerController) + + // サンプルと同じ作り: 14 **dp** の円。密度倍したピクセルでビットマップを作る。 + // core の AbstractDefaultIcon が dpToPxForBitmap(iconSize) でそうしているのと + // 同じ流儀。ここを生ピクセルにすると端末が精細になるほど小さく見える。 + val sizeDp = 10f + val sizePx = ResourceProvider.dpToPxForBitmap(sizeDp).toInt() + val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888) + Canvas(bitmap).drawCircle( + sizePx / 2f, sizePx / 2f, sizePx / 2f - 1f, + Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.RED }, + ) + + val zoom = 16 + val n = (1 shl zoom).toDouble() + val lat = 35.68 + val lon = 139.75 + val latRad = Math.toRadians(lat) + val tx = ((lon + 180.0) / 360.0 * n).toInt() + val ty = ((1.0 - Math.log(Math.tan(latRad) + 1.0 / Math.cos(latRad)) / Math.PI) / 2.0 * n).toInt() + + val manager = MarkerManager.defaultManager(minMarkerCount = 1) + manager.registerEntity( + MarkerEntity( + marker = null, + state = MarkerState(position = GeoPoint(lat, lon), icon = DotIcon(bitmap, sizePx.toFloat())), + visible = true, + isRendered = true, + tiling = true, + ), + ) + val renderer = + MarkerTileRenderer( + markerManager = manager, + tileSize = tileSize, + cacheSizeBytes = 1 shl 20, + iconScaleCallback = { _, _ -> callbackScale }, + ) + + val png = renderer.renderTile(TileRequest(tx, ty, zoom)) + assertTrue("タイルが描けていない", png != null) + val tile = BitmapFactory.decodeByteArray(png, 0, png!!.size) + + var minX = tile.width + var maxX = -1 + for (y in 0 until tile.height) { + for (x in 0 until tile.width) { + if (Color.alpha(tile.getPixel(x, y)) > 8) { + if (x < minX) minX = x + if (x > maxX) maxX = x + } + } + } + val drawnPx = maxX - minX + 1 + // タイルは 256dp として表示されるので、見かけの大きさはこの比。 + val apparentDp = drawnPx.toDouble() / tile.width * 256.0 + println( + "ICONPROBE android density=%.2f tile=%d canvas=%d sizeDp=%.0f sizePx=%d drawnPx=%d apparentDp=%.2f" + .format(density, tileSize, tile.width, sizeDp, sizePx, drawnPx, apparentDp), + ) + assertTrue(drawnPx > 0) + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/MarkerTileCostTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/MarkerTileCostTest.kt new file mode 100644 index 000000000..cf1da0c2b --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/MarkerTileCostTest.kt @@ -0,0 +1,550 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.marker.MarkerEntity +import com.mapconductor.core.marker.MarkerManager +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTileRenderer +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Test +import org.junit.runner.RunWith +import java.nio.ByteBuffer +import java.nio.ByteOrder +import android.graphics.Bitmap +import android.graphics.BitmapFactory + +/** + * Measures where the time actually goes when markers are baked into raster + * tiles, so the question "would the Rust renderer make this faster?" can be + * answered with numbers rather than intuition. + * + * Nothing in this suite asserts a threshold. It reports, because there is no + * prior measurement of this path to regress against — which is itself the + * finding that prompted it. + */ +@RunWith(AndroidJUnit4::class) +class MarkerTileCostTest { + private val tileSize = 512 + + /** Markers scattered over greater Tokyo, deterministic so runs compare. */ + private fun manager(count: Int): MarkerManager { + val manager = MarkerManager.defaultManager(minMarkerCount = 1) + var seed = 12345L + + fun next(): Double { + // Deterministic LCG rather than Random, so a slow run can be + // compared against a fast one marker for marker. + seed = (seed * 6364136223846793005L + 1442695040888963407L) + return ((seed ushr 11).toDouble() / (1L shl 53).toDouble()) + } + repeat(count) { + val lat = 35.5 + next() * 0.4 + val lng = 139.5 + next() * 0.5 + manager.registerEntity( + MarkerEntity( + marker = null, + state = MarkerState(position = GeoPoint(lat, lng)), + visible = true, + isRendered = true, + tiling = true, + ), + ) + } + return manager + } + + private fun renderer(manager: MarkerManager) = + MarkerTileRenderer( + markerManager = manager, + tileSize = tileSize, + cacheSizeBytes = 8 * 1024 * 1024, + ) + + private fun median(values: List): Double = values.sorted()[values.size / 2] + + /** Times one call, having thrown away the tile cache first. */ + private fun timeUncached( + manager: MarkerManager, + request: TileRequest, + rounds: Int = 5, + ): Pair { + var bytes: ByteArray? = null + val samples = ArrayList(rounds) + repeat(rounds) { + // A fresh renderer each round: the cache would otherwise answer + // every call after the first, which is not what is being measured. + val fresh = renderer(manager) + val started = System.nanoTime() + bytes = fresh.renderTile(request) + samples.add((System.nanoTime() - started) / 1_000_000.0) + } + return median(samples) to bytes + } + + @Test + fun whereTheTimeGoesRenderingAMarkerTile() { + for (markerCount in listOf(2_000, 20_000)) { + val manager = manager(markerCount) + + // z=12 covers Tokyo in a handful of tiles: a realistic dense tile. + // z=6 puts the entire dataset on one tile, which is the case the + // renderer has no declutter for. + for ((z, x, y) in listOf(Triple(12, 3637, 1612), Triple(6, 56, 25))) { + val request = TileRequest(x = x, y = y, z = z) + val (renderMs, bytes) = timeUncached(manager, request) + if (bytes == null) { + println("MARKERTILE n=$markerCount z=$z EMPTY") + continue + } + + // Re-encode the tile the renderer actually produced, so the + // encoder comparison runs on real marker-tile content rather + // than on generated content. Synthetic tiles mislead badly + // here: hard-edged icons on transparency made Paeth filtering + // look 7x better than Sub, and on real anti-aliased icons it + // was the same size and 50% slower. + val decoded = + BitmapFactory + .decodeByteArray(bytes, 0, bytes.size) + .copy(Bitmap.Config.ARGB_8888, false) + + val compressSamples = ArrayList(5) + var compressBytes = 0 + repeat(5) { + val stream = java.io.ByteArrayOutputStream(bytes.size) + val started = System.nanoTime() + decoded.compress(Bitmap.CompressFormat.PNG, 100, stream) + compressSamples.add((System.nanoTime() - started) / 1_000_000.0) + compressBytes = stream.size() + } + + val buffer = + ByteBuffer + .allocateDirect(decoded.width * decoded.height * 4) + .order(ByteOrder.nativeOrder()) + decoded.copyPixelsToBuffer(buffer) + val rustSamples = ArrayList(5) + var rustBytes = 0 + repeat(5) { + buffer.rewind() + val started = System.nanoTime() + rustBytes = com.mapconductor.core.tileserver.TilePngEncoder + .encode( + buffer, decoded.width, decoded.height, premultiplied = true, + )?.size ?: 0 + rustSamples.add((System.nanoTime() - started) / 1_000_000.0) + } + + val compressMs = median(compressSamples) + val rustMs = median(rustSamples) + // No encode share here: the renderer no longer calls + // Bitmap.compress, so dividing one by the other would compare a + // path that runs against one that does not. + println( + "MARKERTILE n=%d z=%d render=%.1fms png=%d | reencode compress=%.1fms/%dB rust=%.1fms/%dB" + .format( + markerCount, z, renderMs, bytes.size, + compressMs, compressBytes, rustMs, rustBytes, + ), + ) + decoded.recycle() + } + } + } + + /** How much the tile cache is worth, and therefore what the web SW path loses by lacking one. */ + @Test + fun whatTheTileCacheIsWorth() { + val manager = manager(20_000) + val live = renderer(manager) + val request = TileRequest(x = 3637, y = 1612, z = 12) + + val coldStarted = System.nanoTime() + live.renderTile(request) + val coldMs = (System.nanoTime() - coldStarted) / 1_000_000.0 + + val warmSamples = ArrayList(10) + repeat(10) { + val started = System.nanoTime() + live.renderTile(request) + warmSamples.add((System.nanoTime() - started) / 1_000_000.0) + } + println("MARKERTILE_CACHE cold=%.1fms warm=%.3fms".format(coldMs, median(warmSamples))) + } + + /** + * Splits the low-zoom case into its parts. + * + * z=6 with 20k markers takes seconds per tile, and the encoder is 1% of + * that, so the cost is somewhere in query/prepare/draw. Which one decides + * whether a GPU rasteriser would help at all. + */ + @Test + fun whatMakesTheLowZoomTileSlow() { + val manager = manager(20_000) + val bounds = + com.mapconductor.core.features.GeoRectBounds().apply { + extend(GeoPoint(35.4, 139.4)) + extend(GeoPoint(36.0, 140.1)) + } + + val querySamples = ArrayList(5) + var found = 0 + repeat(5) { + val started = System.nanoTime() + found = manager.findMarkersInBounds(bounds).filter { it.tiling }.size + querySamples.add((System.nanoTime() - started) / 1_000_000.0) + } + + val entities = manager.findMarkersInBounds(bounds).filter { it.tiling } + + // A stand-in for the default pin at this device's density. The real one + // cannot be constructed from here (its Compose-typed constructor does + // not resolve across the test APK), and it does not need to be: the + // renderer's icon lookup is a BitmapIconCache hit, so what is being + // timed is the blit, and the blit only cares about the pixel size. + val iconPx = + com.mapconductor.core.ResourceProvider + .dpToPxForBitmap(32.0) + .toInt() + val icon = + Bitmap.createBitmap(iconPx, iconPx, Bitmap.Config.ARGB_8888).apply { + eraseColor(android.graphics.Color.argb(220, 40, 90, 200)) + } + + // The prepare pass, minus the cached icon lookup: projection per marker. + val prepareSamples = ArrayList(5) + repeat(5) { + val started = System.nanoTime() + var sink = 0.0 + for (entity in entities) { + sink += entity.state.position.latitude + entity.state.position.longitude + } + prepareSamples.add((System.nanoTime() - started) / 1_000_000.0) + check(sink != 0.0) + } + + // The draw loop on its own: one scaled, filtered blit per marker. + val canvas = Bitmap.createBitmap(700, 700, Bitmap.Config.ARGB_8888) + val paint = + android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { + isFilterBitmap = true + isDither = true + } + val drawSamples = ArrayList(5) + repeat(5) { + val target = android.graphics.Canvas(canvas) + val started = System.nanoTime() + for (index in entities.indices) { + val left = (index % 600).toFloat() + val top = ((index / 600) % 600).toFloat() + target.drawBitmap( + icon, + null, + android.graphics.RectF(left, top, left + iconPx, top + iconPx), + paint, + ) + } + drawSamples.add((System.nanoTime() - started) / 1_000_000.0) + } + canvas.recycle() + icon.recycle() + + println( + "MARKERTILE_PHASES markers=%d query=%.1fms prepare=%.1fms draw=%.1fms iconPx=%dx%d" + .format( + found, median(querySamples), median(prepareSamples), median(drawSamples), + iconPx, iconPx, + ), + ) + } + + /** + * Why one blit costs 0.46 ms inside the renderer but 0.01 ms in isolation. + * + * The two differ in three ways — canvas size, whether the destination lands + * on whole pixels, and how much the marks overlap — so this varies them one + * at a time instead of guessing. + */ + @Test + fun whatMakesTheBlitSlow() { + val iconPx = + com.mapconductor.core.ResourceProvider + .dpToPxForBitmap(32.0) + .toInt() + val icon = + Bitmap.createBitmap(iconPx, iconPx, Bitmap.Config.ARGB_8888).apply { + eraseColor(android.graphics.Color.argb(220, 40, 90, 200)) + } + val paint = + android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { + isFilterBitmap = true + isDither = true + } + val count = 20_000 + + fun run( + canvasPx: Int, + fractional: Boolean, + spreadPx: Int, + ): Double { + val surface = Bitmap.createBitmap(canvasPx, canvasPx, Bitmap.Config.ARGB_8888) + val samples = ArrayList(3) + repeat(3) { + val target = android.graphics.Canvas(surface) + val started = System.nanoTime() + for (index in 0 until count) { + val base = (index % spreadPx).toFloat() + val top = ((index / spreadPx) % spreadPx).toFloat() + // 0.37 is arbitrary; the point is only that it is not a whole pixel. + val offset = if (fractional) 0.37f else 0f + val left = base + offset + val up = top + offset + target.drawBitmap( + icon, null, + android.graphics.RectF(left, up, left + iconPx, up + iconPx), + paint, + ) + } + samples.add((System.nanoTime() - started) / 1_000_000.0) + } + surface.recycle() + return median(samples) + } + + val small = run(700, fractional = false, spreadPx = 600) + val big = run(1600, fractional = false, spreadPx = 600) + val bigFractional = run(1600, fractional = true, spreadPx = 600) + val bigFractionalStacked = run(1600, fractional = true, spreadPx = 40) + val bigStacked = run(1600, fractional = false, spreadPx = 40) + icon.recycle() + + println( + ( + "MARKERTILE_BLIT n=%d icon=%d small=%.0fms big=%.0fms " + + "bigFractional=%.0fms bigStacked=%.0fms bigFractionalStacked=%.0fms" + ).format(count, iconPx, small, big, bigFractional, bigStacked, bigFractionalStacked), + ) + } + + /** Two candidate fixes for the sub-pixel blit cost, measured against it. */ + @Test + fun candidateFixesForTheBlit() { + val iconPx = + com.mapconductor.core.ResourceProvider + .dpToPxForBitmap(32.0) + .toInt() + val icon = + Bitmap.createBitmap(iconPx, iconPx, Bitmap.Config.ARGB_8888).apply { + eraseColor(android.graphics.Color.argb(220, 40, 90, 200)) + } + val count = 20_000 + + fun run( + filter: Boolean, + snap: Boolean, + ): Double { + val paint = + android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { + isFilterBitmap = filter + isDither = true + } + val surface = Bitmap.createBitmap(1600, 1600, Bitmap.Config.ARGB_8888) + val samples = ArrayList(3) + repeat(3) { + val target = android.graphics.Canvas(surface) + val started = System.nanoTime() + for (index in 0 until count) { + val leftRaw = (index % 600) + 0.37f + val topRaw = ((index / 600) % 600) + 0.37f + val left = if (snap) kotlin.math.round(leftRaw) else leftRaw + val up = if (snap) kotlin.math.round(topRaw) else topRaw + target.drawBitmap( + icon, null, + android.graphics.RectF(left, up, left + iconPx, up + iconPx), + paint, + ) + } + samples.add((System.nanoTime() - started) / 1_000_000.0) + } + surface.recycle() + return median(samples) + } + + println( + "MARKERTILE_FIX baseline=%.0fms noFilter=%.0fms snapped=%.0fms snappedNoFilter=%.0fms" + .format( + run(filter = true, snap = false), + run(filter = false, snap = false), + run(filter = true, snap = true), + run(filter = false, snap = true), + ), + ) + icon.recycle() + } + + /** + * Markers land where their coordinates say they do. + * + * The draw rounds its destination to whole pixels, which is worth 20x but + * would be worth nothing if it put the markers somewhere else. This pins + * the placement independently of the timing work. + */ + @Test + fun markersLandWhereTheirCoordinatesSay() { + val z = 12 + val tileX = 3638 + val tileY = 1612 + + // Positions are derived from the tile rather than written down, so the + // test cannot drift a marker into the neighbouring tile — which is + // exactly what hand-computed coordinates did on the first attempt. + val worldTilesForPlacement = 1 shl z + + fun atFraction( + fx: Double, + fy: Double, + ): GeoPoint { + val worldX = tileX + fx + val worldY = tileY + fy + val longitude = worldX / worldTilesForPlacement * 360.0 - 180.0 + val n = Math.PI * (1.0 - 2.0 * worldY / worldTilesForPlacement) + val latitude = Math.toDegrees(kotlin.math.atan(kotlin.math.sinh(n))) + return GeoPoint(latitude, longitude) + } + val positions = + listOf( + atFraction(0.25, 0.25), + atFraction(0.50, 0.60), + atFraction(0.75, 0.40), + ) + val manager = MarkerManager.defaultManager(minMarkerCount = 1) + positions.forEach { position -> + manager.registerEntity( + MarkerEntity( + marker = null, + state = MarkerState(position = position), + visible = true, + isRendered = true, + tiling = true, + ), + ) + } + + val bytes = checkNotNull(renderer(manager).renderTile(TileRequest(x = tileX, y = tileY, z = z))) + val tile = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + val worldTiles = 1 shl z + + fun tilePixel(position: GeoPoint): Pair { + val worldX = (position.longitude + 180.0) / 360.0 * worldTiles + val latRad = Math.toRadians(position.latitude) + val worldY = + ( + 1.0 - kotlin.math.ln( + kotlin.math.tan(latRad) + 1.0 / kotlin.math.cos(latRad), + ) / Math.PI + ) / 2.0 * worldTiles + return Math.round((worldX - tileX) * tile.width).toInt() to + Math.round((worldY - tileY) * tile.height).toInt() + } + + /** Is anything drawn within `radius` px of (x, y)? */ + fun painted( + x: Int, + y: Int, + radius: Int, + ): Boolean { + for (dy in -radius..radius) { + for (dx in -radius..radius) { + val px = x + dx + val py = y + dy + if (px !in 0 until tile.width || py !in 0 until tile.height) continue + if (tile.getPixel(px, py) ushr 24 != 0) return true + } + } + return false + } + + for (position in positions) { + val (x, y) = tilePixel(position) + println( + "MARKERTILE_PLACE tile=${tile.width}x${tile.height} " + + "pos=$position -> $x,$y painted=${painted(x, y, 6)}", + ) + // The default pin is anchored near its tip, so the icon body sits + // above the coordinate; a small box around it is the honest test. + org.junit.Assert.assertTrue( + "nothing drawn at $position -> $x,$y (tile ${tile.width})", + painted(x, y, radius = 6), + ) + } + + // Somewhere no marker is: the tile is not simply filled in. + val (firstX, firstY) = tilePixel(positions[0]) + val emptyX = (firstX + tile.width / 3) % tile.width + val emptyY = (firstY + tile.height / 3) % tile.height + org.junit.Assert.assertFalse( + "unexpected paint at $emptyX,$emptyY", + painted(emptyX, emptyY, radius = 2), + ) + tile.recycle() + } + + /** + * Stacked duplicates render the same as one marker. + * + * The renderer drops markers that agree exactly on rectangle and icon, on + * the grounds that all but the last are invisible. This is that claim, + * stated as a test rather than as a comment. + */ + @Test + fun stackedDuplicatesLookLikeOne() { + val z = 12 + val tileX = 3638 + val tileY = 1612 + val worldTiles = 1 shl z + + fun atFraction( + fx: Double, + fy: Double, + ): GeoPoint { + val longitude = (tileX + fx) / worldTiles * 360.0 - 180.0 + val n = Math.PI * (1.0 - 2.0 * (tileY + fy) / worldTiles) + return GeoPoint(Math.toDegrees(kotlin.math.atan(kotlin.math.sinh(n))), longitude) + } + + fun tile(copies: Int): IntArray { + val manager = MarkerManager.defaultManager(minMarkerCount = 1) + repeat(copies) { + manager.registerEntity( + MarkerEntity( + marker = null, + // A fresh state each time: the same position, but not + // the same object, so the manager keeps all of them. + state = MarkerState(position = atFraction(0.5, 0.5)), + visible = true, + isRendered = true, + tiling = true, + ), + ) + } + val bytes = + checkNotNull( + renderer(manager).renderTile(TileRequest(x = tileX, y = tileY, z = z)), + ) + val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + val pixels = IntArray(bitmap.width * bitmap.height) + bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height) + bitmap.recycle() + return pixels + } + + val one = tile(1) + val many = tile(50) + org.junit.Assert.assertEquals(one.size, many.size) + var differing = 0 + for (index in one.indices) if (one[index] != many[index]) differing++ + org.junit.Assert.assertEquals("50 stacked copies differ in $differing pixels", 0, differing) + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/ProviderDisposalTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/ProviderDisposalTest.kt new file mode 100644 index 000000000..f58ade9df --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/ProviderDisposalTest.kt @@ -0,0 +1,78 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.locks.ReentrantReadWriteLock + +@RunWith(AndroidJUnit4::class) +class ProviderDisposalTest { + @Test + fun uiDisposalDoesNotWaitForAnInFlightNativeCallOrFreeItsHandle() { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val style = + instrumentation.context.assets + .open("demo-style.json") + .use { it.readBytes().decodeToString() } + val provider = + VectorTileProvider + .create(styleJson = style, renderMode = VectorTileProvider.RenderMode.GPU, fetchTile = { null }) + val renderer = + VectorTileProvider::class.java + .getDeclaredField("renderer") + .apply { isAccessible = true } + .get(provider) + val lock = + VectorTileRenderer::class.java + .getDeclaredField("liveCalls") + .apply { isAccessible = true } + .get(renderer) as ReentrantReadWriteLock + val handle = + VectorTileRenderer::class.java + .getDeclaredField("handle") + .apply { isAccessible = true } + .get(renderer) as AtomicLong + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val reader = + Thread { + lock.readLock().lock() + try { + entered.countDown() + // Watchdog ensures a broken synchronous disposal cannot hang the test. + release.await(3, TimeUnit.SECONDS) + } finally { + lock.readLock().unlock() + } + } + reader.start() + assertTrue(entered.await(3, TimeUnit.SECONDS)) + try { + var durationMs = 0L + instrumentation.runOnMainSync { + val start = System.nanoTime() + provider.closeAsync() + provider.closeAsync() + durationMs = (System.nanoTime() - start) / 1_000_000 + } + assertTrue("UI disposal blocked for ${durationMs}ms", durationMs < 500) + assertTrue("native handle freed while a call was active", handle.get() != 0L) + assertNull(provider.geometryTiles.renderTile(TileRequest(x = 0, y = 0, z = 0))) + } finally { + release.countDown() + reader.join(4000) + } + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (handle.get() != 0L && System.nanoTime() < deadline) Thread.sleep(10) + assertEquals("native renderer was not released", 0L, handle.get()) + provider.close() + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/RenderAdmissionTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/RenderAdmissionTest.kt new file mode 100644 index 000000000..ce31dd94f --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/RenderAdmissionTest.kt @@ -0,0 +1,193 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.tileserver.TileRequest +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.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.Semaphore +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import android.graphics.BitmapFactory +import android.util.Log + +@RunWith(AndroidJUnit4::class) +class RenderAdmissionTest { + private fun asset(name: String): ByteArray = + InstrumentationRegistry + .getInstrumentation() + .context.assets + .open(name) + .use { it.readBytes() } + + private fun forestStyle( + color: String, + background: Boolean = false, + ): String = + """ + {"version":8,"sources":{"forest":{"type":"vector","tiles":["https://example.invalid/{z}/{x}/{y}.mvt"],"maxzoom":14}}, + "layers":[${if (background) """{"id":"background","type":"background","paint":{"background-color":"$color"}},""" else ""} + {"id":"forest","type":"fill","source":"forest","source-layer":"land","filter":["==","kind","forest"],"paint":{"fill-color":"$color"}}]} + """.trimIndent() + + @Test + fun complexForestUsesCpuWithoutGpuFailure() { + val tile = asset("stencil-experiment/8-226-100.mvt") + val style = forestStyle("#80a040") + VectorTileRenderer.create(style, 512).use { renderer -> + assertTrue("large visible forests must bypass triangulation", renderer.needsCpu(8, listOf(tile))) + } + VectorTileProvider + .create( + styleJson = style, + tileSize = 512, + renderScale = 1, + renderMode = VectorTileProvider.RenderMode.GPU, + fetchTile = { tile }, + ).use { provider -> + val started = System.nanoTime() + val png = provider.geometryTiles.renderTile(TileRequest(x = 226, y = 100, z = 8))!! + val elapsedMs = (System.nanoTime() - started) / 1_000_000 + val bitmap = BitmapFactory.decodeByteArray(png, 0, png.size)!! + try { + assertEquals(512, bitmap.width) + assertTrue( + (0 until 512 step 8).any { y -> + (0 until 512 step 8).any { x -> + bitmap.getPixel(x, y) ushr 24 != + 0 + } + }, + ) + } finally { + bitmap.recycle() + } + assertEquals(0L, provider.gpuRenders) + assertEquals(0L, provider.gpuFallbacks) + Log.i("RenderAdmissionTest", "complex forest CPU render=${elapsedMs}ms bytes=${png.size}") + assertTrue("complex forest stalled for ${elapsedMs}ms", elapsedMs < 5_000) + } + } + + @Test + fun forestMatchingOpaqueBackgroundNeedsNoTriangles() { + val tile = asset("stencil-experiment/8-226-100.mvt") + VectorTileRenderer.create(forestStyle("#000000", background = true), 512).use { renderer -> + TessellatedTile(renderer.tessellate(8, 226, 100, 512, tile, intArrayOf(tile.size))).use { triangles -> + assertEquals(0, triangles.vertexFloatCount) + assertNotNull(triangles.background) + } + } + } + + @Test + fun cancelledGeometryLeavesOccupiedCpuSlots() = cancelWhileSlotsOccupied("renderSlots", gpu = false, labels = false) + + @Test + fun cancelledLabelsLeaveOccupiedCpuSlots() = cancelWhileSlotsOccupied("renderSlots", gpu = false, labels = true) + + @Test + fun cancelledGeometryLeavesOccupiedPreparationSlots() = + cancelWhileSlotsOccupied("gpuPrepareSlots", gpu = true, labels = false) + + private fun cancelWhileSlotsOccupied( + field: String, + gpu: Boolean, + labels: Boolean, + ) { + val tile = asset("tile-0-0-0.pbf") + val style = asset("demo-style.json").decodeToString() + val provider = + VectorTileProvider.create( + styleJson = style, + tileSize = 256, + renderScale = 1, + renderMode = if (gpu) VectorTileProvider.RenderMode.GPU else VectorTileProvider.RenderMode.CPU, + fetchTile = { tile }, + ) + val slots = + provider.javaClass + .getDeclaredField(field) + .apply { isAccessible = true } + .get(provider) as Semaphore + val permits = slots.availablePermits() + slots.acquire(permits) + val workers = Executors.newSingleThreadExecutor() + val cancelled = AtomicBoolean(false) + val source = if (labels) provider.labelTiles else provider.geometryTiles + val request = TileRequest(x = 0, y = 0, z = 0) + try { + val result = workers.submit { source.renderTile(request) { cancelled.get() } } + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (!slots.hasQueuedThreads() && !result.isDone && System.nanoTime() < deadline) Thread.sleep(5) + assertTrue("tile never waited for $field", slots.hasQueuedThreads()) + cancelled.set(true) + assertNull("cancelled tile must return before the occupied slots open", result.get(1, TimeUnit.SECONDS)) + } finally { + slots.release(permits) + workers.shutdownNow() + assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS)) + provider.close() + } + } + + @Test + fun cancelledGpuWaiterLeavesBeforeCommittedDrawFinishes() { + val rasterizer = GpuTileRasterizer.createOrNull(256)!! + val gl = + rasterizer.javaClass + .getDeclaredField("thread") + .apply { isAccessible = true } + .get(rasterizer) as ExecutorService + val slot = + rasterizer.javaClass + .getDeclaredField("drawSlot") + .apply { isAccessible = true } + .get(rasterizer) as Semaphore + val blocked = CountDownLatch(1) + val release = CountDownLatch(1) + val workers = Executors.newFixedThreadPool(2) + val tile = asset("tile-0-0-0.pbf") + val renderer = VectorTileRenderer.create(asset("demo-style.json").decodeToString(), 256) + + fun triangles() = TessellatedTile(renderer.tessellate(0, 0, 0, 256, tile, intArrayOf(tile.size))) + try { + gl.submit { + blocked.countDown() + release.await() + } + assertTrue(blocked.await(5, TimeUnit.SECONDS)) + val owner = workers.submit { rasterizer.renderPng(triangles()) } + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (slot.availablePermits() != 0 && System.nanoTime() < deadline) Thread.sleep(5) + assertEquals(0, slot.availablePermits()) + val cancelled = AtomicBoolean(false) + val waiter = + workers.submit { + rasterizer + .renderPng(triangles(), isCancelled = { cancelled.get() }) + } + while (!slot.hasQueuedThreads() && !waiter.isDone && System.nanoTime() < deadline) Thread.sleep(5) + assertTrue(slot.hasQueuedThreads()) + cancelled.set(true) + assertNull(waiter.get(1, TimeUnit.SECONDS)) + assertTrue("committed draw must retain its tile and pixels", !owner.isDone) + release.countDown() + assertNotNull(owner.get(10, TimeUnit.SECONDS)) + assertNotNull(rasterizer.renderPng(triangles())) + } finally { + release.countDown() + workers.shutdownNow() + workers.awaitTermination(10, TimeUnit.SECONDS) + rasterizer.close() + renderer.close() + } + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/RoadResolutionExperimentTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/RoadResolutionExperimentTest.kt new file mode 100644 index 000000000..596e4a59f --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/RoadResolutionExperimentTest.kt @@ -0,0 +1,80 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.json.JSONArray +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import android.graphics.Bitmap +import android.opengl.GLES20 +import android.util.Log + +/** Same geometry, extent and style widths; only the GPU raster size changes. */ +@RunWith(AndroidJUnit4::class) +class RoadResolutionExperimentTest { + @Test + fun compareRoadRasterResolutionWithTheSameTriangles() { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val assets = instrumentation.context.assets + val folder = "road-resolution-experiment" + val style = assets.open("$folder/style.json").use { it.readBytes().decodeToString() } + val mvt = assets.open("$folder/11-1808-807.mvt").use { it.readBytes() } + val output = File(instrumentation.targetContext.getExternalFilesDir(null), folder) + output.mkdirs() + VectorTileRenderer.create(style, 512).use { native -> + val plan = JSONArray(native.plan(11, 1808, 807)) + val lengths = + IntArray(plan.length()) { + if (plan.getJSONObject(it).optBoolean("labelsOnly", false)) 0 else mvt.size + } + TessellatedTile(native.tessellate(11, 1808, 807, 512, mvt, lengths)).use { tile -> + EglOffscreen.create().use { context -> + SolidBatchRenderer().use { renderer -> + renderer.initialise() + renderer.upload(tile.packed, tile.vertexOffset, tile.vertexFloatCount) + val results = StringBuilder("ES=" + context.esVersion + "\n") + for (size in listOf(512, 1024)) { + context.prepare(size, 4) + val color = tile.background ?: floatArrayOf(0f, 0f, 0f, 0f) + + fun draw() { + context.bindDrawTarget() + renderer.clear(color[0], color[1], color[2], color[3]) + renderer.draw(tile.batches, tile.extent) + } + draw() + val pixels = context.readPixels() + assertEquals(GLES20.GL_NO_ERROR, GLES20.glGetError()) + val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) + bitmap.copyPixelsFromBuffer(pixels) + File(output, "geometry-" + size + ".png").outputStream().use { + bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) + } + bitmap.recycle() + val times = mutableListOf() + repeat(7) { + context.finish() + val start = System.nanoTime() + draw() + context.readPixels() + times.add((System.nanoTime() - start) / 1_000_000.0) + } + results + .append("size=") + .append(size) + .append(" MSAA=") + .append(context.activeSamples) + .append(" draw+resolve+read median=") + .append(times.sorted()[3]) + .append("ms\n") + } + Log.i("RoadResolutionExperiment", results.toString()) + File(output, "results.txt").writeText(results.toString()) + } + } + } + } + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/SourceTileSharingTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/SourceTileSharingTest.kt new file mode 100644 index 000000000..7cb0857ba --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/SourceTileSharingTest.kt @@ -0,0 +1,66 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.util.concurrent.CyclicBarrier +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicLong + +@RunWith(AndroidJUnit4::class) +class SourceTileSharingTest { + @Test + fun concurrentRequestsShareOneDiskReadAndOneByteArray() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val directory = File(context.cacheDir, "source-sharing-${System.nanoTime()}") + val url = "https://example.test/4/8/6.mvt" + val bytes = ByteArray(1024 * 1024) { (it % 251).toByte() } + StyleAssetCache(File(directory, "sources"), 4L * 1024 * 1024).put(url, bytes) + val networkReads = AtomicLong() + val workers = Executors.newFixedThreadPool(16) + try { + VectorTileProvider + .create( + styleJson = """{"version":8,"sources":{},"layers":[]}""", + renderMode = VectorTileProvider.RenderMode.CPU, + diskCacheDir = directory, + fetchTile = { + networkReads.incrementAndGet() + null + }, + ).use { provider -> + // Exercise only the source stage so rendering/caches cannot + // hide duplicate reads of the same source file. + val sourceTile = + VectorTileProvider::class.java + .getDeclaredMethod( + "sourceTile", String::class.java, Array::class.java, + ).apply { isAccessible = true } + val barrier = CyclicBarrier(16) + val stats = Array(7) { AtomicLong() } + val pending = + (0 until 16).map { + workers.submit { + barrier.await(10, TimeUnit.SECONDS) + sourceTile.invoke(provider, url, stats) as ByteArray? + } + } + val results = pending.map { it.get(15, TimeUnit.SECONDS) } + assertEquals("network reads for a cached source", 0L, networkReads.get()) + // STAT_DISK is the second entry in the provider's fetch stats. + android.util.Log.i("SourceTileSharingTest", "diskReads=${stats[1].get()} requests=16") + assertEquals("duplicate disk reads", 1L, stats[1].get()) + for (result in results) assertSame("source bytes were allocated again", results[0], result) + org.junit.Assert.assertArrayEquals(bytes, results[0]) + } + } finally { + workers.shutdownNow() + directory.deleteRecursively() + } + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/StreetTreeCostTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/StreetTreeCostTest.kt new file mode 100644 index 000000000..27a37a36f --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/StreetTreeCostTest.kt @@ -0,0 +1,324 @@ +package com.mapconductor.vectortile + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.marker.BitmapIcon +import com.mapconductor.core.marker.MarkerEntity +import com.mapconductor.core.marker.MarkerIconInterface +import com.mapconductor.core.marker.MarkerManager +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTileRenderer +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Test +import org.junit.runner.RunWith +import java.nio.ByteBuffer +import java.nio.ByteOrder +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint + +/** + * Tokyo's street trees: 144,183 of them, 407 species, inside a box roughly + * 0.34 by 0.27 degrees. + * + * A harder shape than the post office set this suite already measures. There + * are six times as many markers, they are packed into one metropolitan area + * rather than spread over a country, and each species draws its own icon — so + * the renderer cannot collapse two trees of different species that land on the + * same pixel. + */ +@RunWith(AndroidJUnit4::class) +class StreetTreeCostTest { + private val tileSize = 512 + + /** A small coloured dot per species, of the size a tree marker would use. */ + private class DotIcon( + private val bitmap: Bitmap, + private val sizePx: Float, + ) : MarkerIconInterface { + override val scale: Float = 1.0f + override val anchor: Offset = Offset(0.5f, 0.5f) + override val iconSize: Dp = sizePx.dp + override val infoAnchor: Offset = Offset(0.5f, 0.0f) + override val debug: Boolean = false + + // A pre-baked bitmap, so nothing is rasterised per marker: the point of + // the measurement is the drawing, not icon generation. + private val icon = + BitmapIcon( + bitmap = bitmap, + size = Size(sizePx, sizePx), + anchor = anchor, + ) + + override fun toBitmapIcon(): BitmapIcon = icon + } + + private fun speciesIcons( + count: Int, + sizePx: Int, + ): List { + val paint = Paint(Paint.ANTI_ALIAS_FLAG) + return (0 until count).map { index -> + // Golden-angle hue rotation, so neighbouring species indices do not + // come out as neighbouring colours. + val hue = (index * 137.508f) % 360f + val colour = Color.HSVToColor(floatArrayOf(hue, 0.72f, 0.85f)) + val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888) + Canvas(bitmap).apply { + paint.color = colour + drawCircle(sizePx / 2f, sizePx / 2f, sizePx / 2f - 1f, paint) + paint.color = Color.argb(90, 0, 0, 0) + paint.style = Paint.Style.STROKE + paint.strokeWidth = 1f + drawCircle(sizePx / 2f, sizePx / 2f, sizePx / 2f - 1f, paint) + paint.style = Paint.Style.FILL + } + DotIcon(bitmap, sizePx.toFloat()) + } + } + + private class Trees( + val manager: MarkerManager, + val count: Int, + val species: Int, + ) + + private fun loadTrees( + iconPx: Int, + minMarkerCount: Int = 1, + keepEvery: Int = 1, + ): Trees { + val bytes = + InstrumentationRegistry + .getInstrumentation() + .context.assets + .open("tokyo-trees.bin") + .use { it.readBytes() } + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + + // The magic is checked, not skipped. Read past it and the header + // becomes a species count of over a billion, and the icon palette + // allocates until the process aborts — which is what happened, twice, + // after the asset gained its attribute columns. + val magic = ByteArray(5) + buffer.get(magic) + check(String(magic, Charsets.US_ASCII) == "TREE\u0002") { + "unexpected street tree asset format" + } + + // The length has to be read into a local first: buffer.short advances + // the position itself, so reading it inside position(position() + ...) + // captures the offset from before the read and loses two bytes a name. + fun skipName() { + val length = buffer.short.toInt() + buffer.position(buffer.position() + length) + } + + fun skipTable() = repeat(buffer.int) { skipName() } + + val speciesCount = buffer.int + repeat(speciesCount) { skipName() } + skipTable() // wards + skipTable() // roads + val icons = speciesIcons(speciesCount, iconPx) + + val treeCount = buffer.int + val manager = MarkerManager.defaultManager(minMarkerCount = minMarkerCount) + var kept = 0 + repeat(treeCount) { index -> + // Every field is read even when the tree is skipped: the record is + // fixed width, and leaving four of them unread walks the buffer + // ten bytes off per tree until the coordinates are noise. + val lat = buffer.float.toDouble() + val lon = buffer.float.toDouble() + val species = buffer.short.toInt() and 0xFFFF + buffer.float // height + buffer.short // girth + buffer.short // ward + buffer.short // road + if (index % keepEvery != 0) return@repeat + kept++ + manager.registerEntity( + MarkerEntity( + marker = null, + state = MarkerState(position = GeoPoint(lat, lon), icon = icons[species]), + visible = true, + isRendered = true, + tiling = true, + ), + ) + } + return Trees(manager, kept, speciesCount) + } + + private fun median(values: List): Double = values.sorted()[values.size / 2] + + @Test + fun rendersTokyoStreetTrees() { + val loadStarted = System.nanoTime() + val trees = loadTrees(iconPx = 14) + val loadMs = (System.nanoTime() - loadStarted) / 1_000_000.0 + println("TREES loaded=%d species=%d load=%.0fms".format(trees.count, trees.species, loadMs)) + measure(trees, declutterPx = 0) + measure(trees, declutterPx = 14) + } + + /** + * Where a tile's milliseconds actually go: query, encode, and the rest. + * + * The sweep above gives one number a tile, which is enough to see a change + * and useless for deciding what to change. The first cut of this test + * measured `Bitmap.compress` and called it the encode cost — 140 ms a tile, + * a third of the total — when the renderer tries the Rust encoder first and + * only falls back to compress if the native library is missing. Both are + * measured here for that reason: the fallback's cost is worth knowing, but + * it is not what the renderer pays. + */ + @Test + fun tileCostBreakdown() { + val trees = loadTrees(iconPx = 14) + val renderer = + MarkerTileRenderer( + markerManager = trees.manager, + tileSize = tileSize, + cacheSizeBytes = 8 * 1024 * 1024, + declutterPx = 14, + ) + for ((z, x, y) in listOf(Triple(9, 454, 201), Triple(11, 1818, 806), Triple(12, 3637, 1612))) { + val n = 1 shl z + + fun lon(px: Int) = px.toDouble() / n * 360.0 - 180.0 + + fun lat(px: Int): Double { + val t = Math.PI * (1 - 2.0 * px / n) + return Math.toDegrees(Math.atan(Math.sinh(t))) + } + val bounds = + com.mapconductor.core.features.GeoRectBounds( + southWest = + com.mapconductor.core.features.GeoPoint + .fromLatLong(lat(y + 1), lon(x)), + northEast = + com.mapconductor.core.features.GeoPoint + .fromLatLong(lat(y), lon(x + 1)), + ) + + // What a full bounds query costs, for reference. It is not + // necessarily what the renderer pays: when decluttering is on and + // the index's cells are fine enough, the renderer asks for one + // marker per cell instead and never reads the rest. Subtracting + // this from the total used to give a "rest" column, which went + // negative the moment that became true. + var candidates = 0 + val query = + (0 until 5) + .map { + val t0 = System.nanoTime() + candidates = trees.manager.findMarkersInBounds(bounds).size + (System.nanoTime() - t0) / 1_000_000.0 + }.sorted()[2] + + // A neighbouring tile first, untimed and never measured. + // + // The renderer learns the largest icon extent it has had to draw + // and widens its query padding to match, so the first tile any + // renderer produces runs query and prepare twice. Sharing one + // renderer across the zooms hid that: whichever tile went first + // paid for the rest, and a change that altered which markers the + // first tile saw moved a 500 ms retry onto a later zoom and read + // as a regression there. Warming on a neighbour costs one tile and + // makes each zoom's number its own. + renderer.renderTile(TileRequest(x = x + 1, y = y, z = z)) + + val t1 = System.nanoTime() + val png = renderer.renderTile(TileRequest(x = x, y = y, z = z))!! + val total = (System.nanoTime() - t1) / 1_000_000.0 + + val decoded = BitmapFactory.decodeByteArray(png, 0, png.size) + val compress = + (0 until 3) + .map { + val t2 = System.nanoTime() + java.io.ByteArrayOutputStream().use { + decoded.compress(Bitmap.CompressFormat.PNG, 100, it) + } + (System.nanoTime() - t2) / 1_000_000.0 + }.sorted()[1] + + // What the renderer actually pays: it tries Rust first and only + // falls back to compress if the native library is missing. + var rustBytes = 0 + val rust = + (0 until 3) + .map { + val t3 = System.nanoTime() + rustBytes = com.mapconductor.core.tileserver.TilePngEncoder + .encode(decoded) + ?.size ?: -1 + (System.nanoTime() - t3) / 1_000_000.0 + }.sorted()[1] + + println( + ( + "BREAKDOWN z=%d tile=%dpx candidates=%d total=%.0fms scanQuery=%.1fms " + + "rust=%.0fms(%dB) compress=%.0fms" + ).format( + z, decoded.width, candidates, total, query, rust, rustBytes, compress, + ), + ) + decoded.recycle() + } + } + + /** Reports per-tile cost across zooms, with and without decluttering. */ + private fun measure( + trees: Trees, + declutterPx: Int, + ) { + // One renderer for the sweep. Each zoom asks for a different tile and + // the cache is keyed by z/x/y, so it never answers from cache — and a + // renderer per round kept a tile-sized bitmap and its own pool alive + // until native allocation failed inside Canvas::create_canvas. + val renderer = + MarkerTileRenderer( + markerManager = trees.manager, + tileSize = tileSize, + cacheSizeBytes = 8 * 1024 * 1024, + declutterPx = declutterPx, + ) + + // Tiles covering Tokyo from "the whole city on one tile" down to a + // street-level view, so the cost can be seen against tile density. + for ((z, x, y) in listOf( + Triple(9, 454, 201), + Triple(11, 1818, 806), + Triple(12, 3637, 1612), + Triple(14, 14551, 6451), + )) { + val started = System.nanoTime() + val bytes = renderer.renderTile(TileRequest(x = x, y = y, z = z)) + val elapsed = (System.nanoTime() - started) / 1_000_000.0 + + val png = bytes + if (png == null) { + println("TREES z=%d EMPTY".format(z)) + continue + } + val decoded = BitmapFactory.decodeByteArray(png, 0, png.size) + println( + "TREES declutter=%d z=%d render=%.0fms png=%dKB tile=%dpx".format( + declutterPx, z, elapsed, png.size / 1024, decoded.width, + ), + ) + decoded.recycle() + } + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/StyleAssetCacheTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/StyleAssetCacheTest.kt new file mode 100644 index 000000000..b96f289ff --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/StyleAssetCacheTest.kt @@ -0,0 +1,90 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +@RunWith(AndroidJUnit4::class) +class StyleAssetCacheTest { + private lateinit var directory: File + + @Before + fun setUp() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + directory = File(context.cacheDir, "glyph-cache-test-${System.nanoTime()}") + directory.mkdirs() + } + + private fun cache(budgetBytes: Long = 1L * 1024 * 1024) = StyleAssetCache(directory, budgetBytes) + + @Test + fun returnsWhatItWasGiven() { + val subject = cache() + val url = "https://example.test/font/0-255.pbf" + assertNull(subject.get(url)) + + subject.put(url, byteArrayOf(1, 2, 3, 4)) + assertArrayEquals(byteArrayOf(1, 2, 3, 4), subject.get(url)) + assertNull(subject.get("https://example.test/font/256-511.pbf")) + } + + /** + * The point of the cache: a new process knows nothing about which ranges + * it wants until it has drawn a tile, so a warm start has to be able to + * hand back everything without being asked for it by name. + */ + @Test + fun handsBackEveryStoredRangeWithoutBeingAskedForOne() { + val subject = cache() + val stored = (0 until 5).map { "https://example.test/font/$it.pbf" to byteArrayOf(it.toByte()) } + stored.forEach { (url, bytes) -> subject.put(url, bytes) } + + val seen = mutableListOf() + val loaded = StyleAssetCache(directory, 1L * 1024 * 1024).warm { seen.add(it[0]) } + + assertEquals(5, loaded) + assertEquals(stored.map { it.second[0] }.toSet(), seen.toSet()) + } + + /** A range that will not parse must not stop the rest from loading. */ + @Test + fun keepsGoingWhenOneRangeIsRejected() { + val subject = cache() + repeat(4) { subject.put("https://example.test/font/$it.pbf", byteArrayOf(it.toByte())) } + + var seen = 0 + val loaded = + StyleAssetCache(directory, 1L * 1024 * 1024).warm { + seen++ + if (seen == 2) throw IllegalStateException("range would not parse") + } + + assertEquals(4, seen) + assertEquals(3, loaded) + } + + /** + * The budget has to be generous enough to hold what the next launch will + * ask for -- an 8MB one dropped 26 of Tokyo's 69 ranges and the map went + * back to fetching them -- but it still has to bound the directory. + */ + @Test + fun staysWithinItsBudget() { + // Sweeps run every 16 writes, so 32 of these cross the budget twice. + val subject = StyleAssetCache(directory, 64L * 1024) + repeat(32) { index -> + subject.put("https://example.test/font/$index.pbf", ByteArray(8 * 1024) { index.toByte() }) + } + + val total = directory.listFiles().orEmpty().sumOf { it.length() } + assertTrue("directory grew to $total bytes, past its 64KB budget", total <= 64L * 1024) + assertTrue("the sweep emptied the directory instead of trimming it", total > 0) + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/TileDiskCacheTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/TileDiskCacheTest.kt new file mode 100644 index 000000000..f11e73982 --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/TileDiskCacheTest.kt @@ -0,0 +1,115 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.tileserver.TileRequest +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +/** + * The disk cache exists to survive process death: within a session the map SDK + * already caches raster tiles. These tests cover the part that matters — that a + * second provider over the same directory serves without rendering, and that a + * restyle does not serve stale pixels. + */ +@RunWith(AndroidJUnit4::class) +class TileDiskCacheTest { + private lateinit var directory: File + private lateinit var styleJson: String + private lateinit var tileBytes: ByteArray + + @Before + fun setUp() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + directory = File(context.cacheDir, "vectortile-test-${System.nanoTime()}") + val assets = InstrumentationRegistry.getInstrumentation().context.assets + styleJson = assets.open("demo-style.json").use { it.readBytes().decodeToString() } + tileBytes = assets.open("tile-0-0-0.pbf").use { it.readBytes() } + } + + @After + fun tearDown() { + directory.deleteRecursively() + } + + private fun provider(fetches: IntArray) = + VectorTileProvider.create( + styleJson = styleJson, + tileSize = 256, + diskCacheDir = directory, + fetchTile = { + fetches[0]++ + tileBytes + }, + ) + + @Test + fun aSecondProviderServesFromDiskWithoutFetchingOrRendering() { + val first = IntArray(1) + val cold = provider(first).use { it.renderTile(TileRequest(x = 0, y = 0, z = 0)) } + assertNotNull(cold) + assertTrue("expected a fetch on the cold path", first[0] > 0) + + // A brand new provider, same directory: this is the app-restart case. + val second = IntArray(1) + val warm = provider(second).use { it.renderTile(TileRequest(x = 0, y = 0, z = 0)) } + + assertArrayEquals("cached bytes must match", cold, warm) + assertEquals("nothing should have been fetched", 0, second[0]) + } + + @Test + fun restylingDoesNotServeStalePixels() { + val fetches = IntArray(1) + provider(fetches).use { subject -> + val before = subject.renderTile(TileRequest(x = 0, y = 0, z = 0))!! + + subject.setStyle( + """ + {"version":8,"sources":{},"layers":[ + {"id":"bg","type":"background","paint":{"background-color":"#ff0000"}} + ]} + """.trimIndent(), + ) + val after = subject.renderTile(TileRequest(x = 0, y = 0, z = 0))!! + + // Entries are keyed by style, so the old tile is simply not found. + assertTrue("restyle must not return the cached tile", !before.contentEquals(after)) + } + } + + @Test + fun cachedTilesLandInTheGivenDirectory() { + provider(IntArray(1)).use { it.renderTile(TileRequest(x = 0, y = 0, z = 0)) } + val files = directory.listFiles()?.filter { it.isFile }.orEmpty() + assertEquals(1, files.size) + assertTrue("cached tile should be a real PNG", files[0].length() > 1_000) + } + + @Test + fun evictionKeepsTheDirectoryWithinBudget() { + // A one-byte budget: every sweep should leave essentially nothing. + val cache = TileDiskCache(directory, budgetBytes = 1) + val payload = ByteArray(4096) { 7 } + repeat(40) { cache.put("key-$it", payload) } + + val total = directory.listFiles()?.sumOf { it.length() } ?: 0 + assertTrue("expected eviction, directory holds $total bytes", total < 40L * 4096) + } + + @Test + fun missingEntriesReturnNull() { + val cache = TileDiskCache(directory, budgetBytes = 1024) + assertNull(cache.get("nothing-here")) + cache.put("a", byteArrayOf(1, 2, 3)) + assertArrayEquals(byteArrayOf(1, 2, 3), cache.get("a")) + } +} diff --git a/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/VectorTileProviderTest.kt b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/VectorTileProviderTest.kt new file mode 100644 index 000000000..c872a3c56 --- /dev/null +++ b/android-vectortile/src/androidTest/java/com/mapconductor/vectortile/VectorTileProviderTest.kt @@ -0,0 +1,252 @@ +package com.mapconductor.vectortile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.tileserver.TileRequest +import com.mapconductor.core.tileserver.TileServerRegistry +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.net.HttpURLConnection +import java.net.URL +import android.graphics.BitmapFactory + +/** + * Exercises the path a map backend actually takes: provider -> + * `LocalTileServer` route -> URL template -> HTTP -> PNG. + * + * Source tiles come from a bundled asset rather than the network, so the test + * measures the SDK plumbing and not connectivity. + */ +@RunWith(AndroidJUnit4::class) +class VectorTileProviderTest { + private lateinit var styleJson: String + private lateinit var tileBytes: ByteArray + private var provider: VectorTileProvider? = null + private val routeId = "vectortile-test" + + @Before + fun setUp() { + val assets = InstrumentationRegistry.getInstrumentation().context.assets + styleJson = assets.open("demo-style.json").use { it.readBytes().decodeToString() } + tileBytes = assets.open("tile-0-0-0.pbf").use { it.readBytes() } + provider = + VectorTileProvider.create( + styleJson = styleJson, + tileSize = 512, + // Pinned rather than left to the display: the image is this + // times the scale, and the suite runs on whatever device is + // attached. What is under test here is the route, not the grain. + renderScale = 1, + // Serve the bundled tile for whatever the plan asks for. + fetchTile = { tileBytes }, + ) + } + + @After + fun tearDown() { + TileServerRegistry.get().unregister(routeId) + provider?.close() + } + + /** + * A map that has moved on closes the connection, and the tile it no longer + * wants must not be drawn: the render slots and the GL thread are shared, + * so a doomed tile is drawn *instead of* one that is still on screen. + */ + @Test + fun givesUpOnATileTheMapNoLongerWants() { + val subject = provider!! + assertEquals(null, subject.renderTile(TileRequest(x = 0, y = 0, z = 0)) { true }) + + // Cancelled means not drawn, not merely not returned -- the same tile + // must still be renderable afterwards, from scratch rather than from a + // cache entry the cancelled call left behind. + assertNotNull(subject.renderTile(TileRequest(x = 0, y = 0, z = 0)) { false }) + } + + /** + * The sprite is the one style asset whose location is known before a tile + * is drawn, so it goes through the renderer rather than through a tile's + * demands -- and the whole point of it is that icons draw at all. + */ + @Test + fun takesASpriteSheetAndReportsWhenItStillNeedsOne() { + val subject = + VectorTileRenderer.create( + """ + { + "version": 8, + "sprite": [{ "id": "basics", "url": "https://example.test/sprites/basics" }], + "sources": {}, + "layers": [] + } + """.trimIndent(), + VectorTileProvider.DEFAULT_TILE_SIZE, + ) + subject.use { + assertEquals( + listOf( + "https://example.test/sprites/basics.json", + "https://example.test/sprites/basics.png", + ), + it.spriteUrls(1), + ) + assertEquals( + listOf( + "https://example.test/sprites/basics@2x.json", + "https://example.test/sprites/basics@2x.png", + ), + it.spriteUrls(2), + ) + assertTrue("the style names a sprite", it.needsSprite()) + + val sheet = android.graphics.Bitmap.createBitmap(8, 8, android.graphics.Bitmap.Config.ARGB_8888) + sheet.eraseColor(android.graphics.Color.BLACK) + val png = java.io.ByteArrayOutputStream() + sheet.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, png) + + val icons = + it.addSprite( + """{"icon-atm": {"x": 0, "y": 0, "width": 8, "height": 8, "pixelRatio": 1}}""", + png.toByteArray(), + ) + assertEquals(1, icons) + assertTrue("the sheet is in", !it.needsSprite()) + } + } + + /** A cancellation that arrives after the work is done still returns it. */ + @Test + fun keepsATileWhoseCancellationCameTooLate() { + val subject = provider!! + var calls = 0 + // False for every checkpoint, true only afterwards. + val png = subject.renderTile(TileRequest(x = 0, y = 0, z = 0)) { calls++ > 100 } + assertNotNull(png) + assertTrue("no cancellation checkpoints were reached", calls > 0) + } + + @Test + fun servesAPngThroughTheLocalTileServer() { + val server = TileServerRegistry.get() + server.register(routeId, provider!!) + + val template = server.urlTemplate(routeId, 512) + assertTrue("unexpected template: $template", template.contains("/tiles/$routeId/512/")) + + val url = + template + .replace("{z}", "0") + .replace("{x}", "0") + .replace("{y}", "0") + + val connection = URL(url).openConnection() as HttpURLConnection + val png = + try { + assertEquals(200, connection.responseCode) + connection.inputStream.use { it.readBytes() } + } finally { + connection.disconnect() + } + + assertTrue("expected a real PNG, got ${png.size} bytes", png.size > 10_000) + val bitmap = BitmapFactory.decodeByteArray(png, 0, png.size) + assertNotNull("tile did not decode", bitmap) + assertEquals(512, bitmap.width) + + // The demo style paints an opaque background everywhere; a blank + // response would fail this. + var distinct = HashSet() + for (y in 0 until 512 step 8) { + for (x in 0 until 512 step 8) distinct.add(bitmap.getPixel(x, y)) + } + assertTrue("expected varied colours, got ${distinct.size}", distinct.size > 10) + } + + @Test + fun rendersDirectlyThroughTheProviderInterface() { + val png = provider!!.renderTile(TileRequest(x = 0, y = 0, z = 0)) + assertNotNull(png) + assertTrue(png!!.size > 10_000) + } + + @Test + fun reportsStyleDiagnostics() { + // Point labels are drawn now, so a style made of them has nothing to + // report. This test asserted the opposite -- that symbol layers were + // not drawn -- and went on passing after that stopped being true, + // because the message it looked for merely had to contain "symbol". + assertEquals(emptyList(), provider!!.diagnostics()) + + provider!!.setStyle( + """ + { + "version": 8, + "sources": { "src": { "type": "vector", "url": "mapbox://styles" } }, + "layers": [ + { "id": "hills", "type": "hillshade", "source": "src" }, + { "id": "orphan", "type": "fill", "source": "missing", "source-layer": "x" } + ] + } + """.trimIndent(), + ) + + val messages = provider!!.diagnostics() + assertTrue( + "expected the undrawable layer type to be reported, got $messages", + messages.any { it.contains("hillshade") }, + ) + assertTrue( + "expected the missing source to be reported, got $messages", + messages.any { it.contains("orphan") && it.contains("missing") }, + ) + assertTrue( + "expected the unfetchable source URL to be reported, got $messages", + messages.any { it.contains("mapbox:") }, + ) + } + + @Test + fun restylingChangesOutputWithoutRefetching() { + var fetches = 0 + val subject = + VectorTileProvider.create( + styleJson = styleJson, + tileSize = 256, + fetchTile = { + fetches += 1 + tileBytes + }, + ) + subject.use { + val before = it.renderTile(TileRequest(x = 0, y = 0, z = 0))!! + val afterFirstRender = fetches + + it.setStyle( + """ + {"version":8,"sources":{},"layers":[ + {"id":"bg","type":"background","paint":{"background-color":"#ff0000"}} + ]} + """.trimIndent(), + ) + val after = it.renderTile(TileRequest(x = 0, y = 0, z = 0))!! + + assertTrue("restyle should change the pixels", !before.contentEquals(after)) + // Geometry is unchanged, so the cache serves the second render. + assertEquals(afterFirstRender, fetches) + } + } + + @Test + fun closedProviderStopsServing() { + val subject = VectorTileProvider.create(styleJson, fetchTile = { tileBytes }) + subject.close() + subject.close() + assertEquals(null, subject.renderTile(TileRequest(x = 0, y = 0, z = 0))) + } +} diff --git a/android-vectortile/src/androidTest/res/xml/network_security_config.xml b/android-vectortile/src/androidTest/res/xml/network_security_config.xml new file mode 100644 index 000000000..f82269d45 --- /dev/null +++ b/android-vectortile/src/androidTest/res/xml/network_security_config.xml @@ -0,0 +1,12 @@ + + + + + 127.0.0.1 + localhost + + diff --git a/android-vectortile/src/main/AndroidManifest.xml b/android-vectortile/src/main/AndroidManifest.xml new file mode 100644 index 000000000..dd059794a --- /dev/null +++ b/android-vectortile/src/main/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/CancellableRenderGate.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/CancellableRenderGate.kt new file mode 100644 index 000000000..3ce504f5d --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/CancellableRenderGate.kt @@ -0,0 +1,22 @@ +package com.mapconductor.vectortile + +import com.mapconductor.core.InternalMapConductorApi +import java.util.concurrent.Semaphore +import java.util.concurrent.TimeUnit + +/** A cancelled tile must release its worker before an occupied render slot opens. */ +@InternalMapConductorApi +internal fun Semaphore.acquireUnlessCancelled(isCancelled: () -> Boolean): Boolean { + try { + while (!isCancelled()) { + if (tryAcquire(10, TimeUnit.MILLISECONDS)) { + if (!isCancelled()) return true + release() + return false + } + } + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + } + return false +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/EglOffscreen.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/EglOffscreen.kt new file mode 100644 index 000000000..5611e9f56 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/EglOffscreen.kt @@ -0,0 +1,278 @@ +package com.mapconductor.vectortile + +import java.io.Closeable +import java.nio.ByteBuffer +import java.nio.ByteOrder +import android.opengl.EGL14 +import android.opengl.EGLConfig +import android.opengl.EGLContext +import android.opengl.EGLDisplay +import android.opengl.EGLSurface +import android.opengl.GLES20 +import android.opengl.GLES30 + +/** + * A headless OpenGL ES context rendering into an off-screen framebuffer. + * + * There is no window and no `SurfaceView`: tiles are produced on a worker + * thread and handed back as bytes, so the context is created against a 1x1 + * pbuffer purely to have something current, and all drawing goes to an FBO + * whose size is chosen per tile. + * + * The earlier `tile_renderer` prototype did this with GLFW, which does not + * exist on Android — hence EGL directly. + */ +internal class EglOffscreen private constructor( + private val display: EGLDisplay, + private val context: EGLContext, + private val surface: EGLSurface, + /** 3 when an ES3 context was obtained, otherwise 2. */ + val esVersion: Int, +) : Closeable { + private var framebuffer = 0 + private var colorTexture = 0 + private var depthBuffer = 0 + private var msaaFramebuffer = 0 + private var msaaColor = 0 + private var width = 0 + private var height = 0 + private var samples = 0 + + /** Multisample count actually in use; 0 when unavailable. */ + val activeSamples: Int get() = samples + + companion object { + /** + * Creates a context, preferring ES3. + * + * ES3 matters for two things here: multisampled renderbuffers with + * `glBlitFramebuffer`, and instancing. ES2 works but loses MSAA unless + * the driver exposes `EXT_multisampled_render_to_texture`. + */ + fun create(preferEs3: Boolean = true): EglOffscreen { + val display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY) + check(display != EGL14.EGL_NO_DISPLAY) { "no EGL display" } + + val version = IntArray(2) + check(EGL14.eglInitialize(display, version, 0, version, 1)) { "eglInitialize failed" } + + for (clientVersion in if (preferEs3) intArrayOf(3, 2) else intArrayOf(2)) { + val renderable = + if (clientVersion == 3) EGLExt.EGL_OPENGL_ES3_BIT else EGL14.EGL_OPENGL_ES2_BIT + val config = chooseConfig(display, renderable) ?: continue + + val context = + EGL14.eglCreateContext( + display, + config, + EGL14.EGL_NO_CONTEXT, + intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, clientVersion, EGL14.EGL_NONE), + 0, + ) + if (context == EGL14.EGL_NO_CONTEXT) continue + + // A minimal pbuffer: nothing is drawn to it, but a context + // needs a current surface before any GL call is legal. + val surface = + EGL14.eglCreatePbufferSurface( + display, + config, + intArrayOf(EGL14.EGL_WIDTH, 1, EGL14.EGL_HEIGHT, 1, EGL14.EGL_NONE), + 0, + ) + if (surface == EGL14.EGL_NO_SURFACE) { + EGL14.eglDestroyContext(display, context) + continue + } + check(EGL14.eglMakeCurrent(display, surface, surface, context)) { + "eglMakeCurrent failed" + } + return EglOffscreen(display, context, surface, clientVersion) + } + error("could not create an ES3 or ES2 context") + } + + private fun chooseConfig( + display: EGLDisplay, + renderableType: Int, + ): EGLConfig? { + val attributes = + intArrayOf( + EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT, + EGL14.EGL_RENDERABLE_TYPE, renderableType, + EGL14.EGL_RED_SIZE, 8, + EGL14.EGL_GREEN_SIZE, 8, + EGL14.EGL_BLUE_SIZE, 8, + EGL14.EGL_ALPHA_SIZE, 8, + EGL14.EGL_NONE, + ) + val configs = arrayOfNulls(1) + val count = IntArray(1) + if (!EGL14.eglChooseConfig(display, attributes, 0, configs, 0, 1, count, 0)) return null + if (count[0] < 1) return null + return configs[0] + } + } + + /** ES3's `EGL_OPENGL_ES3_BIT_KHR`, which EGL14 does not expose. */ + private object EGLExt { + const val EGL_OPENGL_ES3_BIT = 0x0040 + } + + /** + * Prepares an FBO of the given size, reusing it when the size is unchanged. + * + * @param requestedSamples MSAA samples to attempt. Vector tiles look bad + * without anti-aliasing, and MSAA is the cheap way to get it on a GPU; + * it is silently dropped when unsupported. + */ + fun prepare( + size: Int, + requestedSamples: Int = 4, + ) { + if (size == width && size == height && requestedSamples == samples) return + releaseFramebuffers() + + width = size + height = size + + val ids = IntArray(1) + GLES20.glGenTextures(1, ids, 0) + colorTexture = ids[0] + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, colorTexture) + GLES20.glTexImage2D( + GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, size, size, 0, + GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null, + ) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR) + + GLES20.glGenFramebuffers(1, ids, 0) + framebuffer = ids[0] + GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebuffer) + GLES20.glFramebufferTexture2D( + GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, + GLES20.GL_TEXTURE_2D, colorTexture, 0, + ) + check( + GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER) == + GLES20.GL_FRAMEBUFFER_COMPLETE, + ) { "resolve framebuffer incomplete" } + + samples = 0 + if (esVersion >= 3 && requestedSamples > 1) { + val maxSamples = IntArray(1) + GLES30.glGetIntegerv(GLES30.GL_MAX_SAMPLES, maxSamples, 0) + val use = minOf(requestedSamples, maxSamples[0]) + if (use > 1) { + GLES20.glGenRenderbuffers(1, ids, 0) + msaaColor = ids[0] + GLES20.glBindRenderbuffer(GLES20.GL_RENDERBUFFER, msaaColor) + GLES30.glRenderbufferStorageMultisample( + GLES20.GL_RENDERBUFFER, use, GLES30.GL_RGBA8, size, size, + ) + GLES20.glGenFramebuffers(1, ids, 0) + msaaFramebuffer = ids[0] + GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, msaaFramebuffer) + GLES20.glFramebufferRenderbuffer( + GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, + GLES20.GL_RENDERBUFFER, msaaColor, + ) + if (GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER) == + GLES20.GL_FRAMEBUFFER_COMPLETE + ) { + samples = use + } else { + releaseMsaa() + } + } + } + bindDrawTarget() + } + + /** Binds whichever framebuffer drawing should go to. */ + fun bindDrawTarget() { + GLES20.glBindFramebuffer( + GLES20.GL_FRAMEBUFFER, + if (samples > 0) msaaFramebuffer else framebuffer, + ) + GLES20.glViewport(0, 0, width, height) + } + + /** Resolves MSAA into the readable framebuffer, if MSAA is in use. */ + fun resolve() { + if (samples == 0) return + GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, msaaFramebuffer) + GLES30.glBindFramebuffer(GLES30.GL_DRAW_FRAMEBUFFER, framebuffer) + GLES30.glBlitFramebuffer( + 0, 0, width, height, 0, 0, width, height, + GLES20.GL_COLOR_BUFFER_BIT, GLES20.GL_NEAREST, + ) + GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebuffer) + } + + /** + * Reads the framebuffer back to the CPU. + * + * This is the step that decides whether GPU rasterisation is worth it at + * all: it stalls the pipeline, and on some drivers it is slow enough to + * erase any gain from drawing faster. Hence it is measured separately. + */ + fun readPixels(into: ByteBuffer? = null): ByteBuffer { + resolve() + val buffer = + into ?: ByteBuffer + .allocateDirect(width * height * 4) + .order(ByteOrder.nativeOrder()) + buffer.rewind() + GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebuffer) + GLES20.glReadPixels( + 0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer, + ) + buffer.rewind() + return buffer + } + + /** Blocks until every issued command has completed. */ + fun finish() = GLES20.glFinish() + + private fun releaseMsaa() { + if (msaaFramebuffer != 0) { + GLES20.glDeleteFramebuffers(1, intArrayOf(msaaFramebuffer), 0) + msaaFramebuffer = 0 + } + if (msaaColor != 0) { + GLES20.glDeleteRenderbuffers(1, intArrayOf(msaaColor), 0) + msaaColor = 0 + } + samples = 0 + } + + private fun releaseFramebuffers() { + releaseMsaa() + if (framebuffer != 0) { + GLES20.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0) + framebuffer = 0 + } + if (colorTexture != 0) { + GLES20.glDeleteTextures(1, intArrayOf(colorTexture), 0) + colorTexture = 0 + } + if (depthBuffer != 0) { + GLES20.glDeleteRenderbuffers(1, intArrayOf(depthBuffer), 0) + depthBuffer = 0 + } + width = 0 + height = 0 + } + + override fun close() { + releaseFramebuffers() + EGL14.eglMakeCurrent( + display, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT, + ) + EGL14.eglDestroySurface(display, surface) + EGL14.eglDestroyContext(display, context) + EGL14.eglTerminate(display) + } +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/GpuTileRasterizer.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/GpuTileRasterizer.kt new file mode 100644 index 000000000..3d9b684f5 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/GpuTileRasterizer.kt @@ -0,0 +1,268 @@ +package com.mapconductor.vectortile + +import com.mapconductor.core.tileserver.TilePngEncoder +import java.io.Closeable +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.concurrent.Callable +import java.util.concurrent.ExecutionException +import java.util.concurrent.Executors +import java.util.concurrent.Future +import java.util.concurrent.Semaphore +import android.util.Log + +/** + * Rasterises triangulated tiles on the GPU. + * + * **The GL calls run on one dedicated thread**, because an EGL context belongs + * to the thread that made it current. The tile server calls `renderTile` from + * a pool of eight workers, so those calls are marshalled onto this thread and + * the caller blocks. That is the right shape for the drawing itself: it takes + * about 15 ms and the GPU is a single resource anyway. + * + * Everything after the readback is deliberately *not* on that thread. Labels + * are drawn on the CPU over the pixels and the PNG is encoded from them, and + * both used to run on the GL thread, where they serialised: measured on a + * Pixel 5a they are 30 to 130 ms a tile, so eight workers spent their time + * queueing behind one another for work that has nothing to do with the GPU. + * + * Creating the context is the expensive part (~15 ms), so it is created once + * on first use and kept. + */ +internal class GpuTileRasterizer( + private val tileSize: Int, +) : Closeable { + private val thread = + Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "vectortile-gl").apply { isDaemon = true } + } + + /** Readback/encoder buffers, one per worker that might be encoding. */ + private val pixelBuffers = java.util.concurrent.ArrayBlockingQueue(8) + private val drawSlot = Semaphore(1, true) + + private var egl: EglOffscreen? = null + private var renderer: SolidBatchRenderer? = null + + @Volatile + private var closed = false + + companion object { + private const val TAG = "VectorTileGpu" + + /** + * Creates a rasteriser, or null when this device cannot give us an + * off-screen GL context. + * + * Probing here rather than at first tile means the provider can fall + * back to the CPU before anything is served, instead of failing tiles + * one by one. + */ + fun createOrNull(tileSize: Int): GpuTileRasterizer? { + val candidate = GpuTileRasterizer(tileSize) + val ready = + try { + candidate.thread.submit(Callable { candidate.initialise() }).get() + } catch (error: Exception) { + Log.w(TAG, "no GL context available", error) + false + } + if (ready) return candidate + candidate.close() + return null + } + } + + /** Runs on the GL thread. */ + private fun initialise(): Boolean = + try { + val context = EglOffscreen.create() + context.prepare(tileSize) + val batch = SolidBatchRenderer() + batch.initialise() + egl = context + renderer = batch + true + } catch (error: Throwable) { + Log.w(TAG, "GL initialisation failed", error) + false + } + + /** Describes the context in use, for diagnostics. */ + fun describe(): String = + try { + thread + .submit( + Callable { + val context = egl + if (context == null) "unavailable" else "ES${context.esVersion} MSAA x${context.activeSamples}" + }, + ).get() + } catch (error: Exception) { + "unavailable" + } + + /** + * Draws [tile] and returns PNG bytes, or null if the GPU path failed. + * + * Encoding happens in Rust against the readback buffer directly: the + * platform encoder costs more than the entire rest of the GPU path. + * + * @param decorate given the readback in RGBA, before it is encoded. Used + * to draw labels, which the tessellator does not produce. Runs on the + * calling worker after the readback has been copied out. + */ + fun renderPng( + tile: TessellatedTile, + decorate: ((ByteArray) -> Unit)? = null, + ): ByteArray? = renderPng(tile, decorate) { false } + + internal fun renderPng( + tile: TessellatedTile, + decorate: ((ByteArray) -> Unit)? = null, + isCancelled: () -> Boolean, + ): ByteArray? { + if (closed || isCancelled()) { + tile.close() + return null + } + return try { + val pixels = + pixelBuffers.poll() + ?: ByteBuffer + .allocateDirect(tileSize * tileSize * 4) + .order(ByteOrder.nativeOrder()) + try { + val submitted = System.nanoTime() + if (!drawSlot.acquireUnlessCancelled { closed || isCancelled() }) return null + val rendered = + try { + if (closed || isCancelled()) return null + val draw = + thread + .submit( + Callable { + val queueMs = (System.nanoTime() - submitted) / 1_000_000.0 + drawOnGlThread(tile, pixels, queueMs) + }, + ) + // Once submitted, tile and pixels belong to this draw. + // Wait for completion before releasing either resource. + awaitDraw(draw) + } catch (error: ExecutionException) { + Log.w(TAG, "GPU render failed", error.cause ?: error) + false + } catch (error: Exception) { + Log.w(TAG, "GPU render failed", error) + false + } finally { + drawSlot.release() + } + if (!rendered || closed || isCancelled()) return null + + // FULL tiles still use the legacy draw-onto-byte-array label + // API. Split geometry tiles, which are what map backends + // request, keep the readback direct all the way into Rust. + val labelsStarted = System.nanoTime() + if (decorate != null) { + val rgba = ByteArray(pixels.remaining()) + pixels.get(rgba) + decorate(rgba) + pixels.clear() + pixels.put(rgba) + pixels.rewind() + } + val labelMs = (System.nanoTime() - labelsStarted) / 1_000_000 + + val encodeStarted = System.nanoTime() + val png = + TilePngEncoder.encode( + pixels, tileSize, tileSize, premultiplied = false, + ) + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d( + TAG, + "phases decode=${tile.decodeMs.toInt()}ms " + + "tessellate=${tile.tessellateMs.toInt()}ms " + + "(loop=${tile.featureLoopMs.toInt()} of which fills=${tile.fillMs.toInt()} " + + "lines=${tile.lineMs.toInt()}; filters=${tile.filterMs.toInt()}) " + + "labels=${labelMs}ms encode=${(System.nanoTime() - encodeStarted) / 1_000_000}ms", + ) + } + png + } finally { + pixels.clear() + pixelBuffers.offer(pixels) + } + } finally { + tile.close() + } + } + + private fun awaitDraw(draw: Future): Boolean { + var interrupted = false + try { + while (true) { + try { + return draw.get() + } catch (_: InterruptedException) { + interrupted = true + } + } + } finally { + if (interrupted) Thread.currentThread().interrupt() + } + } + + /** Runs on the GL thread. */ + private fun drawOnGlThread( + tile: TessellatedTile, + pixels: ByteBuffer, + queueMs: Double, + ): Boolean { + val context = egl ?: return false + val batch = renderer ?: return false + + val started = System.nanoTime() + batch.upload(tile.packed, tile.vertexOffset, tile.vertexFloatCount) + val uploaded = System.nanoTime() + context.bindDrawTarget() + val background = tile.background + if (background != null) { + batch.clear(background[0], background[1], background[2], background[3]) + } else { + batch.clear(0f, 0f, 0f, 0f) + } + batch.draw(tile.batches, tile.extent) + val drawn = System.nanoTime() + context.readPixels(pixels) + val read = System.nanoTime() + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d( + TAG, + "gl queue=${queueMs}ms upload=${(uploaded - started) / 1_000_000.0}ms " + + "submit=${(drawn - uploaded) / 1_000_000.0}ms " + + "resolveRead=${(read - drawn) / 1_000_000.0}ms " + + "copy=0.0ms", + ) + } + return true + } + + override fun close() { + if (closed) return + closed = true + try { + thread + .submit { + renderer?.close() + egl?.close() + renderer = null + egl = null + }.get() + } catch (_: Exception) { + // Already gone; nothing useful to do while tearing down. + } + thread.shutdown() + } +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/NativeRenderer.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/NativeRenderer.kt new file mode 100644 index 000000000..26c52f430 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/NativeRenderer.kt @@ -0,0 +1,243 @@ +package com.mapconductor.vectortile + +import java.io.Closeable +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.FloatBuffer +import java.util.concurrent.atomic.AtomicBoolean + +/** + * Thin JNI surface over the Rust renderer. + * + * Every call is one-way: Kotlin hands over coordinates and bytes and gets bytes + * back. Rust never calls into the JVM, so no worker thread has to attach to it + * — the one place JNI overhead would actually be felt. + */ +internal object NativeRenderer { + init { + System.loadLibrary("mvt_render_jni") + } + + /** + * Returns an opaque handle; throws IllegalArgumentException on a bad style. + * + * [displayTileSize] is how many dp one tile covers where the map shows it + * -- not the pixel count a render is asked for. A label pass draws at + * twice the pixels, and a 256dp tile is still 256dp however many pixels it + * carries. It fixes the size the style draws at and the zoom its + * expressions are read at. + */ + external fun nativeNew( + styleJson: String, + displayTileSize: Int, + ): Long + + external fun nativeFree(handle: Long) + + external fun nativeSetStyle( + handle: Long, + styleJson: String, + ) + + /** JSON array of `{ sourceId, url, z, x, y, scale, offsetX, offsetY }`. */ + external fun nativePlan( + handle: Long, + z: Int, + x: Int, + y: Int, + ): String + + /** + * @param data every fetched source tile concatenated in plan order + * @param lengths each tile's byte length, 0 where the fetch produced nothing + */ + external fun nativeRender( + handle: Long, + z: Int, + x: Int, + y: Int, + tileSize: Int, + data: ByteArray, + lengths: IntArray, + geometryOnly: Int, + ): ByteArray + + /** The style's `glyphs` URL template, or empty when it has none. */ + external fun nativeGlyphsUrlTemplate(handle: Long): String + + /** + * JSON array of glyph URLs this tile's labels need and the renderer does + * not have. + * + * Answered from the tile rather than the style: ranges follow the text, and + * a CJK font has 82 of them where a tile of Tokyo uses four. + */ + external fun nativeNeededGlyphs( + handle: Long, + z: Int, + x: Int, + y: Int, + data: ByteArray, + lengths: IntArray, + ): String + + /** Hands over one fetched range; returns how many glyphs it added. */ + external fun nativeSpriteUrls( + handle: Long, + pixelRatio: Int, + ): String + + external fun nativeNeedsSprite(handle: Long): Int + + external fun nativeNeedsCpu( + handle: Long, + z: Int, + data: ByteArray, + lengths: IntArray, + ): Int + + external fun nativeAddSprite( + handle: Long, + indexJson: String, + png: ByteArray, + ): Int + + external fun nativeAddGlyphs( + handle: Long, + pbf: ByteArray, + ): Int + + /** + * Draws this tile's labels onto an RGBA buffer, in place. Returns how many + * were placed. + */ + external fun nativeDrawLabels( + handle: Long, + z: Int, + x: Int, + y: Int, + tileSize: Int, + rgba: ByteArray, + data: ByteArray, + lengths: IntArray, + ): Int + + /** Draws a transparent label tile into Rust-owned direct memory. */ + external fun nativeRenderLabels( + handle: Long, + z: Int, + x: Int, + y: Int, + tileSize: Int, + data: ByteArray, + lengths: IntArray, + placedOut: IntArray, + ): ByteBuffer? + + external fun nativeFreeLabelPixels(buffer: ByteBuffer) + + /** JSON array of layer `type` values the renderer will not draw. */ + external fun nativeUnsupportedLayerTypes(handle: Long): String + + /** JSON array of the credits the style's sources ask to be shown. */ + external fun nativeAttributions(handle: Long): String + + /** JSON array of reasons the style may not render as intended. */ + external fun nativeDiagnostics(handle: Long): String + + /** + * Triangulates a tile for the GPU renderer. Returns one packed direct buffer; see + * [TessellatedTile] for the layout. + */ + external fun nativeTessellate( + handle: Long, + z: Int, + x: Int, + y: Int, + tileSize: Int, + data: ByteArray, + lengths: IntArray, + ): ByteBuffer + + /** Releases the native allocation backing [buffer]. */ + external fun nativeFreeTessellation(buffer: ByteBuffer) +} + +/** + * A tile triangulated by [NativeRenderer.nativeTessellate]. + * + * One packed native buffer carries everything, so a tile crosses JNI without + * copying its vertex data into a Java array: + * + * ```text + * [0] extent + * [1] background present (1) or not (0) + * [2..6] background r, g, b, a + * [6] batch count B + * [7..13] timings ms: copy-in, decode, tessellate, + * filter-compile, fill, line + * [13 .. 13+B*2] per batch: firstVertex, vertexCount + * [13+B*2 ..] vertices: x, y, r, g, b, a + * ``` + * + * Colour is per vertex, not per batch: a style layer may paint each feature + * differently — the MapLibre demo style gives every country its own fill — + * and one colour per draw call disagreed with the CPU renderer on 37% of a + * tile. + */ +internal class TessellatedTile( + private val storage: ByteBuffer, +) : Closeable { + /** Direct view passed to OpenGL; its storage remains owned by Rust. */ + val packed: FloatBuffer = storage.order(ByteOrder.nativeOrder()).asFloatBuffer() + private val closed = AtomicBoolean(false) + val extent: Float = packed[0] + val background: FloatArray? = + if (packed[1] != 0f) floatArrayOf(packed[2], packed[3], packed[4], packed[5]) else null + val batches: List + val vertexOffset: Int + val vertexFloatCount: Int + + /** Milliseconds spent inside the native call, by phase. */ + val decodeMs: Float = packed[7] + val tessellateMs: Float = packed[8] + val filterMs: Float = packed[9] + val fillMs: Float = packed[10] + val lineMs: Float = packed[11] + val featureLoopMs: Float = packed[12] + + init { + val batchCount = packed[6].toInt() + var cursor = 13 + batches = + (0 until batchCount).map { + val batch = + SolidBatchRenderer.Batch( + vertexOffset = packed[cursor].toInt(), + vertexCount = packed[cursor + 1].toInt(), + ) + cursor += 2 + batch + } + vertexOffset = cursor + vertexFloatCount = packed.capacity() - cursor + } + + val triangleCount: Int get() = vertexFloatCount / (SolidBatchRenderer.VERTEX_STRIDE * 3) + + override fun close() { + if (closed.compareAndSet(false, true)) NativeRenderer.nativeFreeTessellation(storage) + } +} + +/** Rust-owned premultiplied RGBA for a transparent label tile. */ +internal class NativeLabelPixels( + val buffer: ByteBuffer, + val placed: Int, +) : Closeable { + private val closed = AtomicBoolean(false) + + override fun close() { + if (closed.compareAndSet(false, true)) NativeRenderer.nativeFreeLabelPixels(buffer) + } +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/OfflinePackage.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/OfflinePackage.kt new file mode 100644 index 000000000..7559b2647 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/OfflinePackage.kt @@ -0,0 +1,274 @@ +package com.mapconductor.vectortile + +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.net.URLEncoder +import java.util.concurrent.atomic.AtomicLong + +/** + * A style and everything it needs to draw one area, on disk. + * + * Downloaded by [OfflinePackageDownloader] and read here. The layout is + * plain files the style's own URL templates map onto, so a package can be + * served to a map that draws vector styles itself (MapLibre, Mapbox, + * MapTiler) as well as read by the rasteriser for every other map: + * + * ``` + * manifest.json what is in here and where it came from + * style.json the style, as downloaded + * index.json source URL -> relative path + * tiles////.mvt + * glyphs//.pbf + * sprite.json sprite.png sprite@2x.json sprite@2x.png + * ``` + * + * ios-vectortile reads and writes the same layout, so a package made on one + * platform serves the other. + */ +class OfflinePackage private constructor( + val directory: File, + val manifest: Manifest, + private val index: Map, +) { + /** South-west to north-east, degrees. */ + class Bounds( + val south: Double, + val west: Double, + val north: Double, + val east: Double, + ) { + fun toJson(): JSONObject = + JSONObject() + .put("south", south) + .put("west", west) + .put("north", north) + .put("east", east) + + companion object { + fun fromJson(json: JSONObject): Bounds = + Bounds( + south = json.getDouble("south"), + west = json.getDouble("west"), + north = json.getDouble("north"), + east = json.getDouble("east"), + ) + } + } + + class Manifest( + val bounds: Bounds, + val minZoom: Int, + val maxZoom: Int, + val styleDigest: String, + val createdAt: Long, + val tiles: Int, + val glyphs: Int, + val sprites: Int, + val bytes: Long, + /** Source id -> the tile URL template the tiles were fetched from. */ + val sources: Map, + val glyphsTemplate: String?, + val spriteBase: String?, + ) { + fun toJson(): JSONObject = + JSONObject() + .put("version", FORMAT_VERSION) + .put("bounds", bounds.toJson()) + .put("minZoom", minZoom) + .put("maxZoom", maxZoom) + .put("styleDigest", styleDigest) + .put("createdAt", createdAt) + .put("tiles", tiles) + .put("glyphs", glyphs) + .put("sprites", sprites) + .put("bytes", bytes) + .put("sources", JSONObject(sources)) + .putOpt("glyphsTemplate", glyphsTemplate) + .putOpt("spriteBase", spriteBase) + + companion object { + fun fromJson(json: JSONObject): Manifest { + val sources = json.optJSONObject("sources") ?: JSONObject() + return Manifest( + bounds = Bounds.fromJson(json.getJSONObject("bounds")), + minZoom = json.getInt("minZoom"), + maxZoom = json.getInt("maxZoom"), + styleDigest = json.getString("styleDigest"), + createdAt = json.getLong("createdAt"), + tiles = json.optInt("tiles"), + glyphs = json.optInt("glyphs"), + sprites = json.optInt("sprites"), + bytes = json.optLong("bytes"), + sources = sources.keys().asSequence().associateWith { sources.getString(it) }, + glyphsTemplate = json.optString("glyphsTemplate").takeIf { it.isNotEmpty() }, + spriteBase = json.optString("spriteBase").takeIf { it.isNotEmpty() }, + ) + } + } + } + + /** The style as it was downloaded, pointing at its original servers. */ + val styleJson: String by lazy { File(directory, STYLE_FILE).readText() } + + /** The bytes the package holds for a source URL, or null when it has none. */ + fun bytes(url: String): ByteArray? { + val relative = index[url] ?: return null + val file = File(directory, relative) + return if (file.isFile) file.readBytes() else null + } + + /** Whether the package answers for this URL. */ + fun contains(url: String): Boolean = index[url]?.let { File(directory, it).isFile } == true + + /** + * Where a file the package does not have would come from. + * + * The relative path is the one the served style asks for, so it maps + * back through the same templates the package was fetched with. Null for + * a path that is not in the package's vocabulary. + */ + fun upstreamUrl(relativePath: String): String? { + val segments = relativePath.split('/') + return when { + segments.size == 5 && segments[0] == TILES_DIR && segments[4].endsWith(".mvt") -> { + val template = manifest.sources[segments[1]] ?: return null + template + .replace("{z}", segments[2]) + .replace("{x}", segments[3]) + .replace("{y}", segments[4].removeSuffix(".mvt")) + } + segments.size == 3 && segments[0] == GLYPHS_DIR && segments[2].endsWith(".pbf") -> { + val template = manifest.glyphsTemplate ?: return null + template + .replace("{fontstack}", URLEncoder.encode(segments[1], "UTF-8").replace("+", "%20")) + .replace("{range}", segments[2].removeSuffix(".pbf")) + } + segments.size == 1 && segments[0].startsWith(SPRITE_FILE) -> { + val base = manifest.spriteBase ?: return null + base + segments[0].removePrefix(SPRITE_FILE) + } + else -> null + } + } + + /** + * The style rewritten to read from [baseUrl], for a map that draws the + * style itself. Every source becomes a tile template under + * `tiles//`, the glyphs and the sprite move under the same root, + * and a TileJSON `url` is dropped in favour of the tiles it named. + */ + fun styleServedBy(baseUrl: String): String { + val style = JSONObject(styleJson) + val sources = style.optJSONObject("sources") ?: JSONObject() + for (id in sources.keys().asSequence().toList()) { + val source = sources.optJSONObject(id) ?: continue + if (!manifest.sources.containsKey(id)) continue + source.remove("url") + source.put("tiles", JSONArray().put("$baseUrl/$TILES_DIR/$id/{z}/{x}/{y}.mvt")) + } + if (manifest.glyphsTemplate != null) style.put("glyphs", "$baseUrl/$GLYPHS_DIR/{fontstack}/{range}.pbf") + if (manifest.spriteBase != null) style.put("sprite", "$baseUrl/$SPRITE_FILE") + return style.toString() + } + + /** + * How the fetches of one provider have gone so far: what the package + * answered, what went to the network, and what was refused offline. + * A value, so that each report is a change a UI notices. + */ + data class Stats( + val packageHits: Long = 0, + val networkFetches: Long = 0, + val blocked: Long = 0, + ) { + override fun toString(): String = "package=$packageHits network=$networkFetches blocked=$blocked" + } + + private class Counters { + val packageHits = AtomicLong() + val networkFetches = AtomicLong() + val blocked = AtomicLong() + + fun snapshot(): Stats = Stats(packageHits.get(), networkFetches.get(), blocked.get()) + } + + /** + * A `fetchTile` for [VectorTileProvider]: the package first, then -- + * while [online] -- the network, and otherwise nothing. + * + * "Nothing" is thrown rather than returned: a null from a fetch means + * "there is no such tile" and is remembered as such, whereas a tile the + * network was not allowed to fetch is there to be had the moment it is. + */ + class Fetcher( + private val pkg: OfflinePackage, + private val upstream: (String) -> ByteArray?, + @Volatile var online: Boolean = true, + private val onStats: ((Stats) -> Unit)? = null, + ) : (String) -> ByteArray? { + private val counters = Counters() + + val stats: Stats get() = counters.snapshot() + + override fun invoke(url: String): ByteArray? { + val packaged = pkg.bytes(url) + if (packaged != null) { + counters.packageHits.incrementAndGet() + onStats?.invoke(counters.snapshot()) + return packaged + } + if (!online) { + counters.blocked.incrementAndGet() + onStats?.invoke(counters.snapshot()) + throw OfflineUnavailableException(url) + } + counters.networkFetches.incrementAndGet() + onStats?.invoke(counters.snapshot()) + return upstream(url) + } + } + + companion object { + const val FORMAT_VERSION = 1 + const val MANIFEST_FILE = "manifest.json" + const val STYLE_FILE = "style.json" + const val INDEX_FILE = "index.json" + const val TILES_DIR = "tiles" + const val GLYPHS_DIR = "glyphs" + const val SPRITE_FILE = "sprite" + + /** The package in [directory], or null when there is none or it will not parse. */ + @JvmStatic + fun open(directory: File): OfflinePackage? { + val manifestFile = File(directory, MANIFEST_FILE) + val indexFile = File(directory, INDEX_FILE) + if (!manifestFile.isFile || !indexFile.isFile) return null + return runCatching { + val manifest = Manifest.fromJson(JSONObject(manifestFile.readText())) + val indexJson = JSONObject(indexFile.readText()) + val index = indexJson.keys().asSequence().associateWith { indexJson.getString(it) } + OfflinePackage(directory, manifest, index) + }.getOrNull() + } + + /** Removes a package, whole. */ + @JvmStatic + fun delete(directory: File): Boolean = directory.deleteRecursively() + + internal fun create( + directory: File, + manifest: Manifest, + index: Map, + ): OfflinePackage { + File(directory, MANIFEST_FILE).writeText(manifest.toJson().toString()) + File(directory, INDEX_FILE).writeText(JSONObject(index).toString()) + return OfflinePackage(directory, manifest, index) + } + } +} + +/** A fetch refused because the network is off and the package has no answer. */ +class OfflineUnavailableException( + url: String, +) : RuntimeException("offline: $url") diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/OfflinePackageDownloader.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/OfflinePackageDownloader.kt new file mode 100644 index 000000000..d2c0ca76f --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/OfflinePackageDownloader.kt @@ -0,0 +1,422 @@ +package com.mapconductor.vectortile + +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLDecoder +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.floor +import kotlin.math.ln +import kotlin.math.tan +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.sync.Semaphore +import kotlinx.coroutines.sync.withPermit +import kotlinx.coroutines.withContext + +/** + * Fetches everything a style needs to draw one area and writes an + * [OfflinePackage]. + * + * What "everything" is comes from the renderer, not from guessing at the + * style: `plan` says which source tiles each display tile reads (including + * the shallower tile a magnified level reads from, so a source that stops at + * z14 is not asked for z15), and `neededGlyphs` says which font ranges the + * labels in those tiles use -- fetching every range a CJK font has would be + * eighty files per font, nearly all unused. The sprite comes in both + * resolutions, since the two platforms' rasterisers ask for different ones. + */ +object OfflinePackageDownloader { + enum class Phase { PLANNING, TILES, GLYPHS, SPRITE, DONE } + + class Progress( + val phase: Phase, + val done: Int, + val total: Int, + ) { + override fun toString(): String = "${phase.name.lowercase()} $done/$total" + } + + /** A bounds and zoom range that would need more tiles than this is refused. */ + const val MAX_TILES = 20_000 + + /** + * @param styleJson the style, with absolute source, glyph and sprite URLs + * @param bounds the area, in degrees + * @param minZoom the shallowest display zoom to cover; 0 costs one tile + * @param maxZoom the deepest display zoom; sources deeper than their own + * `maxzoom` are magnified from it, so this can exceed the data's zoom + * @param directory where the package goes; anything there is replaced + * @param fetch how bytes are got; null for plain HTTP with [headers] + * @throws IllegalArgumentException when the style will not parse or the + * area would need more than [MAX_TILES] tiles + */ + @JvmStatic + suspend fun download( + styleJson: String, + bounds: OfflinePackage.Bounds, + minZoom: Int = 0, + maxZoom: Int = 14, + directory: File, + headers: Map = emptyMap(), + parallelism: Int = 8, + fetch: ((String) -> ByteArray?)? = null, + onProgress: (Progress) -> Unit = {}, + ): OfflinePackage = + withContext(Dispatchers.IO) { + require(minZoom in 0..maxZoom && maxZoom <= 22) { "zoom range $minZoom..$maxZoom" } + val get: (String) -> FetchResult = + fetch?.let { custom -> + { url -> + try { + custom(url) + ?.takeIf { it.isNotEmpty() } + ?.let { FetchResult.Success(it) } + ?: FetchResult.NotFound + } catch (t: Throwable) { + if (t is CancellationException) throw t + FetchResult.TemporaryFailure(url, t) + } + } + } ?: { url -> + httpFetch(url, headers) + } + val normalizedStyleJson = normalizeStyle(styleJson, get) + val renderer = VectorTileRenderer.create(normalizedStyleJson, VectorTileProvider.DEFAULT_TILE_SIZE) + try { + directory.deleteRecursively() + directory.mkdirs() + File(directory, OfflinePackage.STYLE_FILE).writeText(normalizedStyleJson) + val index = java.util.concurrent.ConcurrentHashMap() + val bytes = + java.util.concurrent.atomic + .AtomicLong() + + // --- plan: which source tiles, for which display tiles --- + onProgress(Progress(Phase.PLANNING, 0, 0)) + + class DisplayTile( + val z: Int, + val x: Int, + val y: Int, + val urls: List, + ) + val displayTiles = ArrayList() + val wanted = LinkedHashMap() // url -> relative path + for (z in minZoom..maxZoom) { + val n = 1 shl z + val x0 = tileX(bounds.west, z).coerceIn(0, n - 1) + val x1 = tileX(bounds.east, z).coerceIn(0, n - 1) + val y0 = tileY(bounds.north, z).coerceIn(0, n - 1) + val y1 = tileY(bounds.south, z).coerceIn(0, n - 1) + val minX = minOf(x0, x1) + val maxX = maxOf(x0, x1) + val minY = minOf(y0, y1) + val maxY = maxOf(y0, y1) + for (x in minX..maxX) { + for (y in minY..maxY) { + ensureActive() + val plan = JSONArray(renderer.plan(z, x, y)) + val urls = ArrayList(plan.length()) + val boundary = x == minX || x == maxX || y == minY || y == maxY + for (i in 0 until plan.length()) { + val entry = plan.getJSONObject(i) + // Interior neighbours are only for label + // placement and stay out of the package. At + // the requested edge they are the one-tile + // buffer that keeps boundary labels intact. + if (entry.optBoolean("labelsOnly", false) && !boundary) { + urls.add(null) + continue + } + val url = entry.getString("url") + urls.add(url) + wanted.getOrPut(url) { + "${OfflinePackage.TILES_DIR}/${entry.getString("sourceId")}/" + + "${entry.getInt("z")}/${entry.getInt("x")}/${entry.getInt("y")}.mvt" + } + require(wanted.size <= MAX_TILES) { + "more than $MAX_TILES tiles; shrink the area or the zoom range" + } + } + displayTiles.add(DisplayTile(z, x, y, urls)) + } + } + } + + // --- tiles --- + val total = wanted.size + val done = + java.util.concurrent.atomic + .AtomicInteger() + onProgress(Progress(Phase.TILES, 0, total)) + val gate = Semaphore(parallelism.coerceAtLeast(1)) + coroutineScope { + wanted.entries + .map { (url, relative) -> + async { + gate.withPermit { + ensureActive() + when (val result = get(url)) { + is FetchResult.Success -> { + write(directory, relative, result.data) + index[url] = relative + bytes.addAndGet(result.data.size.toLong()) + } + FetchResult.NotFound -> Unit + is FetchResult.TemporaryFailure -> throw result.toIOException() + } + onProgress(Progress(Phase.TILES, done.incrementAndGet(), total)) + } + } + }.awaitAll() + } + + // --- glyphs: what the fetched tiles' labels need --- + val glyphTemplate = renderer.glyphsUrlTemplate() + val glyphMatcher = glyphTemplate?.let(::templateRegex) + var glyphCount = 0 + onProgress(Progress(Phase.GLYPHS, 0, displayTiles.size)) + if (glyphMatcher != null) { + displayTiles.forEachIndexed { i, tile -> + ensureActive() + val data = + tile.urls.map { url -> + url + ?.let { index[it] } + ?.let { File(directory, it).readBytes() } + } + val needed = + runCatching { + renderer.neededGlyphs(tile.z, tile.x, tile.y, data) + }.getOrDefault(emptyList()) + for (url in needed) { + if (index.containsKey(url)) continue + val match = glyphMatcher.matchEntire(url) ?: continue + val fontstack = URLDecoder.decode(match.groupValues[1], "UTF-8") + val range = match.groupValues[2] + val pbfResult = get(url) + if (pbfResult is FetchResult.TemporaryFailure) throw pbfResult.toIOException() + val pbf = (pbfResult as? FetchResult.Success)?.data ?: continue + val relative = "${OfflinePackage.GLYPHS_DIR}/$fontstack/$range.pbf" + write(directory, relative, pbf) + index[url] = relative + bytes.addAndGet(pbf.size.toLong()) + glyphCount += 1 + // Fed back so the next tile asks only for what is still missing. + runCatching { renderer.addGlyphs(pbf) } + } + onProgress(Progress(Phase.GLYPHS, i + 1, displayTiles.size)) + } + } + + // --- sprite, both resolutions --- + onProgress(Progress(Phase.SPRITE, 0, 2)) + var spriteCount = 0 + for (ratio in 1..2) { + val urls = runCatching { renderer.spriteUrls(ratio) }.getOrDefault(emptyList()) + if (urls.size != 2) continue + val suffix = if (ratio > 1) "@2x" else "" + for ((url, ext) in listOf(urls[0] to "json", urls[1] to "png")) { + val dataResult = get(url) + if (dataResult is FetchResult.TemporaryFailure) throw dataResult.toIOException() + val data = (dataResult as? FetchResult.Success)?.data ?: continue + val relative = "${OfflinePackage.SPRITE_FILE}$suffix.$ext" + write(directory, relative, data) + index[url] = relative + bytes.addAndGet(data.size.toLong()) + spriteCount += 1 + } + onProgress(Progress(Phase.SPRITE, ratio, 2)) + } + + val style = JSONObject(normalizedStyleJson) + val sources = style.optJSONObject("sources") ?: JSONObject() + val templates = + sources + .keys() + .asSequence() + .mapNotNull { id -> + sources + .optJSONObject(id) + ?.optJSONArray("tiles") + ?.optString(0) + ?.takeIf { it.isNotEmpty() } + ?.let { id to it } + }.toMap() + val manifest = + OfflinePackage.Manifest( + bounds = bounds, + minZoom = minZoom, + maxZoom = maxZoom, + styleDigest = TileDiskCache.digest(normalizedStyleJson), + createdAt = System.currentTimeMillis(), + tiles = index.count { it.value.startsWith("${OfflinePackage.TILES_DIR}/") }, + glyphs = glyphCount, + sprites = spriteCount, + bytes = bytes.get(), + sources = templates, + glyphsTemplate = glyphTemplate, + spriteBase = style.optString("sprite").takeIf { it.isNotEmpty() }, + ) + onProgress(Progress(Phase.DONE, total, total)) + OfflinePackage.create(directory, manifest, index) + } finally { + renderer.close() + } + } + + private sealed class FetchResult { + class Success( + val data: ByteArray, + ) : FetchResult() + + object NotFound : FetchResult() + + class TemporaryFailure( + val url: String, + val cause: Throwable? = null, + val status: Int? = null, + ) : FetchResult() { + fun toIOException(): IOException = + IOException( + status?.let { "offline package fetch failed: HTTP $it $url" } + ?: "offline package fetch failed: $url", + cause, + ) + } + } + + private fun normalizeStyle( + styleJson: String, + get: (String) -> FetchResult, + ): String { + val style = JSONObject(styleJson) + val sources = style.optJSONObject("sources") ?: return style.toString() + val ids = sources.keys().asSequence().toList() + for (id in ids) { + val source = sources.optJSONObject(id) ?: continue + val tileJsonUrl = source.optString("url").takeIf { it.isNotEmpty() } ?: continue + val data = + when (val result = get(tileJsonUrl)) { + is FetchResult.Success -> result.data + FetchResult.NotFound -> throw IOException("offline package TileJSON not found: $tileJsonUrl") + is FetchResult.TemporaryFailure -> throw result.toIOException() + } + val tileJson = JSONObject(String(data, Charsets.UTF_8)) + val tiles = + tileJson.optJSONArray("tiles") + ?: throw IOException("offline package TileJSON has no tiles: $tileJsonUrl") + val resolvedTiles = JSONArray() + for (i in 0 until tiles.length()) { + resolvedTiles.put(resolveUrl(tileJsonUrl, tiles.getString(i))) + } + source.put("tiles", resolvedTiles) + for (field in TILEJSON_SOURCE_FIELDS) { + if (tileJson.has(field)) source.put(field, tileJson.get(field)) + } + source.remove("url") + } + return style.toString() + } + + private val TILEJSON_SOURCE_FIELDS = + listOf("minzoom", "maxzoom", "bounds", "attribution", "scheme") + + private fun resolveUrl( + base: String, + value: String, + ): String = + try { + URL(URL(base), value).toString() + } catch (_: Throwable) { + value + } + + private fun httpFetch( + url: String, + headers: Map, + ): FetchResult { + val connection = + try { + URL(url).openConnection() as HttpURLConnection + } catch (t: Throwable) { + if (t is CancellationException) throw t + return FetchResult.TemporaryFailure(url, t) + } + var reuse = false + return try { + connection.requestMethod = "GET" + connection.connectTimeout = 15_000 + connection.readTimeout = 15_000 + headers.forEach(connection::setRequestProperty) + when (val status = connection.responseCode) { + HttpURLConnection.HTTP_NOT_FOUND, HttpURLConnection.HTTP_NO_CONTENT -> { + connection.errorStream?.use { it.readBytes() } + reuse = true + FetchResult.NotFound + } + in 200..299 -> { + val bytes = connection.inputStream.use { it.readBytes() } + reuse = true + bytes.takeIf { it.isNotEmpty() }?.let { FetchResult.Success(it) } + ?: FetchResult.NotFound + } + else -> { + connection.errorStream?.use { it.readBytes() } + reuse = true + FetchResult.TemporaryFailure(url, status = status) + } + } + } catch (t: Throwable) { + if (t is CancellationException) throw t + FetchResult.TemporaryFailure(url, t) + } finally { + if (!reuse) connection.disconnect() + } + } + + private fun write( + directory: File, + relative: String, + data: ByteArray, + ) { + val file = File(directory, relative) + file.parentFile?.mkdirs() + val temp = File(file.parentFile, "${file.name}.part") + temp.writeBytes(data) + if (!temp.renameTo(file)) { + file.writeBytes(data) + temp.delete() + } + } + + /** `{fontstack}` and `{range}` as capture groups; everything else literal. */ + private fun templateRegex(template: String): Regex { + val parts = template.split("{fontstack}", "{range}") + val fontstackFirst = template.indexOf("{fontstack}") < template.indexOf("{range}") + require(parts.size == 3 && fontstackFirst) { "glyph template must name {fontstack} then {range}: $template" } + return Regex(Regex.escape(parts[0]) + "(.+)" + Regex.escape(parts[1]) + "(\\d+-\\d+)" + Regex.escape(parts[2])) + } + + private fun tileX( + lon: Double, + z: Int, + ): Int = floor((lon + 180.0) / 360.0 * (1 shl z)).toInt() + + private fun tileY( + lat: Double, + z: Int, + ): Int { + val rad = Math.toRadians(lat.coerceIn(-85.05112878, 85.05112878)) + return floor((1.0 - ln(tan(rad) + 1.0 / cos(rad)) / PI) / 2.0 * (1 shl z)).toInt() + } +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/SolidBatchRenderer.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/SolidBatchRenderer.kt new file mode 100644 index 000000000..6ccc68ec1 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/SolidBatchRenderer.kt @@ -0,0 +1,183 @@ +package com.mapconductor.vectortile + +import java.io.Closeable +import java.nio.FloatBuffer +import android.opengl.GLES20 + +/** + * Draws batches of solid-coloured triangles in tile-local coordinates. + * + * This is the shape a vector tile actually reduces to on a GPU: every fill and + * every line becomes triangles, grouped by paint colour, one draw call per + * style layer. Anti-aliasing comes from MSAA on the framebuffer rather than + * from per-vertex coverage, which keeps the shader trivial and is enough to + * establish whether the GPU path is worth pursuing. + */ +internal class SolidBatchRenderer : Closeable { + private var program = 0 + private var positionAttribute = 0 + private var colorAttribute = 0 + private var extentUniform = 0 + private var vertexBuffer = 0 + + companion object { + /** Floats per vertex: x, y, r, g, b, a. */ + const val VERTEX_STRIDE = 6 + + // Positions arrive in tile units (0..extent) and are mapped to clip + // space here, so the CPU never has to rescale the geometry. + // + // Tile y grows downward, and the natural mapping would put y=0 at the + // top of clip space. It does not, deliberately: `glReadPixels` returns + // rows bottom-up while `Bitmap.copyPixelsFromBuffer` reads them + // top-down, so rendering upside down here is what makes the readback + // come out the right way up — without an extra CPU flip per tile. + const val VERTEX_SHADER = """ + attribute vec2 aPosition; + attribute vec4 aColor; + uniform float uExtent; + varying vec4 vColor; + void main() { + vec2 unit = aPosition / uExtent; + gl_Position = vec4(unit.x * 2.0 - 1.0, unit.y * 2.0 - 1.0, 0.0, 1.0); + vColor = aColor; + } + """ + + const val FRAGMENT_SHADER = """ + precision mediump float; + varying vec4 vColor; + void main() { gl_FragColor = vColor; } + """ + } + + /** + * One draw call: a run of triangle vertices. + * + * No colour here — it lives on the vertices, because a style layer may + * paint each feature differently and a single colour per draw call gets + * those wrong. + */ + data class Batch( + val vertexOffset: Int, + val vertexCount: Int, + ) + + fun initialise() { + program = link(VERTEX_SHADER, FRAGMENT_SHADER) + positionAttribute = GLES20.glGetAttribLocation(program, "aPosition") + colorAttribute = GLES20.glGetAttribLocation(program, "aColor") + extentUniform = GLES20.glGetUniformLocation(program, "uExtent") + + val ids = IntArray(1) + GLES20.glGenBuffers(1, ids, 0) + vertexBuffer = ids[0] + } + + /** Uploads all geometry for a tile in one go. */ + fun upload( + packed: FloatBuffer, + offset: Int, + count: Int, + ) { + val vertices = packed.duplicate() + vertices.position(offset) + vertices.limit(offset + count) + + GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBuffer) + GLES20.glBufferData( + GLES20.GL_ARRAY_BUFFER, count * 4, vertices, GLES20.GL_STATIC_DRAW, + ) + } + + fun clear( + r: Float, + g: Float, + b: Float, + a: Float, + ) { + GLES20.glClearColor(r, g, b, a) + GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) + } + + fun draw( + batches: List, + extent: Float, + ) { + GLES20.glUseProgram(program) + GLES20.glUniform1f(extentUniform, extent) + + GLES20.glEnable(GLES20.GL_BLEND) + // Separate blend for the alpha channel. Plain glBlendFunc applies + // SRC_ALPHA to alpha too, so drawing a 0.10-alpha layer DROPS the + // stored alpha to 0.91 — and Bitmap, which treats its pixels as + // premultiplied, then un-premultiplies on read: rgb / 0.91, clamped. + // Stack a few translucent land layers and whole regions blow out to + // white. With ONE / ONE_MINUS_SRC_ALPHA the destination alpha stays + // saturated at 1 and the readback is exact. + GLES20.glBlendFuncSeparate( + GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA, + GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA, + ) + + GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBuffer) + val stride = VERTEX_STRIDE * 4 + GLES20.glEnableVertexAttribArray(positionAttribute) + GLES20.glVertexAttribPointer(positionAttribute, 2, GLES20.GL_FLOAT, false, stride, 0) + GLES20.glEnableVertexAttribArray(colorAttribute) + GLES20.glVertexAttribPointer(colorAttribute, 4, GLES20.GL_FLOAT, false, stride, 8) + + // Batches stay one draw call each to preserve painter's order, even + // though they no longer carry state to set. + for (batch in batches) { + GLES20.glDrawArrays(GLES20.GL_TRIANGLES, batch.vertexOffset, batch.vertexCount) + } + + GLES20.glDisableVertexAttribArray(positionAttribute) + GLES20.glDisableVertexAttribArray(colorAttribute) + } + + private fun link( + vertexSource: String, + fragmentSource: String, + ): Int { + val vertex = compile(GLES20.GL_VERTEX_SHADER, vertexSource) + val fragment = compile(GLES20.GL_FRAGMENT_SHADER, fragmentSource) + val id = GLES20.glCreateProgram() + GLES20.glAttachShader(id, vertex) + GLES20.glAttachShader(id, fragment) + GLES20.glLinkProgram(id) + + val status = IntArray(1) + GLES20.glGetProgramiv(id, GLES20.GL_LINK_STATUS, status, 0) + check(status[0] != 0) { "link failed: ${GLES20.glGetProgramInfoLog(id)}" } + + GLES20.glDeleteShader(vertex) + GLES20.glDeleteShader(fragment) + return id + } + + private fun compile( + type: Int, + source: String, + ): Int { + val id = GLES20.glCreateShader(type) + GLES20.glShaderSource(id, source) + GLES20.glCompileShader(id) + val status = IntArray(1) + GLES20.glGetShaderiv(id, GLES20.GL_COMPILE_STATUS, status, 0) + check(status[0] != 0) { "compile failed: ${GLES20.glGetShaderInfoLog(id)}" } + return id + } + + override fun close() { + if (vertexBuffer != 0) { + GLES20.glDeleteBuffers(1, intArrayOf(vertexBuffer), 0) + vertexBuffer = 0 + } + if (program != 0) { + GLES20.glDeleteProgram(program) + program = 0 + } + } +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/StyleAssetCache.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/StyleAssetCache.kt new file mode 100644 index 000000000..3468436ae --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/StyleAssetCache.kt @@ -0,0 +1,130 @@ +package com.mapconductor.vectortile + +import java.io.File +import java.security.MessageDigest +import java.util.concurrent.atomic.AtomicLong +import android.util.Log + +/** + * Keeps a style's fetched assets -- glyph ranges and the sprite sheet -- on + * disk, so a launch does not start with a mute map. + * + * The store the renderer draws from lives in memory, so every process start + * began with no letters at all, and a tile drawn then has no place names on + * it. They arrive with the ranges, and a screen of Japanese wants a lot of + * ranges: CJK is spread thinly across 256-codepoint blocks, so one view of + * Tokyo asked for 69 of them, at 0.4 to 1.3 seconds each. Measured on a Pixel + * 5a, the map was up and unlabelled for 6.2 seconds. + * + * Ranges themselves never change — a `{fontstack}/{range}.pbf` is the same + * file today and next month — so they are worth keeping. The second launch + * reads them back in a few milliseconds and the first tile is drawn with its + * labels already on it. + * + * Glyphs need [warm] because a warm start does not know which ranges it wants + * until it has drawn a tile, and by then it is too late: every file is read + * back and handed to the renderer, which takes the fontstack and range from + * inside the PBF. A sprite needs no such thing -- its two URLs come from the + * style -- so it is fetched through [get] by name like any other cache. + */ +internal class StyleAssetCache( + private val directory: File, + private val budgetBytes: Long, +) { + private val writesSinceSweep = AtomicLong(0) + + companion object { + private const val TAG = "VectorTileGlyphs" + private const val SWEEP_EVERY = 16L + private const val SUFFIX = ".pbf" + } + + private fun fileFor(url: String): File { + val md = MessageDigest.getInstance("SHA-256") + val digest = md.digest(url.toByteArray()).joinToString("") { "%02x".format(it) } + return File(directory, "$digest$SUFFIX") + } + + fun get(url: String): ByteArray? = + try { + val file = fileFor(url) + if (file.isFile) { + file.setLastModified(System.currentTimeMillis()) + file.readBytes().takeIf { it.isNotEmpty() } + } else { + null + } + } catch (error: Exception) { + Log.w(TAG, "read failed for $url", error) + null + } + + fun put( + url: String, + bytes: ByteArray, + ) { + try { + if (!directory.isDirectory && !directory.mkdirs()) return + // Write-then-rename, so a warm start never reads a half-written + // range and decides the font is broken. + val temp = File.createTempFile("glyph", ".tmp", directory) + temp.writeBytes(bytes) + if (!temp.renameTo(fileFor(url))) { + temp.delete() + return + } + if (writesSinceSweep.incrementAndGet() % SWEEP_EVERY == 0L) sweep() + } catch (error: Exception) { + Log.w(TAG, "write failed for $url", error) + } + } + + /** + * Hands every stored range to [load], newest last. + * + * Order matters only for what survives a partial read: the ranges touched + * most recently are the ones this map is most likely to want again. + */ + fun warm(load: (ByteArray) -> Unit): Int { + val files = + try { + directory.listFiles()?.filter { it.isFile && it.name.endsWith(SUFFIX) } + } catch (error: Exception) { + Log.w(TAG, "listing failed", error) + null + } ?: return 0 + + var loaded = 0 + for (file in files.sortedBy { it.lastModified() }) { + val bytes = + runCatching { file.readBytes() } + .onFailure { Log.w(TAG, "read failed for ${file.name}", it) } + .getOrNull() + if (bytes == null || bytes.isEmpty()) continue + runCatching { load(bytes) } + .onSuccess { loaded++ } + .onFailure { Log.w(TAG, "range would not parse: ${file.name}", it) } + } + return loaded + } + + /** Drops the least recently used ranges until the budget is met. */ + private fun sweep() { + try { + val files = directory.listFiles()?.filter { it.isFile } ?: return + var total = files.sumOf { it.length() } + if (total <= budgetBytes) return + for (file in files.sortedBy { it.lastModified() }) { + if (total <= budgetBytes) break + val length = file.length() + if (file.delete()) total -= length + } + } catch (error: Exception) { + Log.w(TAG, "sweep failed", error) + } + } + + fun clear() { + directory.listFiles()?.forEach { it.delete() } + } +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/TileDiskCache.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/TileDiskCache.kt new file mode 100644 index 000000000..315ad8871 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/TileDiskCache.kt @@ -0,0 +1,102 @@ +package com.mapconductor.vectortile + +import java.io.File +import java.security.MessageDigest +import java.util.concurrent.atomic.AtomicLong +import android.util.Log + +/** + * Stores rendered PNG tiles on disk, keyed by style and coordinates. + * + * This does not make the first view of an area faster — nothing can, the tiles + * have to be fetched and rasterised once. What it removes is paying that cost + * *again* on the next app launch. Within a single session the map SDK already + * caches raster tiles itself (measured: 9 renders for 7 distinct tiles across a + * pan away and back), so this is specifically about surviving process death. + * + * Entries are content-addressed, so a restyle simply misses rather than needing + * explicit invalidation. + */ +internal class TileDiskCache( + private val directory: File, + private val budgetBytes: Long, +) { + private val sizeBytes = AtomicLong(-1) + + /** Writes since the last sweep; eviction is amortised rather than per-write. */ + private val writesSinceSweep = AtomicLong(0) + + companion object { + private const val TAG = "VectorTileCache" + private const val SWEEP_EVERY = 32L + + /** Stable short digest of arbitrary text, for use in a file name. */ + fun digest(vararg parts: String): String { + val md = MessageDigest.getInstance("SHA-256") + parts.forEach { md.update(it.toByteArray()) } + return md.digest().joinToString("") { "%02x".format(it) }.take(32) + } + } + + private fun fileFor(key: String) = File(directory, "$key.png") + + fun get(key: String): ByteArray? { + val file = fileFor(key) + return try { + if (!file.isFile) return null + val bytes = file.readBytes() + if (bytes.isEmpty()) return null + // Touch so the sweep below evicts genuinely cold entries. + file.setLastModified(System.currentTimeMillis()) + bytes + } catch (error: Exception) { + Log.w(TAG, "read failed for $key", error) + null + } + } + + fun put( + key: String, + bytes: ByteArray, + ) { + try { + if (!directory.isDirectory && !directory.mkdirs()) return + // Write-then-rename: two threads rendering the same tile must not + // leave a half-written file behind for a third to read. + val temp = File.createTempFile("tile", ".tmp", directory) + temp.writeBytes(bytes) + if (!temp.renameTo(fileFor(key))) { + temp.delete() + return + } + sizeBytes.addAndGet(bytes.size.toLong()) + if (writesSinceSweep.incrementAndGet() % SWEEP_EVERY == 0L) sweep() + } catch (error: Exception) { + Log.w(TAG, "write failed for $key", error) + } + } + + /** Drops the least recently used files until the budget is met. */ + private fun sweep() { + try { + val files = directory.listFiles()?.filter { it.isFile } ?: return + var total = files.sumOf { it.length() } + sizeBytes.set(total) + if (total <= budgetBytes) return + + for (file in files.sortedBy { it.lastModified() }) { + if (total <= budgetBytes) break + val length = file.length() + if (file.delete()) total -= length + } + sizeBytes.set(total) + } catch (error: Exception) { + Log.w(TAG, "sweep failed", error) + } + } + + fun clear() { + directory.listFiles()?.forEach { it.delete() } + sizeBytes.set(0) + } +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileLayer.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileLayer.kt new file mode 100644 index 000000000..b23571e02 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileLayer.kt @@ -0,0 +1,566 @@ +package com.mapconductor.vectortile + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import com.mapconductor.compose.MapViewScope +import com.mapconductor.compose.raster.RasterLayer +import com.mapconductor.core.map.AttributionRule +import com.mapconductor.core.map.LocalMapServiceRegistry +import com.mapconductor.core.map.VectorStyleSupport +import com.mapconductor.core.map.VectorStyleSupportKey +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.raster.RasterTilePreferenceKey +import com.mapconductor.core.raster.TileScheme +import com.mapconductor.core.tileserver.TileServerRegistry +import com.mapconductor.vectorstyle.StyleRules +import com.mapconductor.vectorstyle.VectorStyleRules +import org.json.JSONObject +import java.io.File +import java.util.UUID +import kotlin.math.roundToInt +import android.content.res.Resources +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * Draws a MapLibre vector style on any map backend, by rendering it to raster + * tiles on the device and serving them through the SDK's local tile server. + * + * The backend only ever sees an ordinary raster layer, which is what makes this + * work on Google Maps, MapKit, HERE, ArcGIS and the rest — none of which can + * render a vector style themselves. + * + * Under the hood this mounts *two* raster layers: the geometry, GPU-drawn and + * never invalidated, and a transparent label overlay above it, CPU-drawn and + * refreshed alone when fonts arrive. To the map and the user they read as one + * layer. (Measured on an iPad against one merged layer: the merged tile waits + * for its nine neighbours and its glyphs before it can show anything, and + * first paint was three times slower; the split lets the ground land first.) + * + * Pass [diskCacheDir] to keep rendered tiles across app launches. It does not + * make the first view faster — the tiles still have to be fetched and + * rasterised once — but on a Pixel 5a a second launch served all seven visible + * tiles from disk with zero renders, against ~1 s of fetch plus ~1 s of + * rasterising each on the first. + * + * **The host app must permit cleartext traffic to loopback.** Tiles are served + * by the SDK's local tile server over plain HTTP on 127.0.0.1, and without a + * network security config allowing it the layer simply stays blank: + * + * ```xml + * + * + * + * 127.0.0.1 + * localhost + * + * + * ``` + * + * This is not specific to this module — every tile-server-backed layer in the + * SDK needs it, which is why `example-app` already carries one. + * + * ```kotlin + * VectorTileLayer(styleJson = style, opacity = 0.9f) + * ``` + * + * With [asBasemap] on a map that can draw the style itself (MapLibre, Mapbox, + * MapTiler -- anything registering [VectorStyleSupportKey]), none of the + * above happens: the style document is served to the map as its own style + * and the map's vector renderer draws it. See [VectorStyleSupport] for what + * that means -- chiefly that the style *replaces* the basemap and [opacity] + * does not apply. Maps without the capability take the raster path whatever + * [asBasemap] says. + */ +@Composable +fun MapViewScope.VectorTileLayer( + styleJson: String, + /** + * スタイルを描く前に当てる調整。`VectorStyle` が取るものと同じ [StyleRules] + * なので、「道路は白」「建物は描かない」がどこに書いても同じ意味になる。 + * + * 文書を自分で書き換えるのではなくこれを使う理由は、role を隠す規則が + * 書けること: 渡す文書の側でレイヤーを落とすので、**描画そのものが + * 起きない**。 + * + * ```kotlin + * VectorTileLayer( + * styleJson = style, + * rules = buildStyleRules { + * role(LayerRole.BUILDING) { visible = false } + * role(LayerRole.ROAD) { visible = false } + * }, + * ) + * ``` + * + * 省略すれば作者が書いたままの文書が描かれ、コンパイラは一度も走らない。 + */ + rules: StyleRules = StyleRules.NONE, + /** + * タイル 1 枚の一辺(dp)。null なら地図 SDK の好みに従う。 + * + * 既定を null にしてあるのは、良い値が**載せる地図による**から。1 枚あたりの + * 固定費は枚数に比例するので同じ画面なら大きいタイルが安く、既定は 512。 + * ただし ArcGIS の 3D SceneView のように「タイルは 256px」という前提で + * レベルを選ぶ SDK があり、そこへ 512 を渡すと 1 段深いレベルを 4 倍の枚数で + * 引く。プロバイダが [RasterTilePreferenceKey] で宣言していればそれに従い、 + * 何も言わなければ [VectorTileProvider.DEFAULT_TILE_SIZE]。 + * + * 明示した値は常に優先される。 + */ + tileSize: Int? = null, + opacity: Float = 1.0f, + visible: Boolean = true, + maxZoom: Int = 22, + headers: Map = emptyMap(), + /** + * Where to rasterise. The default probes for an OpenGL ES context and + * falls back to the CPU when there is none. + * + * The GPU mode matters less for raw speed than for *which* processor pays: + * on a mid-range device it is roughly 3x faster, but more to the point it + * takes the drawing off the CPU that the map SDK and the app are already + * competing for. + */ + renderMode: VectorTileProvider.RenderMode = VectorTileProvider.RenderMode.AUTO, + /** + * Image pixels drawn per style pixel. + * + * Null follows the display's own density, which is what stops a 3x screen + * stretching every tile — neither the map SDKs nor this layer ask for + * `@2x` tiles, so without it the tile is drawn at a third of the pixels + * the screen will show it at. A tile covers the same ground whatever this + * says; only its grain changes, and so does the cost: the image is this + * squared, and the GPU readback is per pixel. + * + * Pass 1 to trade sharpness back for speed on a slow device. + * + * Matches `renderScale` on iOS. + */ + renderScale: Int? = null, + /** + * Where to keep rendered tiles across app launches, e.g. + * `context.cacheDir.resolve("vectortile")`. Null disables it. + * + * Deliberately the caller's choice rather than something this module digs + * out of a `Context`: apps have their own opinions about cache location and + * lifetime, and a library helping itself to disk behind their back is not + * a favour. Within a session it changes little — the map SDK already caches + * raster tiles — but it removes re-rendering everything on the next launch. + */ + diskCacheDir: File? = null, + onDiagnostics: ((List) -> Unit)? = null, + /** + * The style is the basemap, not a layer over one. + * + * On a map that renders vector styles itself this hands the style over + * directly and mounts no raster layer at all -- the fast path, and the + * one an offline package will take. Elsewhere it changes nothing here; + * the app blanks the map's own basemap (a `None` design) and the opaque + * raster tiles are the map. + */ + asBasemap: Boolean = false, + /** + * A downloaded [OfflinePackage] to draw from. Source tiles, glyph ranges + * and the sprite the package holds are read from it and never fetched; + * anything else is fetched while [online] and refused otherwise. On the + * direct path the map reads the package through the local tile server. + */ + offlinePackage: OfflinePackage? = null, + /** + * Whether the network may be used for what [offlinePackage] lacks. Off, + * a source the package does not hold is drawn as absent and the tile is + * not kept, so it is drawn again once the network is back. Meaningless + * without a package: a style with no package is always online. + */ + online: Boolean = true, + /** Counts of what the package answered and what it could not, as fetches happen. */ + onOfflineStats: ((OfflinePackage.Stats) -> Unit)? = null, +) { + // Everything downstream is keyed off the group, so asking for a different + // scale rebuilds the provider and the routes with it. Null is resolved by + // the provider, from the display's own density. + val groupId = remember(renderScale) { "vectortile-${UUID.randomUUID()}" } + val tileServer = remember { TileServerRegistry.get() } + + /** + * 実際に描かれる文書 — 作者のスタイルに [rules] を当てたもの。 + * + * 差分ではなく文書に当てる。この下の二つの経路(ラスタライズと、スタイルを + * 自分で描く地図への受け渡し)はどちらも文書を取るからで、一度当てれば + * 両方が同じものを見る。 + * + * 規則が無ければ最初から作者のスタイルそのもの。あるときだけ、コンパイルが + * 終わるまで null = 何も載せない(先に素のスタイルを載せると、消したはずの + * 建物が一瞬出る)。 + */ + var drawnStyle by + remember(styleJson, rules.json) { + mutableStateOf(if (rules.json == StyleRules.NONE.json) styleJson else null) + } + LaunchedEffect(styleJson, rules.json) { + if (rules.json == StyleRules.NONE.json) return@LaunchedEffect + // 324 レイヤーのスタイルを当てるのはフレームの中でやる仕事ではない。 + val compiled = + withContext(Dispatchers.Default) { runCatching { VectorStyleRules.compile(styleJson, rules.json) } } + compiled + .onSuccess { + if (it.diagnostics.isNotEmpty()) onDiagnostics?.invoke(it.diagnostics) + drawnStyle = it.styleJson + }.onFailure { + onDiagnostics?.invoke(listOf("the rules could not be applied: ${it.message}")) + drawnStyle = styleJson + } + } + val drawn = drawnStyle ?: return + + val direct = if (asBasemap) LocalMapServiceRegistry.current.get(VectorStyleSupportKey) else null + if (direct != null) { + DirectVectorStyle( + styleJson = drawn, + support = direct, + tileServer = tileServer, + onDiagnostics = onDiagnostics, + offlinePackage = offlinePackage, + online = online, + headers = headers, + ) + return + } + + // The fetcher outlives any one fetch and is what `online` switches; the + // stats callback is delivered on the main thread, where the caller's + // state lives, from whichever thread fetched. + val statsListener by rememberUpdatedState(onOfflineStats) + val mainHandler = remember { android.os.Handler(android.os.Looper.getMainLooper()) } + val fetcher = + remember(offlinePackage) { + offlinePackage?.let { pkg -> + OfflinePackage.Fetcher( + pkg = pkg, + upstream = { url -> VectorTileProvider.httpGet(url, headers) }, + online = online, + onStats = { stats -> mainHandler.post { statsListener?.invoke(stats) } }, + ) + } + } + LaunchedEffect(fetcher, online) { fetcher?.online = online } + + val preference = LocalMapServiceRegistry.current.get(RasterTilePreferenceKey) + val preferred = preference?.preferredTileSize + + @Suppress("NAME_SHADOWING") + val tileSize = tileSize ?: preferred ?: VectorTileProvider.DEFAULT_TILE_SIZE + // What the map is told. See `VectorTileRasteriser.declaredTileSize`. + val declaredTileSize = + if (preference?.layoutInDevicePixels == true) { + (tileSize * Resources.getSystem().displayMetrics.density).roundToInt() + } else { + tileSize + } + + // Parsing a real basemap style is not free, so it happens once and off the + // main thread; the layer simply does not mount until it is ready. + var provider by remember { mutableStateOf(null) } + // Bumped when glyphs land. The map only refetches a raster source whose + // URL changed, so the generation has to reach the template. + var glyphGeneration by remember { mutableIntStateOf(0) } + var failure by remember { mutableStateOf(null) } + + DisposableEffect(groupId, tileSize) { + onDispose { + tileServer.unregister("$groupId-geom") + tileServer.unregister("$groupId-labels") + provider?.closeAsync() + provider = null + } + } + + LaunchedEffect(groupId, drawn, tileSize) { + val created = + withContext(Dispatchers.Default) { + runCatching { + VectorTileProvider.create( + styleJson = drawn, + tileSize = tileSize, + headers = headers, + diskCacheDir = diskCacheDir, + renderMode = renderMode, + renderScale = renderScale, + fetchTile = fetcher, + ) + } + } + created + .onSuccess { + // Glyphs arrive after the tiles that need them: a range is a + // round trip and a tile at low zoom wants dozens, so tiles are + // drawn with whatever is loaded and refetched once more is. + it.onGlyphsLoaded = { glyphGeneration++ } + // Two routes from one provider: the ground and the labels are + // served as separate tile layers stacked on each other. The + // user sees one map; the halves render in parallel -- GPU + // under, CPU over -- and glyphs arriving refresh only the + // transparent overlay, never the ground. + tileServer.register("$groupId-geom", it.geometryTiles) + tileServer.register("$groupId-labels", it.labelTiles) + provider = it + onDiagnostics?.invoke(it.diagnostics()) + }.onFailure { + failure = it.message + onDiagnostics?.invoke(listOf("style could not be loaded: ${it.message}")) + } + } + + val current = provider ?: return + if (failure != null) return + + /** + * What goes in the tile URL so a restyle is noticed. + * + * Content, not a counter: the same document has to produce the same URL. + * A host that rebuilds its overlay content would otherwise mint a fresh + * URL on every rebuild and the map would refetch every tile for nothing + * -- the mistake `VectorStyleHandoff` documents on the other side. + */ + val styleKey = remember(drawn) { "s${drawn.hashCode().toUInt().toString(16)}" } + + /** + * The credits the style's sources ask for, carried by the layer itself. + * + * The map's attribution overlay is fed from `resolveMapAttributions`, + * which merges the design's rules with those of every visible raster + * layer — so a credit attached here appears without the host writing any + * UI, and disappears when the layer is unmounted. Nothing else about this + * layer can be wrong while still looking right; the tiles draw perfectly + * whether or not anyone is credited for them. + * + * No zoom or bounds narrowing on the rules. A source's `maxzoom` is where + * its tiles stop, not where its data stops being on screen: past it the + * renderer magnifies the deepest tile it has, so the data is still shown + * and still has to be credited. Crediting a little too often costs a line + * of text; crediting too rarely breaks a licence. + */ + val credits = + remember(current) { + current.attributions().map { AttributionRule(attribution = it) } + } + + /** + * The ground: geometry only, drawn by the GPU, never invalidated by + * glyphs. One layer, mounted once, at the bottom. + */ + val ground = + // `credits` is a key so that swapping the style to one with different + // sources re-credits the map. Two styles with the same credits compare + // equal and the layer is left alone, which is the ordinary case -- a + // recolour keeps its data. + // + // `styleKey` is a key for the opposite reason: the same data drawn + // differently. A map refetches a raster source whose URL changed and + // not otherwise, so a restyle has to reach the template -- without it + // the tiles with the buildings still on them are served forever. + remember(groupId, tileSize, declaredTileSize, credits, styleKey) { + RasterLayerState( + id = "$groupId-geom", + source = + RasterLayerSource.UrlTemplate( + template = tileServer.urlTemplate("$groupId-geom", tileSize, styleKey), + tileSize = declaredTileSize, + maxZoom = maxZoom, + attributionRules = credits, + scheme = TileScheme.XYZ, + ), + opacity = opacity.coerceIn(0.0f, 1.0f), + visible = visible, + zIndex = 0, + ) + } + + /** + * The label overlays currently mounted: normally one, briefly two. + * + * Changing a raster layer's source URL is implemented as remove-then-add, + * so the layer vanishes for as long as the new source takes its first + * tiles. Adding the replacement alongside and dropping the old one a + * moment later hands over instead — and because the ground is its own + * layer underneath, the worst a handover can now cost is a moment of + * doubled labels, never a bare map. + */ + fun labelStateFor(generation: Int) = + RasterLayerState( + id = "$groupId-labels-$styleKey-g$generation", + source = + RasterLayerSource.UrlTemplate( + template = tileServer.urlTemplate("$groupId-labels", tileSize, "$styleKey-g$generation"), + tileSize = declaredTileSize, + maxZoom = maxZoom, + // Both halves carry the credit. `resolveMapAttributions` + // ends in `distinct()`, so it is printed once; putting it + // on both means hiding either half cannot silence it. + attributionRules = credits, + scheme = TileScheme.XYZ, + ), + opacity = opacity.coerceIn(0.0f, 1.0f), + visible = visible, + // Above the ground, and above the generation it replaces. + zIndex = 1000 + generation, + ) + + val mounted = + remember(groupId, tileSize, declaredTileSize) { + mutableStateListOf(labelStateFor(0)) + } + + LaunchedEffect(glyphGeneration) { + if (glyphGeneration == 0) return@LaunchedEffect + mounted.add(labelStateFor(glyphGeneration)) + // Long enough for the replacement's tiles to arrive. There is no + // per-source "loaded" signal to wait on, and holding the old layer a + // little too long only costs one extra layer for that moment. + kotlinx.coroutines.delay(HANDOVER_MS) + while (mounted.size > 1) { + mounted.removeAt(0) + } + } + + LaunchedEffect(opacity, visible) { + ground.opacity = opacity.coerceIn(0.0f, 1.0f) + ground.visible = visible + mounted.forEach { + it.opacity = opacity.coerceIn(0.0f, 1.0f) + it.visible = visible + } + } + + // Referencing `current` keeps the provider alive for as long as the layer is + // mounted, and makes the dependency explicit rather than incidental. + LaunchedEffect(current) { } + + RasterLayer(state = ground) + mounted.forEach { RasterLayer(state = it) } +} + +/** + * The direct path: the style is served as a document and the map draws it. + * + * Two effects rather than one so that a style change does not bounce the map + * through the previous design on its way to the new style: the document + * (keyed by content) is swapped, the support is told once more, and only a + * real unmount clears it. + */ +@Composable +private fun DirectVectorStyle( + styleJson: String, + support: VectorStyleSupport, + tileServer: com.mapconductor.core.tileserver.LocalTileServer, + onDiagnostics: ((List) -> Unit)?, + offlinePackage: OfflinePackage?, + online: Boolean, + headers: Map, +) { + // With a package, the map reads its tiles, glyphs and sprite from the + // local server, which answers from the package and -- online -- fetches + // upstream for the rest. The route carries the mode: a map remembers a + // tile it was told does not exist, so going back online has to change + // the URLs to be noticed. + val filesRoute = + remember(offlinePackage, online) { + offlinePackage?.let { + "vectortile-package-${it.manifest.styleDigest.take(12)}-${if (online) "online" else "offline"}" + } + } + DisposableEffect(filesRoute, offlinePackage) { + if (filesRoute != null && offlinePackage != null) { + tileServer.registerFiles( + routeId = filesRoute, + directory = offlinePackage.directory, + fallback = + if (online) { + { relative -> + offlinePackage.upstreamUrl(relative)?.let { VectorTileProvider.httpGet(it, headers) } + } + } else { + null + }, + ) + } + onDispose { if (filesRoute != null) tileServer.unregisterFiles(filesRoute) } + } + val served = + remember(styleJson, filesRoute) { + if (filesRoute != null && + offlinePackage != null + ) { + offlinePackage.styleServedBy(tileServer.filesUrl(filesRoute)) + } else { + styleJson + } + } + + // The id is the content and nothing else -- not the layer instance. The + // map only re-reads a style whose URL changed, so a changed style must + // change the URL; but a provider that rebuilds its view on a design + // change (MapTiler) remounts this layer with it, and if the remount + // minted a fresh URL it would be a fresh design, another rebuild, and + // so on -- the map never comes up. Same content, same URL, and the + // remount is a no-op. Two layers showing one style share the document, + // which is harmless: one basemap is all a map has. + val documentId = remember(served) { "vectortile-style-${served.hashCode().toUInt()}" } + + DisposableEffect(support) { + onDispose { support.clearStyle() } + } + + DisposableEffect(documentId, support) { + tileServer.registerDocument(documentId, "application/json", served.toByteArray()) + support.showStyle( + styleUrl = tileServer.documentUrl(documentId), + attributionRules = styleAttributions(styleJson).map { AttributionRule(attribution = it) }, + ) + onDiagnostics?.invoke( + listOf( + if (offlinePackage != null) { + "direct: the map reads the package itself (${if (online) "online" else "offline"})" + } else { + "direct: the map draws the style itself" + }, + ), + ) + onDispose { tileServer.unregisterDocument(documentId) } + } +} + +/** + * The `attribution` of every source in a style, in style order, without + * duplicates. A style that will not parse credits nothing here -- the map + * will refuse it anyway, more visibly. + */ +private fun styleAttributions(styleJson: String): List = + runCatching { + val sources = JSONObject(styleJson).optJSONObject("sources") ?: return emptyList() + sources + .keys() + .asSequence() + .mapNotNull { sources.optJSONObject(it)?.optString("attribution")?.takeIf { a -> a.isNotBlank() } } + .distinct() + .toList() + }.getOrDefault(emptyList()) + +/** + * How long the layer being replaced stays up. + * + * No signal says a raster source has drawn its first tiles, so this is a + * window rather than a wait. Too short brings the flash back; too long leaves + * two layers stacked, which costs a moment of overdraw and nothing else. + */ +private const val HANDOVER_MS = 900L diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileProvider.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileProvider.kt new file mode 100644 index 000000000..9a7de34d4 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileProvider.kt @@ -0,0 +1,1319 @@ +package com.mapconductor.vectortile + +import com.mapconductor.core.tileserver.TileProviderInterface +import com.mapconductor.core.tileserver.TileRequest +import org.json.JSONArray +import java.io.Closeable +import java.io.File +import java.net.HttpURLConnection +import java.net.URL +import java.util.concurrent.Semaphore +import kotlin.math.roundToInt +import android.util.Log +import android.util.LruCache + +/** + * Renders a MapLibre vector style to raster tiles, for map backends that cannot + * display a vector style themselves. + * + * Register it with `TileServerRegistry.get()` and point a + * [com.mapconductor.core.raster.RasterLayerSource.UrlTemplate] at the resulting + * route — which is what [VectorTileLayer] does for you. + * + * Network I/O happens here rather than in the native library, so the app's own + * HTTP behaviour keeps applying: [headers] covers auth tokens, and swapping + * [fetchTile] hands over completely. + */ +class VectorTileProvider private constructor( + private val renderer: VectorTileRenderer, + private val tileSize: Int, + private val renderScale: Int, + private val headers: Map, + private val fetchTile: (String) -> ByteArray?, + cacheBytes: Int, + private val diskCache: TileDiskCache?, + private val glyphCache: StyleAssetCache?, + private val spriteCache: StyleAssetCache?, + styleJson: String, + /** Null when rendering on the CPU. */ + private val gpu: GpuTileRasterizer?, +) : TileProviderInterface, + Closeable { + private val groundResolution = tileSize * renderScale + + /** Where rasterisation actually happens, after any fallback. */ + val renderMode: RenderMode = if (gpu != null) RenderMode.GPU else RenderMode.CPU + + /** + * Called when glyphs have arrived and the tiles drawn before them are + * missing labels. The layer refetches; nothing here can make the map do + * that on its own. + */ + @Volatile + var onGlyphsLoaded: (() -> Unit)? = null + + private val gpuRenderCount = + java.util.concurrent.atomic + .AtomicLong() + private val gpuFallbackCount = + java.util.concurrent.atomic + .AtomicLong() + + /** + * Tiles actually drawn by the GPU, and tiles that fell back to the CPU. + * + * Worth exposing rather than keeping internal: [renderMode] only says a GL + * context was obtained, and a path that quietly falls back on every tile + * looks exactly like a working one from the outside. + */ + val gpuRenders: Long get() = gpuRenderCount.get() + val gpuFallbacks: Long get() = gpuFallbackCount.get() + + private var sourceDiskCache: StyleAssetCache? = null + + /** + * Identifies the style for disk cache keys. Content-addressed, so a + * restyle misses rather than needing explicit invalidation. + */ + @Volatile + private var styleKey: String = TileDiskCache.digest(styleJson) + + /** Glyph URLs already claimed, so concurrent tiles fetch each once. */ + private val requestedGlyphs = java.util.Collections.synchronizedSet(HashSet()) + + /** Bumped when glyphs arrive, so tiles drawn before them stop being served. */ + private val glyphGeneration = + java.util.concurrent.atomic + .AtomicInteger() + + /** Set while a notification is already scheduled, so a burst sends one. */ + private val glyphNotifyPending = + java.util.concurrent.atomic + .AtomicBoolean(false) + + /** + * How long to let a burst of ranges settle before telling the layer. + * + * A viewport's worth arrives within a second or two of each other, and + * notifying per range would redraw every visible tile dozens of times to + * reach the same picture. + */ + private val glyphNotifyQuietMs = 400L + + /** + * How long to keep waiting while ranges are still in flight. + * + * The quiet window alone was not enough. Ranges do not arrive in one + * burst: six threads each take 0.4 to 1.3 seconds per range and a low + * zoom wants dozens, so arrivals are spread over many seconds and the + * 400ms window closed between them again and again. Every close was a + * handover, and a handover redraws every visible tile — that steady + * two-per-second replacement was the flicker. So the window is held open + * while any fetch is outstanding, and the whole viewport's labels appear + * in one go. The cap is there because a range that never answers must not + * hold the labels back forever. + */ + private val glyphNotifyMaxWaitMs = 10_000L + + /** + * Whether any tile has been drawn short of glyphs since the last handover. + * + * Panning turns up new labels, which fetch new ranges, which used to hand + * the whole viewport over again -- the generation reached 81 in half a + * minute of use, and each handover refetched and redrew everything on + * screen at roughly 0.6 to 0.9 seconds a tile. Most of those handovers + * changed nothing: the ranges had arrived before anything needed them. + */ + private val provisionalSinceHandover = + java.util.concurrent.atomic + .AtomicBoolean(false) + + /** + * Fetches source tiles, several at a time. + * + * Sized for the whole worker pool, not for one tile: eight tiles render at + * once and each plan is nine fetches, and when this pool held nine threads + * the whole screen fetched through one tile's worth of bandwidth -- + * measured concurrency across a cold screen was 1.2 with eight workers + * available. The threads spend their lives blocked on sockets, so they are + * cheap to hold. + */ + private val sourceFetchers = + java.util.concurrent.Executors.newFixedThreadPool(32) { runnable -> + Thread(runnable, "mc-tiles").apply { isDaemon = true } + } + + /** + * Source fetches under way, so the nine tiles that all want the same + * neighbour share one download instead of racing nine. + */ + private val inFlight = + java.util.concurrent.ConcurrentHashMap>() + + /** Glyph fetches queued or running, so the notify can wait for quiet. */ + private val glyphsInFlight = + java.util.concurrent.atomic + .AtomicInteger() + + /** + * Fetches glyph ranges off the tile threads. + * + * One range is a round trip of 0.4 to 1.3 seconds and a tile at low zoom + * wants dozens, so nothing waits on them: six at a time, and the tiles + * that were drawn without them are handed over when they land. + */ + private val glyphFetchers = + java.util.concurrent.Executors.newFixedThreadPool(6) { runnable -> + Thread(runnable, "mc-glyphs").apply { isDaemon = true } + } + + /** True when the style names no glyph source, so labels can never draw. */ + private val glyphsUnavailable: Boolean = renderer.glyphsUrlTemplate() == null + + /** + * Open once the ranges kept from earlier runs are back in the store. + * + * A tile drawn before that has no labels on it and has to be handed over + * later, which is the thing this is here to avoid, so the first render + * waits -- but only for reads of a few small local files, and only up to + * [GLYPH_WARM_WAIT_MS] so a slow disk cannot hold the map up. + */ + private val glyphsWarmed = java.util.concurrent.CountDownLatch(1) + + init { + Log.i(TAG, "rasterising on ${rendererDescription()}") + val cache = glyphCache + if (cache == null && !renderer.needsSprite()) { + glyphsWarmed.countDown() + } else { + Thread({ + val started = System.nanoTime() + val loaded = + if (cache == null || glyphsUnavailable) { + 0 + } else { + runCatching { cache.warm { renderer.addGlyphs(it) } }.getOrDefault(0) + } + // The sprite is looked for here too, because unlike glyphs its + // URLs come from the style: a sheet that is already on disk can + // be in place before the first tile rather than after it. + val icons = runCatching { loadSpriteFromDisk() }.getOrDefault(0) + glyphsWarmed.countDown() + if (Log.isLoggable(TAG, Log.DEBUG)) { + val ms = (System.nanoTime() - started) / 1_000_000 + Log.d(TAG, "loaded $loaded glyph ranges and $icons icons from disk in ${ms}ms") + } + // Only then the network, so a cold start does not hold the + // first tile behind two more round trips. + fetchSpriteIfMissing() + }, "mc-style-assets").apply { isDaemon = true }.start() + } + } + + /** The style's sprite pair, or null when it names none. */ + private fun spriteUrls(): Pair? { + val urls = runCatching { renderer.spriteUrls(1) }.getOrDefault(emptyList()) + return if (urls.size == 2) urls[0] to urls[1] else null + } + + /** Returns how many icons were loaded, 0 when the pair is not on disk. */ + private fun loadSpriteFromDisk(): Int { + if (closed || !renderer.needsSprite()) return 0 + val (indexUrl, imageUrl) = spriteUrls() ?: return 0 + val index = spriteCache?.get(indexUrl) ?: return 0 + val image = spriteCache.get(imageUrl) ?: return 0 + return runCatching { renderer.addSprite(index.decodeToString(), image) } + .onFailure { Log.w(TAG, "cached sprite would not parse; refetching", it) } + .getOrDefault(0) + } + + /** + * Fetches the sheet once, and hands the drawn tiles over when it lands. + * + * The same machinery as a glyph range, for the same reason: tiles drawn + * before the sheet arrived have holes where their icons belong. + */ + private fun fetchSpriteIfMissing() { + if (closed || !renderer.needsSprite()) return + val (indexUrl, imageUrl) = spriteUrls() ?: return + val index = runCatching { fetchTile(indexUrl) }.getOrNull() + val image = runCatching { fetchTile(imageUrl) }.getOrNull() + if (index == null || image == null || index.isEmpty() || image.isEmpty()) { + Log.w(TAG, "sprite unavailable: $indexUrl") + return + } + val icons = + runCatching { renderer.addSprite(index.decodeToString(), image) } + .onFailure { Log.w(TAG, "sprite would not parse: $indexUrl", it) } + .getOrDefault(0) + if (icons <= 0) return + spriteCache?.put(indexUrl, index) + spriteCache?.put(imageUrl, image) + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d(TAG, "sprite sheet in: $icons icons") + } + onGlyphsArrived() + } + + /** + * Source tiles keyed by URL. + * + * Not an optimisation detail: neighbouring target tiles routinely need the + * same source tile — always, once overzoom kicks in, where one magnified + * ancestor serves 16 targets — and a map asks for a whole viewport at once. + */ + private val cache = + object : LruCache(cacheBytes) { + // Sized in bytes, not entries. Counting entries is the default and + // it is wrong here: a basemap tile is 150-300 KB, so a few hundred + // entries is tens of megabytes, and the native allocator aborts the + // host process when it runs out — `catch_unwind` cannot save it. + override fun sizeOf( + key: String, + value: ByteArray, + ): Int = value.size + } + + /** + * Caps concurrent rasterisation. + * + * The tile server will happily run eight requests at once, but each render + * holds a decoded tile and a full pixmap, and on a mid-range device eight + * at a time both exhausts memory and thrashes the CPU — measured render + * times climbed from 235 ms to 1790 ms purely from contention. + */ + private val renderSlots = + Semaphore( + maxOf(1, Runtime.getRuntime().availableProcessors() / 2), + true, + ) + + /** + * Bounds only GPU input packing and native tessellation. + * + * The Pixel 5a gains little throughput from its seventh and eighth + * simultaneous preparation, while latency and memory rise sharply. Six + * slots also let its six street-zoom viewport tiles start immediately; + * only excess/fallback work queues. This is deliberately separate from + * [renderSlots]: labels must not wait behind geometry that will later + * serialize on the GL thread anyway. + */ + private val gpuPrepareSlots = + Semaphore( + minOf(6, maxOf(1, Runtime.getRuntime().availableProcessors() - 1)), + true, + ) + + /** URLs known to hold nothing, so a missing tile is not re-requested. */ + private val empties = java.util.Collections.synchronizedSet(HashSet()) + + @Volatile + private var closed = false + + /** Which rasteriser to use. */ + enum class RenderMode { + /** `tiny-skia`, on the calling thread. Always available. */ + CPU, + + /** + * OpenGL ES. Roughly 3x faster on a mid-range device and, more to the + * point, moves the drawing off the CPU that the map SDK and the app + * are already competing for. + * + * Output is not bit-identical to [CPU]: anti-aliasing comes from MSAA + * rather than analytic coverage, which measured at 0.39% of pixels + * differing on a dense street tile, all of it on thin-line edges. + */ + GPU, + + /** [GPU] where a context can be created, otherwise [CPU]. */ + AUTO, + } + + companion object { + private const val TAG = "VectorTileProvider" + const val DEFAULT_TILE_SIZE: Int = 512 + + /** + * Source tile cache budget, in bytes. + * + * Raised when tiles started fetching their neighbours: the working set + * for a screen went from the tiles on it to those plus the ring around + * them, and at low zoom a tile is most of a megabyte. Too small a + * cache here does not lose the picture, it re-fetches it. + */ + const val DEFAULT_CACHE_BYTES: Int = 48 * 1024 * 1024 + + /** Rendered tile disk cache budget, in bytes. */ + const val DEFAULT_DISK_CACHE_BYTES: Long = 64L * 1024 * 1024 + + /** Source MVT disk cache budget, in bytes. */ + private const val DEFAULT_SOURCE_CACHE_BYTES: Long = 128L * 1024 * 1024 + + /** + * Glyph range disk cache budget, in bytes. + * + * Measured rather than guessed: one screen of Tokyo wants 69 ranges + * and they average 150KB each, so a single view is already 10MB. At + * 8MB the sweep threw away exactly what the next launch was about to + * ask for -- 43 of the 69 survived and the map still spent 3.4 + * seconds unlabelled. This holds roughly 200 ranges, which is a + * couple of scripts' worth of roaming. + */ + const val DEFAULT_GLYPH_CACHE_BYTES: Long = 32L * 1024 * 1024 + + /** + * Sprite sheet disk cache budget, in bytes. + * + * A style has one sheet, and a large one is a few hundred kilobytes; + * the room is for the handful of styles an app switches between. + */ + const val DEFAULT_SPRITE_CACHE_BYTES: Long = 4L * 1024 * 1024 + + /** + * How long a tile waits for the stored ranges to be read back. + * + * Reading them is local and takes milliseconds; the limit is only so + * that a wedged filesystem costs a mute first tile rather than a map + * that never draws. + */ + private const val GLYPH_WARM_WAIT_MS: Long = 1_500 + private const val STAT_MEMORY = 0 + private const val STAT_DISK = 1 + private const val STAT_NETWORK = 2 + private const val STAT_SHARED = 3 + private const val STAT_CANCELLED = 4 + private const val STAT_QUEUE_MS = 5 + private const val STAT_BLOCKED = 6 + private const val STAT_COUNT = 7 + + /** + * The least grain the label overlay is drawn at, as a multiple of the + * tile size. + * + * Two, because a glyph drawn at one-to-one arrives at the eye + * stretched to blur, and labels are the one thing on a map read as + * shapes. On a screen denser than this, [renderScale] already asks + * for those pixels and this adds nothing -- the larger of the two + * wins, not the product. The image covers the same ground either + * way; only its grain changes. + * + * Matches `VectorTileProvider.labelResolution` on iOS. + */ + private const val LABEL_RESOLUTION = 2 + + /** + * The display's own pixels per style pixel, for when the caller does + * not say. + * + * `Resources.getSystem()` rather than a `Context`: this module does not + * hold one, and the default display's density is what a map fills the + * screen with. A Compose host has a better answer — `LocalDensity` — + * and [VectorTileLayer] passes it. + */ + private fun displayRenderScale(): Int = + android.content.res.Resources + .getSystem() + .displayMetrics + .density + .roundToInt() + .coerceAtLeast(1) + + /** + * @param styleJson a MapLibre style document + * @param renderScale image pixels drawn per style pixel. Null follows the + * display's own density, which is what stops a 3x screen stretching + * every tile; the geographic size of a tile does not change either way. + * @param headers sent with every source tile request + * @param fetchTile overrides fetching entirely; return null for "no tile" + * @throws IllegalArgumentException if the style cannot be parsed + */ + @JvmStatic + @JvmOverloads + fun create( + styleJson: String, + tileSize: Int = DEFAULT_TILE_SIZE, + headers: Map = emptyMap(), + cacheBytes: Int = DEFAULT_CACHE_BYTES, + diskCacheDir: File? = null, + diskCacheBytes: Long = DEFAULT_DISK_CACHE_BYTES, + renderMode: RenderMode = RenderMode.AUTO, + renderScale: Int? = null, + fetchTile: ((String) -> ByteArray?)? = null, + ): VectorTileProvider { + @Suppress("NAME_SHADOWING") + val renderScale = (renderScale ?: displayRenderScale()).coerceAtLeast(1) + // No upper bound on the scale itself -- iOS takes whatever the + // screen reports and so does this -- but the image it implies has + // to be a texture the GPU will accept. + require(tileSize in 1..(8192 / maxOf(renderScale, LABEL_RESOLUTION))) { + "tile size $tileSize at scale $renderScale exceeds the maximum texture size" + } + // The renderer needs the dp a tile covers, not the pixels a render + // asks for: the label pass draws at twice the pixels, and the + // style's sizes are screen units either way. + val renderer = VectorTileRenderer.create(styleJson, tileSize) + val gpu = + when (renderMode) { + RenderMode.CPU -> null + // AUTO and GPU both probe; AUTO falls back silently, GPU says + // so, because asking for the GPU and quietly getting the CPU + // is how a performance regression hides. + RenderMode.AUTO -> GpuTileRasterizer.createOrNull(tileSize * renderScale) + RenderMode.GPU -> + GpuTileRasterizer.createOrNull(tileSize * renderScale).also { + if (it == null) Log.w(TAG, "GPU requested but unavailable; using the CPU") + } + } + return VectorTileProvider( + renderer = renderer, + tileSize = tileSize, + renderScale = renderScale, + headers = headers, + fetchTile = fetchTile ?: { url -> httpGet(url, headers) }, + cacheBytes = cacheBytes, + diskCache = diskCacheDir?.let { TileDiskCache(it, diskCacheBytes) }, + glyphCache = + diskCacheDir?.let { + StyleAssetCache(File(it, "glyphs"), DEFAULT_GLYPH_CACHE_BYTES) + }, + spriteCache = + diskCacheDir?.let { + StyleAssetCache(File(it, "sprites"), DEFAULT_SPRITE_CACHE_BYTES) + }, + styleJson = styleJson, + gpu = gpu, + ).apply { + sourceDiskCache = + diskCacheDir?.let { + StyleAssetCache(File(it, "sources"), DEFAULT_SOURCE_CACHE_BYTES) + } + } + } + + internal fun httpGet( + url: String, + headers: Map, + ): ByteArray? { + val connection = URL(url).openConnection() as HttpURLConnection + var reuse = false + return try { + connection.requestMethod = "GET" + connection.connectTimeout = 15_000 + connection.readTimeout = 15_000 + // Tiles are gzipped on the wire by most servers; the client + // undoes that transparently when the header is left to it. + headers.forEach(connection::setRequestProperty) + when (val status = connection.responseCode) { + // A missing tile is normal at the edge of a source's coverage. + HttpURLConnection.HTTP_NOT_FOUND, HttpURLConnection.HTTP_NO_CONTENT -> { + connection.errorStream?.use { it.readBytes() } + reuse = true + null + } + in 200..299 -> { + val bytes = connection.inputStream.use { it.readBytes() } + // Draining the body to completion is what lets the + // socket go back to the pool. + reuse = true + bytes.takeIf { it.isNotEmpty() } + } + else -> { + connection.errorStream?.use { it.readBytes() } + reuse = true + throw java.io.IOException("tile fetch failed: $status $url") + } + } + } finally { + // `disconnect()` tears the socket down instead of returning it + // to the keep-alive pool. With a viewport's worth of tiles + // going to one host, that means a fresh TLS handshake per + // tile — so it is only used when the connection is already + // unusable. + if (!reuse) connection.disconnect() + } + } + } + + /** + * The credits this style's sources ask to be shown. + * + * These are not optional. A style is data under someone's licence, and the + * sample basemap draws OpenStreetMap, whose licence requires the credit; + * reading it out of the style and then not showing it is the one way this + * layer can be used wrongly without anything looking wrong. May contain + * HTML — the credit is normally a link to the licence. + */ + fun attributions(): List { + val array = JSONArray(renderer.attributions()) + return (0 until array.length()).map { array.getString(it) } + } + + /** Reasons the current style may not render as intended. */ + fun diagnostics(): List { + val array = JSONArray(renderer.diagnostics()) + return (0 until array.length()).map { array.getString(it) } + } + + /** Describes the GL context in use, or "cpu" when rasterising on the CPU. */ + fun rendererDescription(): String = gpu?.describe() ?: "cpu" + + /** + * Replaces the style. Fetched vector tiles stay valid — the geometry is + * unchanged, only the paint applied to it — so recolouring costs a + * re-rasterise and no network traffic. + * + * The caller still has to make the map drop its *raster* tiles; pass a new + * `cacheKey` to `LocalTileServer.urlTemplate`. + */ + fun setStyle(styleJson: String) { + renderer.setStyle(styleJson) + // Rendered tiles are keyed by style, so the old ones simply stop being + // found; there is nothing to invalidate. + styleKey = TileDiskCache.digest(styleJson) + } + + override fun renderTile(request: TileRequest): ByteArray? = renderTile(request) { false } + + override fun renderTile( + request: TileRequest, + isCancelled: () -> Boolean, + ): ByteArray? = renderTile(request, isCancelled, Content.FULL) + + /** What one of this provider's routes serves. */ + private enum class Content { FULL, GEOMETRY, LABELS } + + /** + * The style's geometry alone: fills, lines, patterns, no labels. + * + * Serve this and [labelTiles] as two stacked raster layers and the user + * sees one map -- but the halves fail and refresh independently. Glyphs + * arriving refresh only the transparent overlay, so the ground never + * flashes; and the ground is drawn by the GPU while labels are drawn by + * the CPU, in parallel rather than in line. + */ + val geometryTiles: TileProviderInterface = + object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray? = renderTile(request, { false }, Content.GEOMETRY) + + override fun renderTile( + request: TileRequest, + isCancelled: () -> Boolean, + ): ByteArray? = renderTile(request, isCancelled, Content.GEOMETRY) + } + + /** The labels and icons alone, on a transparent ground. */ + val labelTiles: TileProviderInterface = + object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray? = renderTile(request, { false }, Content.LABELS) + + override fun renderTile( + request: TileRequest, + isCancelled: () -> Boolean, + ): ByteArray? = renderTile(request, isCancelled, Content.LABELS) + } + + private fun renderTile( + request: TileRequest, + isCancelled: () -> Boolean, + content: Content, + ): ByteArray? { + if (closed) return null + + // Two keys, because a rendered tile goes stale for one reason only: + // it was drawn while some of its glyphs were still on the way. A tile + // that had them all is finished, and no later arrival can change it, + // so it is stored under a key with no generation in it and survives + // every handover. Only the ones that were drawn short are tied to the + // generation they were drawn at, and only they are redrawn. + fun key(generation: String) = + TileDiskCache.digest( + styleKey, + "$tileSize", + // The renderer's own generation: a build that draws more + // than the one that filled this cache must not serve its + // tiles. + "v${VectorTileRenderer.OUTPUT_VERSION}", + generation, + // Both halves are drawn at a scale the display chose, so a + // tile from one screen must never be served to another -- + // nothing else about the key says how many pixels it holds. + "scale$renderScale", + "${request.z}/${request.x}/${request.y}", + ) + + val completeKey = + diskCache?.let { + when (content) { + // Geometry has no glyphs to be short of; one key, forever. + Content.GEOMETRY -> key("geom") + Content.LABELS -> key("labels-complete") + Content.FULL -> key("complete") + } + } + val provisionalKey = + when (content) { + Content.GEOMETRY -> null + Content.LABELS -> diskCache?.let { key("labels-g${glyphGeneration.get()}") } + Content.FULL -> diskCache?.let { key("g${glyphGeneration.get()}") } + } + for (candidate in listOfNotNull(completeKey, provisionalKey)) { + val hit = diskCache?.get(candidate) + if (hit != null) { + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d( + TAG, + "tile ${request.z}/${request.x}/${request.y} content=$content disk-hit " + + "bytes=${hit.size}", + ) + } + return hit + } + } + + val plan = JSONArray(renderer.plan(request.z, request.x, request.y)) + val tiles = ArrayList(plan.length()) + + // Fetch and rasterise are timed separately: when a tile is slow, the + // answer is almost always one or the other, and guessing wastes time. + val fetchStarted = System.nanoTime() + // In parallel, because a plan is no longer one tile: the renderer also + // asks for the ring of neighbours so a label at the edge can be drawn + // whole, and nine round trips one after another is a second of waiting + // for what takes a fraction of it at once. Most are cache hits in + // steady use -- every tile is its neighbours' neighbour. + val urls = + (0 until plan.length()).map { + val source = plan.getJSONObject(it) + // Preserve positional entries for Rust's plan, but avoid both + // downloading and packing neighbours used only by labels. + if (content == Content.GEOMETRY && source.optBoolean("labelsOnly", false)) { + null + } else { + source.getString("url") + } + } + val fetchStats = + Array(STAT_COUNT) { + java.util.concurrent.atomic + .AtomicLong() + } + val pending = MutableList?>(urls.size) { null } + urls.indices + .sortedBy { index -> + val labelsOnly = plan.getJSONObject(index).optBoolean("labelsOnly", false) + if (labelsOnly) 1_000 + index else index + }.forEach { index -> + val url = urls[index] + pending[index] = + if (url == null) { + java.util.concurrent.CompletableFuture + .completedFuture(null) + } else { + val queued = System.nanoTime() + sourceFetchers.submit { + fetchStats[STAT_QUEUE_MS].addAndGet((System.nanoTime() - queued) / 1_000_000) + if (closed) null else sourceTile(url, fetchStats) + } + } + } + for (future in pending) { + if (isCancelled()) { + fetchStats[STAT_CANCELLED].addAndGet(pending.count { it?.cancel(false) == true }.toLong()) + pending.forEach { it?.cancel(false) } + return null + } + tiles.add(runCatching { future?.get() }.getOrNull()) + } + val fetchMs = (System.nanoTime() - fetchStarted) / 1_000_000 + if (closed) return null + + // Cached ranges belong in the store before the tile is judged to be + // missing them; otherwise the first tile of a launch is drawn bare and + // handed over a moment later for no reason. Geometry has no glyphs, so + // it does not wait on them. + if (content != Content.GEOMETRY && glyphsWarmed.count > 0L) { + runCatching { + glyphsWarmed.await(GLYPH_WARM_WAIT_MS, java.util.concurrent.TimeUnit.MILLISECONDS) + } + } + + // Short of its sheet counts the same as short of its glyphs: the tile + // is missing ink it will have later. + val drawnShortOfGlyphs = + content != Content.GEOMETRY && + (requestGlyphs(request, tiles) || renderer.needsSprite()) + + // The last chance to bail. Past here the work is native and cannot be + // interrupted, and it is the part that takes hundreds of milliseconds + // -- a tile drawn for a viewport the map has left holds up the tiles + // it is waiting for, because the render slots and the GL thread are + // shared. + if (isCancelled()) { + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d(TAG, "tile ${request.z}/${request.x}/${request.y} dropped before rendering") + } + return null + } + + val renderStarted = System.nanoTime() + val groundKey = key("geom") + // A tile drawn while the network was off and a source was not in the + // package is missing ink, like one drawn short of glyphs -- but + // nothing will arrive to redraw it, so it must not be kept at all. + val drawnShortOfSources = fetchStats[STAT_BLOCKED].get() > 0 + val keepGroundAs = if (drawnShortOfSources) null else groundKey + val png = + when (content) { + Content.LABELS -> renderLabelTile(request, tiles, isCancelled) + Content.FULL -> + groundRasters.get(groundKey)?.let { compositeLabels(request, it, tiles) } + ?: renderGroundTile(request, tiles, isCancelled, content, cacheGroundAs = keepGroundAs) + Content.GEOMETRY -> renderGroundTile(request, tiles, isCancelled, content, cacheGroundAs = null) + } + val renderMs = (System.nanoTime() - renderStarted) / 1_000_000 + + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d( + TAG, + "tile ${request.z}/${request.x}/${request.y} content=$content " + + "sources=${urls.count { it != null }} planned=${plan.length()} fetch=${fetchMs}ms " + + "render=${renderMs}ms bytes=${png?.size ?: 0} " + + "mvt(mem=${fetchStats[STAT_MEMORY].get()} disk=${fetchStats[STAT_DISK].get()} " + + "net=${fetchStats[STAT_NETWORK].get()} shared=${fetchStats[STAT_SHARED].get()} " + + "blocked=${fetchStats[STAT_BLOCKED].get()} cancel=${fetchStats[STAT_CANCELLED].get()} " + + "queue=${fetchStats[STAT_QUEUE_MS].get()}ms)", + ) + } + if (drawnShortOfGlyphs) provisionalSinceHandover.set(true) + if (png != null && !drawnShortOfSources) { + val store = if (drawnShortOfGlyphs) provisionalKey else completeKey + if (store != null) diskCache?.put(store, png) + } + return png + } + + /** + * The ground of every tile the GPU drew, straight RGBA, keyed like the + * disk cache. A glyph generation arriving redraws the tile, and with this + * the redraw is the labels and a PNG encode, not the geometry again. + */ + private val groundRasters = + object : LruCache(64 shl 20) { + override fun sizeOf( + key: String, + value: ByteArray, + ): Int = value.size + } + + /** + * Labels over a ground the GPU drew earlier: the whole cost of a glyph + * generation arriving, once the ground is in [groundRasters]. + */ + private fun compositeLabels( + request: TileRequest, + ground: ByteArray, + tiles: List, + ): ByteArray? { + if (ground.size != groundResolution * groundResolution * 4) return null + val rgba = ground.copyOf() + if (!glyphsUnavailable) { + runCatching { renderer.drawLabels(request.z, request.x, request.y, groundResolution, rgba, tiles) } + .onFailure { Log.w(TAG, "label pass failed on the cached ground", it) } + } + // The encoder reads a direct buffer only. + val buffer = + java.nio.ByteBuffer + .allocateDirect(rgba.size) + .order(java.nio.ByteOrder.nativeOrder()) + buffer.put(rgba) + buffer.rewind() + return com.mapconductor.core.tileserver.TilePngEncoder + .encode(buffer, groundResolution, groundResolution, premultiplied = false) + } + + /** + * Draws the ground: on the GPU when there is one and no pattern in the + * tile, on the CPU otherwise. [Content.FULL] also composites labels over + * the readback, the single-layer behaviour. + */ + private fun renderGroundTile( + request: TileRequest, + tiles: List, + isCancelled: () -> Boolean, + content: Content, + cacheGroundAs: String?, + ): ByteArray? { + // Patterns and complex polygons use the CPU; the latter avoids + // triangulation that can take tens of seconds on a tablet. + val onGpu = + gpu != null && + runCatching { !renderer.needsCpu(request.z, tiles) }.getOrDefault(true) + if (gpu != null && !onGpu && Log.isLoggable(TAG, Log.DEBUG)) { + Log.d( + TAG, + "tile ${request.z}/${request.x}/${request.y} drawn on the CPU: " + + "a pattern or complex polygon requires scanline rendering", + ) + } + if (onGpu) { + // GL submission is serialized by the rasterizer. Sharing the + // label semaphore here increased viewport latency on Pixel 5a. + val drawn = + try { + renderOnGpu(request, tiles, withLabels = content == Content.FULL, isCancelled, cacheGroundAs) + } catch (error: Throwable) { + // Logged, not swallowed: a silent catch here is what made a + // GPU path that fell back on every single tile look healthy. + Log.w(TAG, "GPU render failed; falling back to the CPU", error) + null + } + if (drawn != null) { + gpuRenderCount.incrementAndGet() + return drawn + } + if (closed || isCancelled()) return null + gpuFallbackCount.incrementAndGet() + } + // A GPU failure must not lose the tile; the CPU can always draw it. + if (!renderSlots.acquireUnlessCancelled { closed || isCancelled() }) return null + return try { + // Waiting for a slot is where a tile spends its time when the map + // is busy, and the map can lose interest while it waits. + if (closed || isCancelled()) return null + runCatching { + renderer.render( + request.z, + request.x, + request.y, + groundResolution, + tiles, + geometryOnly = content == Content.GEOMETRY, + ) + }.getOrNull() + } finally { + renderSlots.release() + } + } + + /** + * Draws the labels and icons on a transparent ground. + * + * Pure CPU: no GL thread, no readback -- which is the point of serving + * them as their own layer. Eight of these can run at once while the GPU + * draws geometry underneath. + */ + private fun renderLabelTile( + request: TileRequest, + tiles: List, + isCancelled: () -> Boolean, + ): ByteArray? { + val queued = System.nanoTime() + if (!renderSlots.acquireUnlessCancelled { closed || isCancelled() }) return null + val started = System.nanoTime() + return try { + if (isCancelled()) return null + // Drawn at twice the tile's nominal size. The image is stretched + // over the same ground either way, and at one-to-one every glyph + // was being blown up by the screen's density and read as blur -- + // text is where resolution is seen, so text is where it is spent. + // The ground layer stays at one-to-one: a fill's edge does not + // show it the way a letter does, and its cost is per pixel on the + // GPU readback. + val resolution = tileSize * maxOf(renderScale, LABEL_RESOLUTION) + val rendered = + runCatching { + renderer.renderLabels(request.z, request.x, request.y, resolution, tiles) + }.getOrElse { + Log.w(TAG, "label tile failed", it) + return null + } + val placed = rendered?.placed ?: 0 + // A tile with nothing on it is common -- water, fields -- and one + // shared transparent PNG serves them all. + val drawn = System.nanoTime() + val png = + if (rendered == null) { + emptyLabelTile + } else { + try { + encodeLabelTile(rendered.buffer, resolution) + } finally { + rendered.close() + } + } + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d( + TAG, + "labels ${request.z}/${request.x}/${request.y} placed=$placed " + + "queue=${(started - queued) / 1_000_000.0}ms " + + "draw=${(drawn - started) / 1_000_000.0}ms " + + "encode=${(System.nanoTime() - drawn) / 1_000_000.0}ms", + ) + } + png + } finally { + renderSlots.release() + } + } + + /** One fully transparent tile, encoded once. */ + private val emptyLabelTile: ByteArray by lazy { + val resolution = tileSize * maxOf(renderScale, LABEL_RESOLUTION) + encodeLabelTile(ByteArray(resolution * resolution * 4), resolution) + ?: ByteArray(0) + } + + /** + * Direct buffers for the label encoder. + * + * Capped below the worker count on purpose: at label resolution each is + * several megabytes, and [renderSlots] already bounds how many renders + * run at once. + */ + private val labelEncodeBuffers = + java.util.concurrent.ArrayBlockingQueue(4) + + private fun encodeLabelTile( + rgba: ByteArray, + resolution: Int, + ): ByteArray? { + val buffer = + labelEncodeBuffers.poll()?.takeIf { it.capacity() >= rgba.size } + ?: java.nio.ByteBuffer.allocateDirect(rgba.size) + return try { + buffer.clear() + buffer.put(rgba) + buffer.rewind() + // Premultiplied, not straight. The label pass composites source- + // over into a transparent buffer, and that arithmetic leaves each + // channel scaled by its own alpha. Encoding it as straight alpha + // is what turned the style's white halo into a grey shadow: white + // at 0.8 was stored as the grey 204 and composited again by the + // map. On the old opaque single layer alpha was always one, so + // the two readings agreed and the bug had nowhere to show. + com.mapconductor.core.tileserver.TilePngEncoder + .encode(buffer, resolution, resolution, premultiplied = true) + } finally { + labelEncodeBuffers.offer(buffer) + } + } + + /** Encodes Rust-owned label pixels without another 4 MiB staging copy. */ + private fun encodeLabelTile( + rgba: java.nio.ByteBuffer, + resolution: Int, + ): ByteArray? = + com.mapconductor.core.tileserver.TilePngEncoder + .encode(rgba, resolution, resolution, premultiplied = true) + + /** + * Starts fetching the glyph ranges this tile's labels need, and returns. + * + * Waiting was the obvious thing and the wrong one: a range is a 0.4 to 1.3 + * second round trip, a tile at low zoom wants dozens, and the tile drew + * nothing until the last one landed — 13 seconds for 69 ranges, which is + * what "it stops when you zoom out" was. The tile is drawn with whatever + * glyphs are already in, exactly as MapLibre does it, and the ones that + * arrive later bring the labels with them through [onGlyphsLoaded]. + * + * Returns whether this tile is about to be drawn without glyphs it wants, + * which is what decides between the two cache keys and whether a handover + * is worth making. + */ + private fun requestGlyphs( + request: TileRequest, + tiles: List, + ): Boolean { + if (glyphsUnavailable || closed) return false + val needed = + runCatching { renderer.neededGlyphs(request.z, request.x, request.y, tiles) } + .getOrElse { emptyList() } + if (needed.isEmpty()) return false + + // Only the ranges nobody has claimed yet. Two tiles wanting the same + // range at once would otherwise both fetch it. + val mine = needed.filter { requestedGlyphs.add(it) } + if (mine.isEmpty()) return true + + for (url in mine) { + glyphsInFlight.incrementAndGet() + val queued = + runCatching { + glyphFetchers.execute { + try { + if (closed) return@execute + val cached = glyphCache?.get(url) + val fetched = if (cached != null) Result.success(cached) else runCatching { fetchTile(url) } + if (fetched.exceptionOrNull() is OfflineUnavailableException) { + // Unclaimed: the range is there to be had + // once the network is back. + requestedGlyphs.remove(url) + return@execute + } + val bytes = + fetched.getOrNull()?.also { + // Ranges do not change, so this is kept + // without an expiry. + if (cached == null) glyphCache?.put(url, it) + } + if (bytes == null || bytes.isEmpty()) { + // Left in the claimed set: a range the server + // does not have will not appear on a retry. + Log.w(TAG, "glyph range unavailable: $url") + return@execute + } + val added = + runCatching { renderer.addGlyphs(bytes) }.getOrElse { + Log.w(TAG, "glyph range would not parse: $url", it) + 0 + } + if (added > 0) onGlyphsArrived() + } finally { + glyphsInFlight.decrementAndGet() + } + } + } + if (queued.isFailure) glyphsInFlight.decrementAndGet() + } + return true + } + + /** + * Tells the layer that tiles drawn before now are missing labels. + * + * Coalesced: a viewport's worth of ranges lands in a burst, and asking the + * map to refetch on each one would redraw everything dozens of times for + * the same result. The generation is what makes the already-rendered tiles + * stale — without it the caches would keep serving the unlabelled ones. + */ + private fun onGlyphsArrived() { + glyphGeneration.incrementAndGet() + if (!glyphNotifyPending.compareAndSet(false, true)) return + // Its own thread: the fetch pool is six wide and a sleeper sitting in + // it is one fewer range in flight. + val waiter = + Thread { + val deadline = System.nanoTime() + glyphNotifyMaxWaitMs * 1_000_000L + try { + Thread.sleep(glyphNotifyQuietMs) + // Hold the window open while ranges are still coming. + while (glyphsInFlight.get() > 0 && System.nanoTime() < deadline && !closed) { + Thread.sleep(glyphNotifyQuietMs) + } + } catch (_: InterruptedException) { + glyphNotifyPending.set(false) + return@Thread + } + glyphNotifyPending.set(false) + if (closed) return@Thread + // Nothing to hand over to: every tile drawn since the last one + // had all the glyphs it wanted, so the picture on screen is + // already the finished picture. A handover here would refetch + // and redraw the viewport to arrive at the same pixels. + if (!provisionalSinceHandover.compareAndSet(true, false)) { + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d(TAG, "glyphs arrived but no tile was waiting on them") + } + return@Thread + } + // The vector tiles are deliberately not dropped. Glyphs change + // what a tile is drawn *with*, not what it contains, and + // throwing them away made every handover refetch the viewport + // over the network before it could redraw it. + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d(TAG, "glyph generation -> ${glyphGeneration.get()}; tiles hand over") + } + runCatching { onGlyphsLoaded?.invoke() } + .onFailure { Log.w(TAG, "glyph notification failed", it) } + } + waiter.isDaemon = true + waiter.name = "mc-glyph-notify" + waiter.start() + } + + private fun renderOnGpu( + request: TileRequest, + tiles: List, + withLabels: Boolean, + isCancelled: () -> Boolean, + cacheGroundAs: String? = null, + ): ByteArray? { + val rasterizer = gpu ?: return null + val queued = System.nanoTime() + if (closed || isCancelled()) return null + if (!gpuPrepareSlots.acquireUnlessCancelled { closed || isCancelled() }) return null + val started = System.nanoTime() + val tessellated = + try { + if (closed || isCancelled()) return null + val lengths = IntArray(tiles.size) { tiles[it]?.size ?: 0 } + val data = ByteArray(lengths.sum()) + var offset = 0 + for (tile in tiles) { + if (tile == null) continue + tile.copyInto(data, offset) + offset += tile.size + } + TessellatedTile( + renderer.tessellate( + request.z, request.x, request.y, groundResolution, data, lengths, + ), + ) + } finally { + gpuPrepareSlots.release() + } + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d( + TAG, + "prepare ${request.z}/${request.x}/${request.y} " + + "queue=${(started - queued) / 1_000_000.0}ms " + + "cpu=${(System.nanoTime() - started) / 1_000_000.0}ms", + ) + } + if (closed || isCancelled()) { + tessellated.close() + return null + } + // The tessellator produces fills and lines; labels come from a + // distance field per glyph and are drawn over the readback. Without + // this the GPU path lost every label a style asked for and said + // nothing about it. + val drawLabels = withLabels && !glyphsUnavailable + val decorate: ((ByteArray) -> Unit)? = + if (!drawLabels && cacheGroundAs == null) { + null + } else { + { rgba -> + if (cacheGroundAs != null) groundRasters.put(cacheGroundAs, rgba.copyOf()) + if (drawLabels) { + runCatching { + renderer.drawLabels(request.z, request.x, request.y, groundResolution, rgba, tiles) + }.onFailure { Log.w(TAG, "label pass failed on the GPU readback", it) } + } + } + } + return rasterizer.renderPng(tessellated, decorate) { closed || isCancelled() } + } + + private fun sourceTile( + url: String, + stats: Array, + ): ByteArray? { + cache.get(url)?.let { + stats[STAT_MEMORY].incrementAndGet() + return it + } + if (empties.contains(url)) return null + // Share disk reads as well as downloads. A cold memory cache lets + // neighbouring label tiles ask for the same file simultaneously. + val mine = java.util.concurrent.CompletableFuture() + val existing = inFlight.putIfAbsent(url, mine) + if (existing != null) { + stats[STAT_SHARED].incrementAndGet() + return runCatching { existing.get() }.getOrNull() + } + try { + // A prior flight may have filled memory between our initial + // lookup and claiming this URL. Recheck before doing any I/O. + val bytes = + cache.get(url)?.also { + stats[STAT_MEMORY].incrementAndGet() + } ?: if (empties.contains(url)) { + null + } else { + sourceDiskCache?.get(url)?.also { + stats[STAT_DISK].incrementAndGet() + cache.put(url, it) + } ?: fetchAndRemember(url, stats) + } + mine.complete(bytes) + return bytes + } catch (error: Throwable) { + mine.complete(null) + throw error + } finally { + inFlight.remove(url) + } + } + + private fun fetchAndRemember( + url: String, + stats: Array, + ): ByteArray? { + // A source that answers "no tile here" is remembered, because it will + // answer the same way tomorrow. A source that fails to answer is not: + // treating a dropped connection as an empty tile leaves a hole in the + // map for as long as the app runs, and the hole is invisible from + // here -- the tile simply draws without that data. + stats[STAT_NETWORK].incrementAndGet() + val fetched = runCatching { fetchTile(url) } + val bytes = fetched.getOrNull() + if (bytes == null) { + if (fetched.exceptionOrNull() is OfflineUnavailableException) { + // Not an error and not an answer: the network is off. The + // tile is drawn without this source and not kept, so it is + // drawn again once the network is back. + stats[STAT_BLOCKED].incrementAndGet() + } else if (fetched.isSuccess) { + empties.add(url) + } else { + // A network failure is the same for the tile: drawn without + // this source, not kept, tried again next time. + stats[STAT_BLOCKED].incrementAndGet() + Log.w(TAG, "source tile failed; will try again: $url", fetched.exceptionOrNull()) + } + return null + } + cache.put(url, bytes) + sourceDiskCache?.put(url, bytes) + return bytes + } + + private val closeStarted = + java.util.concurrent.atomic + .AtomicBoolean() + + private fun beginClose(): Boolean { + if (!closeStarted.compareAndSet(false, true)) return false + closed = true + onGlyphsLoaded = null + glyphFetchers.shutdownNow().forEach { (it as? java.util.concurrent.Future<*>)?.cancel(false) } + sourceFetchers.shutdownNow().forEach { (it as? java.util.concurrent.Future<*>)?.cancel(false) } + return true + } + + private fun releaseResources() { + try { + gpu?.close() + } finally { + try { + // Retain the renderer's write lock: an in-flight JNI call + // must finish before its native allocation can be freed. + renderer.close() + } finally { + cache.evictAll() + groundRasters.evictAll() + empties.clear() + } + } + } + + /** Stops accepting tiles immediately and waits for native/GL cleanup off the UI thread. */ + fun closeAsync() { + if (!beginClose()) return + Thread({ + try { + releaseResources() + } catch (error: Exception) { + Log.e(TAG, "asynchronous renderer cleanup failed", error) + } + }, "vectortile-close").apply { isDaemon = true }.start() + } + + /** Releases resources synchronously. Use [closeAsync] when disposing a UI layer. */ + override fun close() { + if (!beginClose()) return + releaseResources() + } +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileRasteriser.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileRasteriser.kt new file mode 100644 index 000000000..1c9043b97 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileRasteriser.kt @@ -0,0 +1,281 @@ +package com.mapconductor.vectortile + +import com.mapconductor.core.map.AttributionRule +import com.mapconductor.core.map.MapStyleHost +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.raster.RasterTilePreferenceKey +import com.mapconductor.core.raster.TileScheme +import com.mapconductor.vectorstyle.StyleAffects +import com.mapconductor.vectorstyle.VectorStyleRasterisation +import com.mapconductor.vectorstyle.VectorStyleRasteriser +import java.io.File +import java.util.UUID +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.math.roundToInt +import android.content.res.Resources +import android.os.Handler +import android.os.Looper + +/** + * Draws a vector style for a map that cannot read one. + * + * ```kotlin + * GoogleMapView( + * state = state, + * style = VectorStyle( + * document = VectorStyleSource.Url("https://…/style.json"), + * rules = rules, + * rasteriser = VectorTileRasteriser(), + * ), + * ) + * ``` + * + * Google Maps, MapKit, HERE, ArcGIS, Longdo, TomTom and the rest have no + * vector renderer to hand a style to. This renders the style to PNG tiles on + * the device and mounts them as an ordinary raster layer, so the same rules + * produce the same map on a backend that has never heard of MapLibre. + * + * A separate class from [VectorTileLayer] rather than the same code, because + * the two are mounted from different places and only one of them is a + * composable: the layer is content the app declares, this is a property of + * the view installed from outside it. What they share — the provider, the + * two-route split, the tile server — is [VectorTileProvider]. + * + * ## Why two layers + * + * The ground (geometry, drawn by the GPU) and the labels (glyphs, drawn on + * the CPU) are separate raster layers stacked on each other, for the reason + * [VectorTileLayer] gives: they render in parallel, and glyphs arriving late + * refresh only the transparent overlay rather than redrawing the map. + */ +class VectorTileRasteriser( + /** + * Tile size in pixels, or null to take the map's own preference. + * + * Null is almost always right: a provider that wants 256 says so through + * [RasterTilePreferenceKey], and ArcGIS's 3D view is the one that does. + */ + private val tileSize: Int? = null, + private val headers: Map = emptyMap(), + private val diskCacheDir: File? = null, + private val renderMode: VectorTileProvider.RenderMode = VectorTileProvider.RenderMode.AUTO, + private val renderScale: Int? = null, +) : VectorStyleRasteriser { + override fun install( + host: MapStyleHost, + styleJson: String, + affects: StyleAffects, + ): VectorStyleRasterisation = Rasterisation(host, this).also { it.start(styleJson) } + + private class Rasterisation( + private val host: MapStyleHost, + private val options: VectorTileRasteriser, + ) : VectorStyleRasterisation { + private val groupId = "vectorstyle-raster-${UUID.randomUUID()}" + private val disposed = AtomicBoolean(false) + private val main = Handler(Looper.getMainLooper()) + + /** + * Bumped whenever the pixels change for the same geometry. + * + * A map only refetches a raster source whose URL changed, so a + * restyle has to reach the template. The ground and the labels are + * counted apart: recolouring roads need not redraw the labels, and + * `affects` is what says which moved. + */ + private var groundGeneration = 0 + private var labelGeneration = 0 + + private var provider: VectorTileProvider? = null + private var credits: List = emptyList() + + /** Resolved once, when the first provider is built; the routes are keyed on it. */ + private var tileSize = VectorTileProvider.DEFAULT_TILE_SIZE + + /** + * The size the map is told. The dp size for a map that lays tiles + * out in dp, the pixel size for one that lays them out in physical + * pixels -- which is the provider's to say, through + * [RasterTilePreference.layoutInDevicePixels]. The tile URL always + * carries [tileSize]: that is what the provider renders at. + */ + private var declaredTileSize = VectorTileProvider.DEFAULT_TILE_SIZE + + fun start(styleJson: String) { + workers.execute { + val preference = host.serviceRegistry.get(RasterTilePreferenceKey) + tileSize = + options.tileSize + ?: preference?.preferredTileSize + ?: VectorTileProvider.DEFAULT_TILE_SIZE + declaredTileSize = + if (preference?.layoutInDevicePixels == true) { + (tileSize * Resources.getSystem().displayMetrics.density).roundToInt() + } else { + tileSize + } + val created = runCatching { build(styleJson) } + if (disposed.get()) { + created.getOrNull()?.closeAsync() + return@execute + } + created + .onSuccess { ready(it) } + .onFailure { + host.report(listOf("the style could not be rasterised: ${it.message}")) + } + } + } + + private fun build(styleJson: String): VectorTileProvider = + VectorTileProvider.create( + styleJson = styleJson, + tileSize = tileSize, + headers = options.headers, + diskCacheDir = options.diskCacheDir, + renderMode = options.renderMode, + renderScale = options.renderScale, + ) + + private fun ready(created: VectorTileProvider) { + // Glyphs arrive after the tiles that need them -- a range is a + // round trip and a low zoom wants dozens -- so tiles are drawn + // with what is loaded and the labels refetched once more is. + created.onGlyphsLoaded = { + if (!disposed.get()) { + labelGeneration++ + main.post { if (!disposed.get()) mountLabels() } + } + } + host.tileServer.register("$groupId-geom", created.geometryTiles) + host.tileServer.register("$groupId-labels", created.labelTiles) + provider = created + credits = created.attributions().map { AttributionRule(attribution = it) } + host.report(created.diagnostics()) + main.post { + if (disposed.get()) return@post + mountGround() + mountLabels() + } + } + + override fun restyle( + styleJson: String, + affects: StyleAffects, + ) { + if (affects == StyleAffects.NONE) return + workers.execute { + if (disposed.get()) return@execute + // A new provider rather than a style swap: the renderer + // holds the parsed document, and nothing in it is meant to + // be mutated under the tiles it is already drawing. The + // *source* tiles are what cost a network, and those live in + // a cache the new provider shares -- so this is a + // re-rasterise and no refetch, which is the promise. + val rebuilt = + runCatching { build(styleJson) }.getOrElse { error -> + host.report(listOf("the style could not be redrawn: ${error.message}")) + return@execute + } + if (disposed.get()) { + rebuilt.closeAsync() + return@execute + } + val previous = provider + rebuilt.onGlyphsLoaded = { + if (!disposed.get()) { + labelGeneration++ + main.post { if (!disposed.get()) mountLabels() } + } + } + // Re-registering a route replaces it, so the map never asks + // for an id that is not served. + host.tileServer.register("$groupId-geom", rebuilt.geometryTiles) + host.tileServer.register("$groupId-labels", rebuilt.labelTiles) + provider = rebuilt + credits = rebuilt.attributions().map { AttributionRule(attribution = it) } + previous?.closeAsync() + // Only the half that moved. A recolour of the roads leaves + // every label tile valid, and redrawing them would cost the + // whole screen for nothing. + if (affects == StyleAffects.GROUND || affects == StyleAffects.BOTH) groundGeneration++ + if (affects == StyleAffects.LABELS || affects == StyleAffects.BOTH) labelGeneration++ + main.post { + if (disposed.get()) return@post + if (affects == StyleAffects.GROUND || affects == StyleAffects.BOTH) mountGround() + if (affects == StyleAffects.LABELS || affects == StyleAffects.BOTH) mountLabels() + } + } + } + + override fun dispose() { + if (!disposed.compareAndSet(false, true)) return + main.post { + host.removeRaster("$groupId-geom") + host.removeRaster("$groupId-labels") + } + host.tileServer.unregister("$groupId-geom") + host.tileServer.unregister("$groupId-labels") + provider?.closeAsync() + provider = null + } + + /** Geometry only, drawn by the GPU, never invalidated by glyphs. */ + private fun mountGround() { + host.upsertRaster( + RasterLayerState( + id = "$groupId-geom", + source = + RasterLayerSource.UrlTemplate( + template = host.tileServer.urlTemplate("$groupId-geom", tileSize, "g$groundGeneration"), + tileSize = declaredTileSize, + maxZoom = MAX_ZOOM, + attributionRules = credits, + scheme = TileScheme.XYZ, + ), + visible = true, + // Under everything the app declared, and under the + // labels. A style *is* the basemap here. + zIndex = -2, + ), + ) + } + + /** The transparent overlay the glyphs land on. */ + private fun mountLabels() { + host.upsertRaster( + RasterLayerState( + id = "$groupId-labels", + source = + RasterLayerSource.UrlTemplate( + template = host.tileServer.urlTemplate("$groupId-labels", tileSize, "g$labelGeneration"), + tileSize = declaredTileSize, + maxZoom = MAX_ZOOM, + // Both halves carry the credit, so hiding either + // one cannot silence it. `resolveMapAttributions` + // ends in `distinct()`. + attributionRules = credits, + scheme = TileScheme.XYZ, + ), + visible = true, + zIndex = -1, + ), + ) + } + + private companion object { + const val MAX_ZOOM = 22 + + /** + * Where a style is parsed and redrawn. Daemon threads and few: a + * map has one style, and the work is a parse plus a re-rasterise. + */ + val workers = + Executors.newFixedThreadPool(2) { runnable -> + Thread(runnable, "mapconductor-vectorstyle-raster").apply { isDaemon = true } + } + } + } +} diff --git a/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileRenderer.kt b/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileRenderer.kt new file mode 100644 index 000000000..fc66eca17 --- /dev/null +++ b/android-vectortile/src/main/java/com/mapconductor/vectortile/VectorTileRenderer.kt @@ -0,0 +1,319 @@ +package com.mapconductor.vectortile + +import org.json.JSONArray +import java.io.Closeable +import java.nio.ByteBuffer +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.locks.ReentrantReadWriteLock +import kotlin.concurrent.read +import kotlin.concurrent.write + +/** + * Renders MapLibre vector styles to raster PNG tiles. + * + * Rendering is split in two so that **no network I/O happens inside the native + * library**: [plan] says which source tiles are needed, the caller fetches them + * with its own HTTP stack — keeping auth header injection, certificate pinning + * and OkHttp's cache — and passes the bytes to [render]. + * + * Instances hold a native allocation; call [close] when done. + */ +class VectorTileRenderer private constructor( + handle: Long, +) : Closeable { + private val handle = AtomicLong(handle) + + /** + * Keeps [close] from freeing the renderer while a native call is inside it. + * + * Tiles are drawn on the tile server's worker threads while the thread + * that owns the layer decides to drop it -- a provider switch, a page + * leaving, a style change. Freeing the handle then leaves those workers + * holding a pointer into freed memory, and whatever is allocated next + * writes over it: the process died inside `nativeRender` with a fault + * address made of style-layer name bytes, which is what the freed block + * held by the time it was read. + * + * Calls take the read side, so tiles still render in parallel. Only + * [close] takes the write side, and that is what makes it wait for the + * calls already inside the library -- bounded by one tile, since nothing + * here loops. A call that arrives after the free finds the handle cleared + * and throws instead of reading freed memory. + */ + private val liveCalls = ReentrantReadWriteLock() + + companion object { + const val DEFAULT_TILE_SIZE: Int = 512 + + /** + * Bumped whenever the renderer's output changes for the same style. + * + * Callers key their tile caches on this. Without it, a build that + * started drawing labels kept serving the unlabelled PNGs the previous + * one had cached — the tiles were correct for the renderer that made + * them and wrong for the one asking. + * + * 1: fills, lines, circles. + * 2: labels. + * 14: drawn for the screen size the host shows a tile at, and read + * from the source level that size belongs to. + * 15: the whole background stack, not its last layer. + * 16: magnified geometry lands inside its tile on the GPU path. + * 17: labels judged against a tile of margin, so neighbours agree. + * 18: glyph pixels align across tile boundaries. + * 19: label bounds include glyph bearings and SDF raster extents. + * 20: that extent decides which tile a label draws in; collisions are + * judged on the layout box again, so labels are as dense as before. + */ + const val OUTPUT_VERSION: Int = 23 + + /** @throws IllegalArgumentException if the style cannot be parsed. */ + @JvmStatic + fun create( + styleJson: String, + displayTileSize: Int, + ): VectorTileRenderer = VectorTileRenderer(NativeRenderer.nativeNew(styleJson, displayTileSize)) + } + + /** + * Runs one native call with the renderer held alive for its duration. + * + * The handle is read inside the lock. Reading it outside would race + * [close] again, which is the bug this exists to stop. + */ + private inline fun withRenderer(block: (Long) -> T): T = + liveCalls.read { + val value = handle.get() + check(value != 0L) { "VectorTileRenderer has been closed" } + block(value) + } + + /** + * Source tiles needed to draw `z/x/y`, as JSON. Fetch them in order and + * pass the bytes to [render] positionally. + */ + fun plan( + z: Int, + x: Int, + y: Int, + ): String = withRenderer { handle -> NativeRenderer.nativePlan(handle, z, x, y) } + + /** The style's `glyphs` URL template, or null when it has none. */ + fun glyphsUrlTemplate(): String? = + withRenderer { handle -> NativeRenderer.nativeGlyphsUrlTemplate(handle) }.takeIf { it.isNotEmpty() } + + /** + * Glyph URLs this tile's labels need and the renderer does not hold. + * + * Asked after the source tiles are in, because which ranges a tile needs + * depends on the text in it — a CJK font has 82 ranges where a tile of + * Tokyo uses four. + */ + fun neededGlyphs( + z: Int, + x: Int, + y: Int, + tiles: List, + ): List { + val (data, lengths) = pack(tiles) + val urls = + JSONArray( + withRenderer { handle -> + NativeRenderer.nativeNeededGlyphs(handle, z, x, y, data, lengths) + }, + ) + return (0 until urls.length()).map { urls.getString(it) } + } + + /** + * Hands one fetched range to the renderer, which keeps it for every later + * tile. Returns how many glyphs it gained. + */ + fun addGlyphs(pbf: ByteArray): Int = withRenderer { handle -> NativeRenderer.nativeAddGlyphs(handle, pbf) } + + /** + * The style's sprite pair — index then image — or an empty list when the + * style names no sprite. + * + * Unlike glyphs these are known from the style alone, so they can be + * fetched before a single tile has been drawn. + */ + fun spriteUrls(pixelRatio: Int = 1): List { + val urls = JSONArray(withRenderer { handle -> NativeRenderer.nativeSpriteUrls(handle, pixelRatio) }) + return (0 until urls.length()).map { urls.getString(it) } + } + + /** + * Whether a tile at this zoom has to be rasterised on the CPU. + * + * Complex visible polygons use the CPU to avoid expensive triangulation. + * The GPU path draws flat-coloured triangles; a patterned fill needs an + * image repeated across the polygon. Asked of the tile rather than of the + * style, because a style that paints prisons with a hatch says nothing + * about whether this tile has a prison in it. + */ + fun needsCpu( + z: Int, + tiles: List, + ): Boolean { + val (data, lengths) = pack(tiles) + return withRenderer { handle -> NativeRenderer.nativeNeedsCpu(handle, z, data, lengths) } != 0 + } + + /** Whether the style names a sprite the renderer has not been given. */ + fun needsSprite(): Boolean = withRenderer { handle -> NativeRenderer.nativeNeedsSprite(handle) } != 0 + + /** + * Hands over the fetched pair, and returns how many icons the sheet holds. + * + * One sheet covers a whole style, so this replaces rather than + * accumulates — a restyle brings its own. + * + * @throws IllegalArgumentException if the pair will not parse + */ + fun addSprite( + indexJson: String, + png: ByteArray, + ): Int = withRenderer { handle -> NativeRenderer.nativeAddSprite(handle, indexJson, png) } + + /** + * Draws this tile's labels onto pixels something else rasterised. + * + * The GPU path tessellates fills and lines and knows nothing about glyphs. + * The label pass does not care how the pixels underneath were made, so it + * runs over the readback rather than forcing the whole tile onto the CPU. + * + * @param rgba `tileSize * tileSize * 4` bytes, modified in place + * @return how many labels were placed + */ + fun drawLabels( + z: Int, + x: Int, + y: Int, + tileSize: Int, + rgba: ByteArray, + tiles: List, + ): Int { + val (data, lengths) = pack(tiles) + return withRenderer { handle -> + NativeRenderer.nativeDrawLabels(handle, z, x, y, tileSize, rgba, data, lengths) + } + } + + /** Draws a standalone transparent label tile without an RGBA JNI copy. */ + internal fun renderLabels( + z: Int, + x: Int, + y: Int, + tileSize: Int, + tiles: List, + ): NativeLabelPixels? { + val (data, lengths) = pack(tiles) + val placed = IntArray(1) + val pixels = + withRenderer { handle -> + NativeRenderer.nativeRenderLabels( + handle, z, x, y, tileSize, data, lengths, placed, + ) + } ?: return null + return NativeLabelPixels(pixels, placed[0]) + } + + /** + * Rasterises `z/x/y` to PNG bytes. + * + * @param tiles one entry per [plan] request, in the same order; null where + * the fetch 404'd or came back empty. + */ + fun render( + z: Int, + x: Int, + y: Int, + tileSize: Int = DEFAULT_TILE_SIZE, + tiles: List, + geometryOnly: Boolean = false, + ): ByteArray { + val (data, lengths) = pack(tiles) + return withRenderer { handle -> + NativeRenderer.nativeRender( + handle, + z, + x, + y, + tileSize, + data, + lengths, + if (geometryOnly) 1 else 0, + ) + } + } + + /** + * One concatenated buffer plus a length table, which is what the native + * side takes: an array-of-arrays would be marshalled element by element + * across JNI. + */ + private fun pack(tiles: List): Pair { + val lengths = IntArray(tiles.size) { tiles[it]?.size ?: 0 } + val data = ByteArray(lengths.sum()) + var offset = 0 + for (tile in tiles) { + if (tile == null) continue + tile.copyInto(data, offset) + offset += tile.size + } + return data to lengths + } + + /** + * Replaces the style. Fetched vector tiles stay valid — the geometry is + * unchanged, only the paint applied to it — so recolouring needs no refetch. + */ + fun setStyle(styleJson: String) { + withRenderer { handle -> NativeRenderer.nativeSetStyle(handle, styleJson) } + } + + /** + * Triangulates `z/x/y` for the GPU renderer. See `TessellatedTile` for the + * packed layout. + */ + internal fun tessellate( + z: Int, + x: Int, + y: Int, + tileSize: Int, + data: ByteArray, + lengths: IntArray, + ): ByteBuffer = withRenderer { handle -> NativeRenderer.nativeTessellate(handle, z, x, y, tileSize, data, lengths) } + + /** JSON array of layer `type` values in this style that will not be drawn. */ + fun unsupportedLayerTypes(): String = withRenderer { handle -> NativeRenderer.nativeUnsupportedLayerTypes(handle) } + + /** + * JSON array of the credits this style's sources ask to be shown. + * + * The host must display these: a style is data under someone's licence, + * and the sample basemap draws OpenStreetMap, whose licence requires the + * credit. May contain HTML — the text is normally a link to the licence. + */ + fun attributions(): String = withRenderer { handle -> NativeRenderer.nativeAttributions(handle) } + + /** + * Reasons the current style may not render as intended, as a JSON array of + * strings: unsupported layer types, sources that cannot be fetched, layers + * pointing at undefined sources, Mapbox `imports`. + * + * Worth surfacing — the failure mode that matters is a blank tile, and a + * style this renderer cannot use should say so. + */ + fun diagnostics(): String = withRenderer { handle -> NativeRenderer.nativeDiagnostics(handle) } + + /** Releases the native renderer. Safe to call more than once. */ + override fun close() { + liveCalls.write { + // getAndSet keeps a double close from freeing the same pointer twice. + val value = handle.getAndSet(0L) + if (value != 0L) NativeRenderer.nativeFree(value) + } + } +} diff --git a/android-vectortile/src/main/jniLibs/arm64-v8a/libmvt_render_jni.so b/android-vectortile/src/main/jniLibs/arm64-v8a/libmvt_render_jni.so new file mode 100755 index 000000000..fff25203d Binary files /dev/null and b/android-vectortile/src/main/jniLibs/arm64-v8a/libmvt_render_jni.so differ diff --git a/build.gradle.kts b/build.gradle.kts index 8fb4a4a70..fe3319dad 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -92,7 +92,10 @@ val publishableModules = listOf( "android-for-here", "android-for-mapbox", "android-for-maplibre", - "android-for-tomtom" + "android-for-tomtom", + // ベクタースタイル。RN のラッパー基底が MavenLocal から読む(任意依存)ので、 + // ここに載っていないと RN からは使えない。 + "android-vectorstyle" ) tasks.register("publishAllLocal") { diff --git a/docs/src/components/components/circle/CircleBasicSignature.astro b/docs/src/components/components/circle/CircleBasicSignature.astro index 79026ec46..8c27a9589 100644 --- a/docs/src/components/components/circle/CircleBasicSignature.astro +++ b/docs/src/components/components/circle/CircleBasicSignature.astro @@ -7,7 +7,7 @@ fun MapViewScope.Circle( radiusMeters: Double, geodesic: Boolean = false, strokeColor: Color = Color.Red, - strokeWidth: Dp = 2.dp, + strokeWidth: Dp = 1.dp, fillColor: Color = Color.White.copy(alpha = 0.5f), extra: Serializable? = null, id: String? = null diff --git a/docs/src/components/components/circle/CircleStateSignature.astro b/docs/src/components/components/circle/CircleStateSignature.astro index 629615be5..59c582b03 100644 --- a/docs/src/components/components/circle/CircleStateSignature.astro +++ b/docs/src/components/components/circle/CircleStateSignature.astro @@ -6,7 +6,7 @@ const code = `CircleState( radiusMeters: Double, geodesic: Boolean = false, strokeColor: Color = Color.Red, - strokeWidth: Dp = 2.dp, + strokeWidth: Dp = 1.dp, fillColor: Color = Color.White.copy(alpha = 0.5f), extra: Serializable? = null, id: String? = null diff --git a/docs/src/components/components/groundimage/GroundImageBasicSignature.astro b/docs/src/components/components/groundimage/GroundImageBasicSignature.astro index 0747f2016..1c0738923 100644 --- a/docs/src/components/components/groundimage/GroundImageBasicSignature.astro +++ b/docs/src/components/components/groundimage/GroundImageBasicSignature.astro @@ -5,7 +5,7 @@ const code = `@Composable fun MapViewScope.GroundImage( bounds: GeoRectBounds, image: Drawable, - opacity: Float = 0.5f, + opacity: Float = 1.0f, id: String? = null, extra: Serializable? = null )`; diff --git a/docs/src/components/core/spherical-utilities/ComputeAreaExample.astro b/docs/src/components/core/spherical-utilities/ComputeAreaExample.astro index 52f716784..22a13ccca 100644 --- a/docs/src/components/core/spherical-utilities/ComputeAreaExample.astro +++ b/docs/src/components/core/spherical-utilities/ComputeAreaExample.astro @@ -16,7 +16,7 @@ println("Polygon area: ${'$'}{areaKm2.toInt()} km²") // Signed area tells you orientation val signedArea = Spherical.computeSignedArea(polygonPoints) -val orientation = if (signedArea > 0) "Counter-clockwise" else "Clockwise" +val orientation = if (signedArea > 0) "Clockwise" else "Counter-clockwise" println("Polygon orientation: ${'$'}orientation")`; --- diff --git a/docs/src/components/states/polygon/PolygonStateConstructorExample.astro b/docs/src/components/states/polygon/PolygonStateConstructorExample.astro index c77f8ef3f..a7527e001 100644 --- a/docs/src/components/states/polygon/PolygonStateConstructorExample.astro +++ b/docs/src/components/states/polygon/PolygonStateConstructorExample.astro @@ -5,7 +5,7 @@ const code = `PolygonState( points: List, id: String? = null, strokeColor: Color = Color.Black, - strokeWidth: Dp = 2.dp, + strokeWidth: Dp = 1.dp, fillColor: Color = Color.Transparent, geodesic: Boolean = false, extra: Serializable? = null diff --git a/docs/src/content/docs/components/circle.mdx b/docs/src/content/docs/components/circle.mdx index 16298d6a3..0430c9836 100644 --- a/docs/src/content/docs/components/circle.mdx +++ b/docs/src/content/docs/components/circle.mdx @@ -48,7 +48,7 @@ For a large number of circles or when moving circles, using state is recommended - **`radiusMeters`**: Radius in meters (`Double`) - **`geodesic`**: Whether to draw the circle using geodesic edges that follow the Earth’s curvature (default: `false`) - **`strokeColor`**: Color of the circle's border (default: `Color.Red`) -- **`strokeWidth`**: Width of the border line (default: `2.dp`) +- **`strokeWidth`**: Width of the border line (default: `1.dp`) - **`fillColor`**: Fill color of the circle interior (default: semi-transparent white) - **`extra`**: Additional data attached to the circle (`Serializable?`) - **`id`**: Unique identifier for the circle (`String?`) diff --git a/docs/src/content/docs/components/groundimage.mdx b/docs/src/content/docs/components/groundimage.mdx index 0ea499c10..24729eeaf 100644 --- a/docs/src/content/docs/components/groundimage.mdx +++ b/docs/src/content/docs/components/groundimage.mdx @@ -34,7 +34,7 @@ Ground images are image overlays that are positioned geographically on the map. - **`bounds`**: Geographic rectangular bounds where the image is positioned (`GeoRectBounds`) - **`image`**: Drawable image to display (`Drawable`) -- **`opacity`**: Opacity level from 0.0 (transparent) to 1.0 (opaque) (default: `0.5f`) +- **`opacity`**: Opacity level from 0.0 (transparent) to 1.0 (opaque) (default: `1.0f`) - **`id`**: Optional unique identifier for the GroundImage (`String?`) - **`extra`**: Additional data attached to the GroundImage (`Serializable?`) diff --git a/docs/src/content/docs/es-419/components/circle.mdx b/docs/src/content/docs/es-419/components/circle.mdx index 35f209a08..07b9fd742 100644 --- a/docs/src/content/docs/es-419/components/circle.mdx +++ b/docs/src/content/docs/es-419/components/circle.mdx @@ -50,7 +50,7 @@ Especificar `id` puede reducir Recomposiciones innecesarias. - **`radiusMeters`**: Radio en metros (`Double`) - **`geodesic`**: Si se debe dibujar el círculo usando bordes geodésicos que sigan la curvatura de la Tierra (predeterminado: `false`) - **`strokeColor`**: Color del borde del círculo (predeterminado: `Color.Red`) -- **`strokeWidth`**: Ancho de la línea del borde (predeterminado: `2.dp`) +- **`strokeWidth`**: Ancho de la línea del borde (predeterminado: `1.dp`) - **`fillColor`**: Color de relleno del interior del círculo (predeterminado: blanco semi-transparente) - **`extra`**: Datos adicionales adjuntos al círculo (`Serializable?`) - **`id`**: Identificador único para el círculo (`String?`) diff --git a/docs/src/content/docs/es-419/components/groundimage.mdx b/docs/src/content/docs/es-419/components/groundimage.mdx index fdffa586b..8838eed4f 100644 --- a/docs/src/content/docs/es-419/components/groundimage.mdx +++ b/docs/src/content/docs/es-419/components/groundimage.mdx @@ -34,7 +34,7 @@ Una GroundImage es una superposición de imagen posicionada geográficamente en - **`bounds`**: Límites rectangulares geográficos donde se posiciona la imagen (`GeoRectBounds`) - **`image`**: Imagen dibujable para mostrar (`Drawable`) -- **`opacity`**: Nivel de opacidad de 0.0 (transparente) a 1.0 (opaco) (predeterminado: `0.5f`) +- **`opacity`**: Nivel de opacidad de 0.0 (transparente) a 1.0 (opaco) (predeterminado: `1.0f`) - **`id`**: Identificador único opcional para la GroundImage (`String?`) - **`extra`**: Datos adicionales adjuntos a la GroundImage (`Serializable?`) diff --git a/docs/src/content/docs/ja/components/circle.mdx b/docs/src/content/docs/ja/components/circle.mdx index 00ba4636f..ef4a28d4b 100644 --- a/docs/src/content/docs/ja/components/circle.mdx +++ b/docs/src/content/docs/ja/components/circle.mdx @@ -49,7 +49,7 @@ import CircleIdDetailedExample from '~/components/components/circle/CircleIdDeta - **`radiusMeters`**: 半径(メートル単位、`Double`) - **`geodesic`**: 測地線(地球の曲率に沿う)を描画するかどうか(デフォルト: `false`) - **`strokeColor`**: 円の境界線の色(デフォルト: `Color.Red`) -- **`strokeWidth`**: 境界線の幅(デフォルト: `2.dp`) +- **`strokeWidth`**: 境界線の幅(デフォルト: `1.dp`) - **`fillColor`**: 円の内部の塗りつぶし色(デフォルト: 半透明の白) - **`extra`**: 円に付加する追加データ(`Serializable?`) - **`id`**: 円の一意識別子(`String?`) diff --git a/docs/src/content/docs/ja/components/groundimage.mdx b/docs/src/content/docs/ja/components/groundimage.mdx index 0064a43ef..5033dd801 100644 --- a/docs/src/content/docs/ja/components/groundimage.mdx +++ b/docs/src/content/docs/ja/components/groundimage.mdx @@ -35,7 +35,7 @@ GroundImage は、地図上に地理的に配置される画像オーバーレ - **`bounds`**: 画像を配置する地理的な矩形境界(`GeoRectBounds`) - **`image`**: 表示する drawable 画像(`Drawable`) -- **`opacity`**: 透明度レベル、0.0(透明)から 1.0(不透明)まで(デフォルト: `0.5f`) +- **`opacity`**: 透明度レベル、0.0(透明)から 1.0(不透明)まで(デフォルト: `1.0f`) - **`id`**: GroundImage のオプションの一意識別子(`String?`) - **`extra`**: GroundImage に付加する追加データ(`Serializable?`) diff --git a/example-app/build.gradle.kts b/example-app/build.gradle.kts index a23d2ab49..29889b550 100644 --- a/example-app/build.gradle.kts +++ b/example-app/build.gradle.kts @@ -40,6 +40,23 @@ configurations.configureEach { } } +// TomTom Orbis Maps SDK 2.4.x は OkHttp 4.x でビルドされていて、**OkHttp 5.x では +// 衛星(ラスタ)スタイルからベクタスタイルへ戻したときに地図が地色一色になる**。 +// `loadStyle` は `onSuccess()` を返しレイヤーも 137 枚読めるのに、タイルが一切描かれない。 +// 例外も HTTP エラーも出ない無音の失敗なので、症状からは絶対に辿り着けない。 +// +// ArcGIS Maps SDK for Kotlin 300.1.0 が okhttp 5.3.2 を引き込み、Gradle の +// 「高いほうが勝つ」解決で TomTom の 4.12.0 が 5.3.2 へ引き上げられていた。 +// Pixel 5a / map-display 2.4.2 で両方向を確認済み: +// - ArcGIS 無し + okhttp 5.3.2 を強制 → 再現する +// - ArcGIS 有り + okhttp 4.12.0 に固定 → 直る +// ベクタ→ベクタ(Standard ⇄ Driving)は 5.x でも壊れない。ラスタ→ベクタだけ。 +configurations.configureEach { + resolutionStrategy { + force("com.squareup.okhttp3:okhttp:4.12.0") + } +} + // secrets.properties(無ければ local.defaults.properties)を manifest placeholder として読む。 // 値は使うだけで、ログにも BuildConfig にも出さない。 val secretPlaceholders: Map = @@ -140,6 +157,9 @@ android { // どちらも libc++_shared.so を同梱していて衝突する。どちらも同じ // NDK の STL なので 1 つに畳んでよい。 pickFirsts += "lib/**/libc++_shared.so" + // The app's patched OMM quad/stencil implementation takes priority + // over the published 4.0.0 native library (upstream PR #928). + pickFirsts += "lib/arm64-v8a/libmapscore.so" } } @@ -249,6 +269,8 @@ dependencies { implementation(project(":android-for-mappls")) debugImplementation(project(":android-marker-clustering")) debugImplementation(project(":android-heatmap")) + debugImplementation(project(":android-vectortile")) + debugImplementation(project(":android-vectorstyle")) debugImplementation(project(":android-geojson-layer")) debugImplementation(project(":android-kml")) diff --git a/example-app/omm-native/LICENSE b/example-app/omm-native/LICENSE new file mode 100644 index 000000000..a612ad981 --- /dev/null +++ b/example-app/omm-native/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/example-app/omm-native/README.md b/example-app/omm-native/README.md new file mode 100644 index 000000000..8d1b966c7 --- /dev/null +++ b/example-app/omm-native/README.md @@ -0,0 +1,18 @@ +# OMM flat raster seam fix + +The examples app bundles an arm64 `libmapscore.so` ahead of the OMM 4.0.0 AAR's +native library. The binary is built from openmobilemaps/maps-core commit +`82c1fac` plus `flat-raster-seams.patch`; the source changes are also available +in this workspace's `ios-sdk/maps-core` checkout. OMM is licensed under MPL-2.0 +(see LICENSE). No MapConductor classes are added to OMM. + +For flat, stencil-masked raster tiles, expand the quad and its UV coordinates +by the same fraction. Keeping the mapping unchanged inside the tile avoids +compressing boundary labels, while the expanded geometry covers subpixel gaps. +Textures use GL_CLAMP_TO_EDGE. Unmasked and 3D paths keep their previous behavior. +This refines the earlier zero-overlap proposal in upstream PR #928. + +Rebuild from the Android SDK checkout with `example-app/omm-native/rebuild.sh`. +Set ANDROID_HOME if needed. The script uses NDK 27.1.12297006, CMake 3.22.1, +and arm64 only. Build products and the source checkout go into example-app/build. +After rebuilding, run `./gradlew :example-app:assembleDebug`. diff --git a/example-app/omm-native/flat-raster-seams.patch b/example-app/omm-native/flat-raster-seams.patch new file mode 100644 index 000000000..491e17b63 --- /dev/null +++ b/example-app/omm-native/flat-raster-seams.patch @@ -0,0 +1,92 @@ +diff --git a/shared/public/Textured2dLayerObject.h b/shared/public/Textured2dLayerObject.h +index 9f53c05..da3f791 100644 +--- a/shared/public/Textured2dLayerObject.h ++++ b/shared/public/Textured2dLayerObject.h +@@ -71,6 +71,7 @@ class Textured2dLayerObject : public LayerObjectInterface, public std::enable_sh + + void setRectCoord(const ::RectCoord &rectCoord); + void setRectCoord(const ::RectCoord &rectCoord, double overlapFactor); ++ void setRectCoord(const ::RectCoord &rectCoord, double overlapFactor, bool preserveTextureScale); + void setPolygons(const std::vector<::PolygonCoord> &polygons, const ::RectCoord &textureBounds); + void setPolygons(const std::vector<::PolygonCoord> &polygons, const ::RectCoord &textureBounds, double overlapFactor); + +@@ -110,6 +111,7 @@ class Textured2dLayerObject : public LayerObjectInterface, public std::enable_sh + + protected: + void setFrame(const ::Quad3dD &frame, const ::Vec3D & origin); ++ void setPositions(const ::QuadCoord &coords, const RectD &textureCoordinates); + + private: + std::shared_ptr quad; +diff --git a/shared/src/map/layers/objects/Textured2dLayerObject.cpp b/shared/src/map/layers/objects/Textured2dLayerObject.cpp +index 76b17c6..daf1e59 100644 +--- a/shared/src/map/layers/objects/Textured2dLayerObject.cpp ++++ b/shared/src/map/layers/objects/Textured2dLayerObject.cpp +@@ -89,6 +89,26 @@ void Textured2dLayerObject::setRectCoord(const ::RectCoord &rectCoord) { + } + + void Textured2dLayerObject::setRectCoord(const ::RectCoord &rectCoord, double overlapFactor) { ++ setRectCoord(rectCoord, overlapFactor, false); ++} ++ ++void Textured2dLayerObject::setRectCoord(const ::RectCoord &rectCoord, double overlapFactor, bool preserveTextureScale) { ++ if (preserveTextureScale) { ++ const double width = rectCoord.bottomRight.x - rectCoord.topLeft.x; ++ const double height = rectCoord.bottomRight.y - rectCoord.topLeft.y; ++ const double x = rectCoord.topLeft.x - width * overlapFactor; ++ const double y = rectCoord.topLeft.y - height * overlapFactor; ++ const double w = width * (1.0 + 2.0 * overlapFactor); ++ const double h = height * (1.0 + 2.0 * overlapFactor); ++ const auto system = rectCoord.topLeft.systemIdentifier; ++ const auto z = rectCoord.topLeft.z; ++ // Expand UVs with the geometry: the image inside the original bounds ++ // keeps its mapping, while CLAMP_TO_EDGE covers subpixel raster gaps. ++ setPositions(QuadCoord(Coord(system, x, y, z), Coord(system, x + w, y, z), ++ Coord(system, x + w, y + h, z), Coord(system, x, y + h, z)), ++ RectD(-overlapFactor, -overlapFactor, 1.0 + 2.0 * overlapFactor, 1.0 + 2.0 * overlapFactor)); ++ return; ++ } + auto width = rectCoord.bottomRight.x - rectCoord.topLeft.x; + auto height = rectCoord.bottomRight.y - rectCoord.topLeft.y; + const double xOverlap = width * overlapFactor; +@@ -106,6 +126,10 @@ void Textured2dLayerObject::setPosition(const ::Coord &coord, double width, doub + } + + void Textured2dLayerObject::setPositions(const ::QuadCoord &coords) { ++ setPositions(coords, RectD(0, 0, 1, 1)); ++} ++ ++void Textured2dLayerObject::setPositions(const ::QuadCoord &coords, const RectD &textureCoordinates) { + QuadCoord renderCoords = conversionHelper->convertQuadToRenderSystem(coords); + + const double cx = (renderCoords.bottomRight.x + renderCoords.topLeft.x) / 2.0; +@@ -127,10 +151,9 @@ void Textured2dLayerObject::setPositions(const ::QuadCoord &coords) { + return Vec3D(x, y, z); + }; + +- setFrame(Quad3dD(transform(renderCoords.topLeft), +- transform(renderCoords.topRight), +- transform(renderCoords.bottomRight), +- transform(renderCoords.bottomLeft)), origin); ++ quad->setFrame(Quad3dD(transform(renderCoords.topLeft), transform(renderCoords.topRight), ++ transform(renderCoords.bottomRight), transform(renderCoords.bottomLeft)), ++ textureCoordinates, origin, is3d); + } + + void Textured2dLayerObject::setFrame(const ::Quad3dD &frame, const ::Vec3D & origin) { +diff --git a/shared/src/map/layers/tiled/raster/Tiled2dMapRasterLayer.cpp b/shared/src/map/layers/tiled/raster/Tiled2dMapRasterLayer.cpp +index 770d045..22b36c9 100644 +--- a/shared/src/map/layers/tiled/raster/Tiled2dMapRasterLayer.cpp ++++ b/shared/src/map/layers/tiled/raster/Tiled2dMapRasterLayer.cpp +@@ -369,7 +369,10 @@ void Tiled2dMapRasterLayer::onTilesUpdated(const std::string &layerName, VectorS + is3D ? RASTER_TILE_RENDER_OVERLAP_FACTOR : 0.0); + tileGeometryMaskHashes[tile.tileInfo] = hash; + } else { +- tileObject->setRectCoord(tile.tileInfo.tileInfo.bounds, RASTER_TILE_RENDER_OVERLAP_FACTOR); ++ // Preserve the texture mapping inside the tile while still ++ // covering subpixel gaps at adjacent stencil/quad edges. ++ tileObject->setRectCoord(tile.tileInfo.tileInfo.bounds, RASTER_TILE_RENDER_OVERLAP_FACTOR, ++ !is3D && usesStencilTileMasking()); + } + tilesToSetup.emplace_back(std::make_pair(tile, tileObject)); + diff --git a/example-app/omm-native/rebuild.sh b/example-app/omm-native/rebuild.sh new file mode 100755 index 000000000..7aaf3ce27 --- /dev/null +++ b/example-app/omm-native/rebuild.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail +root="$(cd "$(dirname "$0")/../.." && pwd)" +sdk="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}}" +checkout="$root/example-app/build/omm-source" +ndk="$sdk/ndk/${NDK_VERSION:-27.1.12297006}" +cmake="$sdk/cmake/${CMAKE_VERSION:-3.22.1}/bin" +if [[ ! -d "$checkout/.git" ]]; then + git clone https://github.com/openmobilemaps/maps-core.git "$checkout" + git -C "$checkout" checkout 82c1fac +fi +if [[ "$(git -C "$checkout" rev-parse --short=7 HEAD)" != 82c1fac ]]; then + echo "Expected OMM commit 82c1fac in $checkout" >&2; exit 1 +fi +git -C "$checkout" submodule update --init --recursive +patch="$root/example-app/omm-native/flat-raster-seams.patch" +if ! git -C "$checkout" apply --reverse --check "$patch" 2>/dev/null; then + git -C "$checkout" apply --check "$patch" + git -C "$checkout" apply "$patch" +fi +native_build="$root/example-app/build/omm-native" +"$cmake/cmake" -S "$checkout/android" -B "$native_build" -G Ninja \ + -DCMAKE_TOOLCHAIN_FILE="$ndk/build/cmake/android.toolchain.cmake" \ + -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-28 -DANDROID_STL=c++_shared \ + -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_MAKE_PROGRAM="$cmake/ninja" +"$cmake/cmake" --build "$native_build" --target mapscore -j 8 +dest="$root/example-app/src/main/jniLibs/arm64-v8a" +mkdir -p "$dest" +cp "$native_build/libmapscore.so" "$dest/libmapscore.so" +host="$(uname -s | tr '[:upper:]' '[:lower:]')-x86_64" +"$ndk/toolchains/llvm/prebuilt/$host/bin/llvm-strip" --strip-unneeded "$dest/libmapscore.so" diff --git a/example-app/release/output-metadata.json b/example-app/release/output-metadata.json index a2d551fba..95be051e4 100644 --- a/example-app/release/output-metadata.json +++ b/example-app/release/output-metadata.json @@ -1,37 +1,37 @@ { - "version": 3, - "artifactType": { - "type": "APK", - "kind": "Directory" - }, - "applicationId": "com.mapconductor.example", - "variantName": "release", - "elements": [ - { - "type": "SINGLE", - "filters": [], - "attributes": [], - "versionCode": 5, - "versionName": "1.0.4", - "outputFile": "example-app-release.apk" - } - ], - "elementType": "File", - "baselineProfiles": [ - { - "minApi": 28, - "maxApi": 30, - "baselineProfiles": [ - "baselineProfiles/1/example-app-release.dm" - ] + "version": 3, + "artifactType": { + "type": "APK", + "kind": "Directory" }, - { - "minApi": 31, - "maxApi": 2147483647, - "baselineProfiles": [ - "baselineProfiles/0/example-app-release.dm" - ] - } - ], - "minSdkVersionForDexing": 26 -} \ No newline at end of file + "applicationId": "com.mapconductor.example", + "variantName": "release", + "elements": [ + { + "type": "SINGLE", + "filters": [], + "attributes": [], + "versionCode": 5, + "versionName": "1.0.4", + "outputFile": "example-app-release.apk" + } + ], + "elementType": "File", + "baselineProfiles": [ + { + "minApi": 28, + "maxApi": 30, + "baselineProfiles": [ + "baselineProfiles/1/example-app-release.dm" + ] + }, + { + "minApi": 31, + "maxApi": 2147483647, + "baselineProfiles": [ + "baselineProfiles/0/example-app-release.dm" + ] + } + ], + "minSdkVersionForDexing": 26 +} diff --git a/example-app/src/androidTest/java/com/mapconductor/example/CircleFilteringStressTest.kt b/example-app/src/androidTest/java/com/mapconductor/example/CircleFilteringStressTest.kt new file mode 100644 index 000000000..41e337595 --- /dev/null +++ b/example-app/src/androidTest/java/com/mapconductor/example/CircleFilteringStressTest.kt @@ -0,0 +1,134 @@ +package com.mapconductor.example + +import androidx.compose.ui.platform.ViewRootForTest +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.semantics.SemanticsNode +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.semantics.getAllSemanticsNodes +import androidx.compose.ui.semantics.getOrNull +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry +import androidx.test.runner.lifecycle.Stage +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.maplibre.android.camera.CameraUpdateFactory +import org.maplibre.android.maps.MapLibreMap +import org.maplibre.android.maps.MapView +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import android.content.Intent +import android.os.SystemClock +import android.util.Log +import android.view.View +import android.view.ViewGroup + +/** Full nationwide data, native camera zooms, repeated carrier removal/restoration. */ +@RunWith(AndroidJUnit4::class) +class CircleFilteringStressTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + + private fun onMain(block: () -> T): T { + var result: T? = null + instrumentation.runOnMainSync { result = block() } + return result!! + } + + private fun activity(): MainActivity = + ActivityLifecycleMonitorRegistry + .getInstance() + .getActivitiesInStage(Stage.RESUMED) + .filterIsInstance() + .single() + + // Read Compose semantics directly. This leaves the app's real frame clock + // running and avoids depending on the device accessibility service cache. + private fun nodes(view: View): Sequence = + sequence { + if (view is ViewRootForTest) yieldAll(view.semanticsOwner.getAllSemanticsNodes(false)) + if (view is ViewGroup) for (index in 0 until view.childCount) yieldAll(nodes(view.getChildAt(index))) + } + + private fun toggleVerizon() = + onMain { + val checkboxes = + nodes(activity().window.decorView) + .filter { it.config.getOrNull(SemanticsProperties.ToggleableState) != null } + .sortedBy { it.boundsInRoot.top } + .toList() + assertTrue(checkboxes.size >= 4) + assertTrue(checkboxes[2].config[SemanticsActions.OnClick].action!!.invoke()) + } + + private fun waitForCount(count: Int) { + val deadline = SystemClock.uptimeMillis() + 60_000 + var lastTexts = emptyList() + while (SystemClock.uptimeMillis() < deadline) { + lastTexts = + onMain { + nodes(activity().window.decorView) + .mapNotNull { + it.config.getOrNull(SemanticsProperties.Text)?.joinToString("") { text -> text.text } + }.toList() + } + if (lastTexts.any { it == "$count / 723800 circles" }) return + SystemClock.sleep(250) + } + throw AssertionError("Circle count did not reach $count; semantics texts: $lastTexts") + } + + private fun mapView(view: View): MapView? { + if (view is MapView) return view + if (view is ViewGroup) for (i in 0 until view.childCount) mapView(view.getChildAt(i))?.let { return it } + return null + } + + @Test + fun zoomAndToggleVerizonFiveTimes() { + val intent = + Intent(ApplicationProvider.getApplicationContext(), MainActivity::class.java).apply { + putExtra("page", "antenna-horizons") + putExtra("provider", "maplibre") + } + ActivityScenario.launch(intent).use { + waitForCount(723800) + SystemClock.sleep(5_000) + lateinit var map: MapLibreMap + val ready = CountDownLatch(1) + onMain { + val view = mapView(activity().window.decorView)!! + view.getMapAsync { + map = it + ready.countDown() + } + } + assertTrue(ready.await(10, TimeUnit.SECONDS)) + + fun zoom(): Double { + var result = 0.0 + instrumentation.runOnMainSync { result = map.cameraPosition.zoom } + return result + } + repeat(5) { + Log.i("CircleFilterStress", "Starting cycle ${it + 1}") + val before = zoom() + onMain { map.animateCamera(CameraUpdateFactory.zoomTo(before + 2), 300) } + SystemClock.sleep(1_000) + assertTrue("Native map must actually zoom in", zoom() > before + 0.5) + onMain { map.animateCamera(CameraUpdateFactory.zoomTo(before), 300) } + SystemClock.sleep(1_000) + assertTrue("Native map must actually zoom out", zoom() < before + 0.5) + toggleVerizon() + waitForCount(576636) + SystemClock.sleep(3_000) + toggleVerizon() + waitForCount(723800) + SystemClock.sleep(3_000) + Log.i("CircleFilterStress", "Completed cycle ${it + 1}") + } + } + } +} diff --git a/example-app/src/main/AndroidManifest.xml b/example-app/src/main/AndroidManifest.xml index 278246bb8..d7318b601 100644 --- a/example-app/src/main/AndroidManifest.xml +++ b/example-app/src/main/AndroidManifest.xml @@ -53,6 +53,7 @@ + =", + "rank", + 3 + ], + [ + "!has", + "iso_a2" + ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "migu1c-regular" + ], + "text-max-width": 6.25, + "text-size": { + "stops": [ + [ + 3, + 11 + ], + [ + 7, + 17 + ] + ] + }, + "text-transform": "uppercase", + "visibility": "visible" + }, + "paint": { + "text-color": "#334", + "text-halo-blur": 1, + "text-halo-color": "rgba(255,255,255,0.8)", + "text-halo-width": 2 + } + }, + { + "id": "place-country-3", + "type": "symbol", + "metadata": { + "mapbox:group": "1444849242106.713" + }, + "source": "openmaptiles", + "source-layer": "place", + "filter": [ + "all", + [ + "==", + "class", + "country" + ], + [ + ">=", + "rank", + 3 + ], + [ + "has", + "iso_a2" + ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "migu2m-bold" + ], + "text-max-width": 6.25, + "text-size": { + "stops": [ + [ + 3, + 11 + ], + [ + 7, + 17 + ] + ] + }, + "text-transform": "uppercase", + "visibility": "visible" + }, + "paint": { + "text-color": "#334", + "text-halo-blur": 1, + "text-halo-color": "rgba(255,255,255,0.8)", + "text-halo-width": 2 + } + }, + { + "id": "place-country-2", + "type": "symbol", + "metadata": { + "mapbox:group": "1444849242106.713" + }, + "source": "openmaptiles", + "source-layer": "place", + "filter": [ + "all", + [ + "==", + "class", + "country" + ], + [ + "==", + "rank", + 2 + ], + [ + "has", + "iso_a2" + ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "migu2m-bold" + ], + "text-max-width": 6.25, + "text-size": { + "stops": [ + [ + 2, + 11 + ], + [ + 5, + 17 + ] + ] + }, + "text-transform": "uppercase", + "visibility": "visible" + }, + "paint": { + "text-color": "#334", + "text-halo-blur": 1, + "text-halo-color": "rgba(255,255,255,0.8)", + "text-halo-width": 2 + } + }, + { + "id": "place-country-1", + "type": "symbol", + "metadata": { + "mapbox:group": "1444849242106.713" + }, + "source": "openmaptiles", + "source-layer": "place", + "filter": [ + "all", + [ + "==", + "class", + "country" + ], + [ + "==", + "rank", + 1 + ], + [ + "has", + "iso_a2" + ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "migu2m-bold" + ], + "text-max-width": 6.25, + "text-size": { + "stops": [ + [ + 1, + 11 + ], + [ + 4, + 17 + ] + ] + }, + "text-transform": "uppercase", + "visibility": "visible" + }, + "paint": { + "text-color": "#334", + "text-halo-blur": 1, + "text-halo-color": "rgba(255,255,255,0.8)", + "text-halo-width": 2 + } + }, + { + "id": "place-continent", + "type": "symbol", + "metadata": { + "mapbox:group": "1444849242106.713" + }, + "source": "openmaptiles", + "source-layer": "place", + "maxzoom": 1, + "filter": [ + "==", + "class", + "continent" + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "migu2m-bold" + ], + "text-max-width": 6.25, + "text-size": 14, + "text-transform": "uppercase", + "visibility": "visible" + }, + "paint": { + "text-color": "#334", + "text-halo-blur": 1, + "text-halo-color": "rgba(255,255,255,0.8)", + "text-halo-width": 2 + } + } + ], + "id": "bright" +} diff --git a/example-app/src/main/assets/tokyo-trees.bin b/example-app/src/main/assets/tokyo-trees.bin new file mode 100644 index 000000000..3448c1cb7 Binary files /dev/null and b/example-app/src/main/assets/tokyo-trees.bin differ diff --git a/example-app/src/main/java/com/mapconductor/example/DemoAppScreen.kt b/example-app/src/main/java/com/mapconductor/example/DemoAppScreen.kt index a0586bff7..67337a6ea 100644 --- a/example-app/src/main/java/com/mapconductor/example/DemoAppScreen.kt +++ b/example-app/src/main/java/com/mapconductor/example/DemoAppScreen.kt @@ -1,359 +1,476 @@ -package com.mapconductor.example - -import androidx.appcompat.content.res.AppCompatResources -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import androidx.core.content.ContextCompat -import com.mapconductor.core.marker.ImageIcon -import com.mapconductor.example.navigation.NavigationViewModel -import com.mapconductor.example.pages.circle.CircleMapPage -import com.mapconductor.example.pages.geojson.basic.BasicGeoJSONMapPage -import com.mapconductor.example.pages.geojson.layer.GeoJSONLayerMapPage -import com.mapconductor.example.pages.groundimage.GroundImageMapPage -import com.mapconductor.example.pages.groundimage.GroundImageResources -import com.mapconductor.example.pages.heatmaplayer.HeatmapLayerPage -import com.mapconductor.example.pages.infobubble.MultipleBubblesPage -import com.mapconductor.example.pages.infobubble.RichContentBubblePage -import com.mapconductor.example.pages.infobubble.SimpleTextBubblePage -import com.mapconductor.example.pages.infobubble.StyledInfoBubblePage -import com.mapconductor.example.pages.kml.KMLMapPage -import com.mapconductor.example.pages.map.basic.StoreMapPage -import com.mapconductor.example.pages.map.camerasync.CameraSyncPage -import com.mapconductor.example.pages.map.design.MapDesignMapPage -import com.mapconductor.example.pages.map.fitbounds.FitBoundsMapPage -import com.mapconductor.example.pages.map.flyto.FlyToMapIcons -import com.mapconductor.example.pages.map.flyto.FlyToMapPage -import com.mapconductor.example.pages.map.tilt.TiltMapPage -import com.mapconductor.example.pages.map.uisettings.UISettingsMapPage -import com.mapconductor.example.pages.map.visibleregion.VisibleRegionPage -import com.mapconductor.example.pages.marker.animation.AnimationMapPage -import com.mapconductor.example.pages.marker.icons.MarkerBasicPage -import com.mapconductor.example.pages.marker.postoffice.PostOfficePage -import com.mapconductor.example.pages.marker.postofficecluster.MarkerClusterMapPage as PostOfficeClusterMapPage -import com.mapconductor.example.pages.polygon.basic.PolygonMapPage -import com.mapconductor.example.pages.polygon.click.PolygonClickPage -import com.mapconductor.example.pages.polygon.geodesic.PolygonGeodesicPage -import com.mapconductor.example.pages.polygon.hole.HolePolygonMapPage -import com.mapconductor.example.pages.polyline.PolylineClickMapPage -import com.mapconductor.example.pages.polyline.PolylineMapPage -import com.mapconductor.example.pages.rasterlayer.RasterHeaderProbePage -import com.mapconductor.example.pages.rasterlayer.RasterLayerMapPage -import com.mapconductor.example.pages.startup.StartUpPage -import com.mapconductor.example.ui.sidebar.Sidebar -import com.mapconductor.example.ui.sidebar.SidebarItem -import com.mapconductor.example.ui.sidebar.SidebarSection -import com.mapconductor.example.ui.theme.AppTheme - -@Composable -fun DemoAppScreen(initPage: String = "map") { - val navigationViewModel: NavigationViewModel = remember { NavigationViewModel(initPage) } - - val currentPage by navigationViewModel.currentPage - val isSidebarExpanded by navigationViewModel.isSidebarExpanded - val context = LocalContext.current - val flyToMapPageIcons = - remember { - FlyToMapIcons( - honolulu = ContextCompat.getDrawable(context, R.drawable.honolulu)!!, - tokyo = ContextCompat.getDrawable(context, R.drawable.tokyo)!!, - london = ContextCompat.getDrawable(context, R.drawable.london)!!, - newYork = ContextCompat.getDrawable(context, R.drawable.newyork)!!, - sydney = ContextCompat.getDrawable(context, R.drawable.sydney)!!, - ) - } - - val groundImageResources = - remember { - GroundImageResources( - image = ContextCompat.getDrawable(context, R.drawable.university_of_eswatini)!!, - ) - } - val postOfficeIcon = - remember { - val baseicon = AppCompatResources.getDrawable(context, R.drawable.postoffice)!! - ImageIcon( - image = baseicon, - scale = 0.5f, - ) - } - - val sidebarSections = - listOf( - SidebarSection( - title = "Map", - items = - listOf( - SidebarItem(id = "map-basic", title = "Map"), - SidebarItem(id = "tilt-map", title = "Tilt Map"), - SidebarItem(id = "ui-settings", title = "UI Settings"), - SidebarItem(id = "map-flyTo", title = "Move Camera"), - SidebarItem(id = "map-fitBounds", title = "Fit Bounds"), - SidebarItem(id = "map-design", title = "Map Design"), - SidebarItem(id = "map-visibleregion", title = "Visible Region"), - SidebarItem(id = "map-camerasync", title = "Camera Sync"), - SidebarItem(id = "camera-restriction", title = "Camera Restriction"), - ), - ), - SidebarSection( - title = "Info Bubble", - items = - listOf( - SidebarItem(id = "simple-info-bubble", title = "Simple Text Bubble"), - SidebarItem(id = "styled-info-bubble", title = "Custom Styled Bubble"), - SidebarItem(id = "rich-content-info-bubble", title = "Rich Content Bubble"), - SidebarItem(id = "multiple-info-bubbles", title = "Multiple Bubbles"), - ), - ), - SidebarSection( - title = "Marker", - items = - listOf( - SidebarItem(id = "marker-basic", title = "Marker"), - SidebarItem(id = "marker-animation", title = "Marker Animation"), - SidebarItem(id = "marker-postoffice", title = "Bunch of Markers"), - SidebarItem(id = "marker-postoffice-cluster", title = "Marker Clustering"), - ), - ), - SidebarSection( - title = "Circle", - items = listOf(SidebarItem(id = "circle", title = "Circle")), - ), - SidebarSection( - title = "Ground Image", - items = listOf(SidebarItem(id = "groundImage", title = "Ground Image")), - ), - SidebarSection( - title = "Polyline", - items = - listOf( - SidebarItem(id = "polyline", title = "Polyline"), - SidebarItem(id = "polyline-click", title = "Polyline Click"), - ), - ), - SidebarSection( - title = "Polygon", - items = - listOf( - SidebarItem(id = "polygon", title = "Polygon"), - SidebarItem(id = "polygon-click", title = "Polygon Click"), - SidebarItem(id = "polygon-geodesic", title = "Geodesic Polygons"), - SidebarItem(id = "polygon-hole", title = "Hole Polygon"), - ), - ), - SidebarSection( - title = "Raster Layer", - items = listOf(SidebarItem(id = "raster-layer", title = "Raster Layer")), - ), - SidebarSection( - title = "Heatmap Layer", - items = listOf(SidebarItem(id = "heatmap-overlay", title = "Heatmap Overlay")), - ), - SidebarSection( - title = "GeoJSON", - items = - listOf( - SidebarItem(id = "geojson-basic", title = "Basic GeoJSON"), - SidebarItem(id = "geojson-layer", title = "GeoJSON Layer"), - ), - ), - SidebarSection( - title = "KML", - items = listOf(SidebarItem(id = "kml-layer", title = "KML Layer")), - ), - ) - - AppTheme { - Box(modifier = Modifier.fillMaxSize()) { - // Main content - Box(modifier = Modifier.fillMaxSize()) { - when (currentPage) { - "startup" -> { - StartUpPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "simple-info-bubble" -> { - SimpleTextBubblePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "styled-info-bubble" -> { - StyledInfoBubblePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "rich-content-info-bubble" -> { - RichContentBubblePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "multiple-info-bubbles" -> { - MultipleBubblesPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "camera-restriction" -> { - com.mapconductor.example.pages.map.camerarestriction.CameraRestrictionMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - - "ui-settings" -> { - UISettingsMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "map-basic" -> { - StoreMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "map-design" -> { - MapDesignMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "map-visibleregion" -> { - VisibleRegionPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) -// ZoomCalibrationPage( -// onToggleSidebar = navigationViewModel::toggleSidebar, -// ) - } - "map-camerasync" -> { - CameraSyncPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "map-flyTo" -> { - FlyToMapPage( - icons = flyToMapPageIcons, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "map-fitBounds" -> { - FitBoundsMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "marker-basic" -> { - MarkerBasicPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "marker-animation" -> { - AnimationMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "marker-postoffice" -> { - PostOfficePage( - postOfficeIcon = postOfficeIcon, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "marker-postoffice-cluster" -> { - PostOfficeClusterMapPage( - postOfficeIcon = postOfficeIcon, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "circle" -> { - CircleMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "polyline" -> { - PolylineMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "polyline-click" -> { - PolylineClickMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "polygon" -> { - PolygonMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "polygon-click" -> { - PolygonClickPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "polygon-geodesic" -> { - PolygonGeodesicPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "polygon-hole" -> { - HolePolygonMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "groundImage" -> { - GroundImageMapPage( - groundImageResources = groundImageResources, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "raster-layer" -> { - RasterLayerMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - // 計測専用。サイドバーには出さない(RasterHeaderInstrumentedTest が使う)。 - "raster-header" -> { - RasterHeaderProbePage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "heatmap-overlay" -> { - HeatmapLayerPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "geojson-basic" -> { - BasicGeoJSONMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "geojson-layer" -> { - GeoJSONLayerMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "kml-layer" -> { - KMLMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - "tilt-map" -> { - TiltMapPage( - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - } - } - - // Overlay sidebar - Sidebar( - sections = sidebarSections, - selectedItemId = currentPage, - onItemClick = { item -> - navigationViewModel.navigateTo(item.id) - }, - isExpanded = isSidebarExpanded, - onToggleSidebar = navigationViewModel::toggleSidebar, - ) - } - } -} +package com.mapconductor.example + +import androidx.appcompat.content.res.AppCompatResources +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.core.content.ContextCompat +import com.mapconductor.core.marker.ImageIcon +import com.mapconductor.example.navigation.NavigationViewModel +import com.mapconductor.example.pages.circle.AntennaHorizonsPage +import com.mapconductor.example.pages.circle.CircleMapPage +import com.mapconductor.example.pages.geojson.basic.BasicGeoJSONMapPage +import com.mapconductor.example.pages.geojson.layer.GeoJSONLayerMapPage +import com.mapconductor.example.pages.groundimage.GroundImageMapPage +import com.mapconductor.example.pages.groundimage.GroundImageResources +import com.mapconductor.example.pages.heatmaplayer.HeatmapLayerPage +import com.mapconductor.example.pages.infobubble.MultipleBubblesPage +import com.mapconductor.example.pages.infobubble.RichContentBubblePage +import com.mapconductor.example.pages.infobubble.SimpleTextBubblePage +import com.mapconductor.example.pages.infobubble.StyledInfoBubblePage +import com.mapconductor.example.pages.kml.KMLMapPage +import com.mapconductor.example.pages.map.basic.StoreMapPage +import com.mapconductor.example.pages.map.camerarestriction.CameraRestrictionMapPage +import com.mapconductor.example.pages.map.camerasync.CameraSyncPage +import com.mapconductor.example.pages.map.design.MapDesignMapPage +import com.mapconductor.example.pages.map.fitbounds.FitBoundsMapPage +import com.mapconductor.example.pages.map.flyto.FlyToMapIcons +import com.mapconductor.example.pages.map.flyto.FlyToMapPage +import com.mapconductor.example.pages.map.projected.ProjectedCoordinatesPage +import com.mapconductor.example.pages.map.tilt.TiltMapPage +import com.mapconductor.example.pages.map.uisettings.UISettingsMapPage +import com.mapconductor.example.pages.map.visibleregion.VisibleRegionPage +import com.mapconductor.example.pages.marker.animation.AnimationMapPage +import com.mapconductor.example.pages.marker.icons.MarkerBasicPage +import com.mapconductor.example.pages.marker.labelposition.MarkerLabelPositionPage +import com.mapconductor.example.pages.marker.postoffice.PostOfficePage +import com.mapconductor.example.pages.marker.postofficecluster.MarkerClusterMapPage as PostOfficeClusterMapPage +import com.mapconductor.example.pages.marker.streettree.StreetTreePage +import com.mapconductor.example.pages.offlinemap.OfflineMapPage +import com.mapconductor.example.pages.polygon.basic.PolygonMapPage +import com.mapconductor.example.pages.polygon.boston.BostonBuildingsPage +import com.mapconductor.example.pages.polygon.click.PolygonClickPage +import com.mapconductor.example.pages.polygon.collection.PolygonsMapPage +import com.mapconductor.example.pages.polygon.geodesic.PolygonGeodesicPage +import com.mapconductor.example.pages.polygon.hole.HolePolygonMapPage +import com.mapconductor.example.pages.polyline.PolylineClickMapPage +import com.mapconductor.example.pages.polyline.PolylineMapPage +import com.mapconductor.example.pages.polyline.boston.BostonRoadsPage +import com.mapconductor.example.pages.rasterlayer.RasterHeaderProbePage +import com.mapconductor.example.pages.rasterlayer.RasterLayerMapPage +import com.mapconductor.example.pages.startup.StartUpPage +import com.mapconductor.example.pages.vectorstyle.VectorStylePage +import com.mapconductor.example.pages.vectortile.VectorTilePage +import com.mapconductor.example.ui.sidebar.Sidebar +import com.mapconductor.example.ui.sidebar.SidebarItem +import com.mapconductor.example.ui.sidebar.SidebarSection +import com.mapconductor.example.ui.theme.AppTheme + +@Composable +fun DemoAppScreen(initPage: String = "map") { + val navigationViewModel: NavigationViewModel = remember { NavigationViewModel(initPage) } + + val currentPage by navigationViewModel.currentPage + val isSidebarExpanded by navigationViewModel.isSidebarExpanded + val context = LocalContext.current + val flyToMapPageIcons = + remember { + FlyToMapIcons( + honolulu = ContextCompat.getDrawable(context, R.drawable.honolulu)!!, + tokyo = ContextCompat.getDrawable(context, R.drawable.tokyo)!!, + london = ContextCompat.getDrawable(context, R.drawable.london)!!, + newYork = ContextCompat.getDrawable(context, R.drawable.newyork)!!, + sydney = ContextCompat.getDrawable(context, R.drawable.sydney)!!, + ) + } + + val groundImageResources = + remember { + GroundImageResources( + image = ContextCompat.getDrawable(context, R.drawable.university_of_eswatini)!!, + ) + } + val postOfficeIcon = + remember { + val baseicon = AppCompatResources.getDrawable(context, R.drawable.postoffice)!! + ImageIcon( + image = baseicon, + scale = 0.5f, + ) + } + + val sidebarSections = + listOf( + SidebarSection( + title = "Map", + items = + listOf( + SidebarItem(id = "map-basic", title = "Map"), + SidebarItem(id = "tilt-map", title = "Tilt Map"), + SidebarItem(id = "ui-settings", title = "UI Settings"), + SidebarItem(id = "map-flyTo", title = "Move Camera"), + SidebarItem(id = "map-fitBounds", title = "Fit Bounds"), + SidebarItem(id = "map-design", title = "Map Design"), + SidebarItem(id = "map-visibleregion", title = "Visible Region"), + SidebarItem(id = "map-projected", title = "Projected Coordinates"), + SidebarItem(id = "map-camerasync", title = "Camera Sync"), + SidebarItem(id = "camera-restriction", title = "Camera Restriction"), + ), + ), + SidebarSection( + title = "Info Bubble", + items = + listOf( + SidebarItem(id = "simple-info-bubble", title = "Simple Text Bubble"), + SidebarItem(id = "styled-info-bubble", title = "Custom Styled Bubble"), + SidebarItem(id = "rich-content-info-bubble", title = "Rich Content Bubble"), + SidebarItem(id = "multiple-info-bubbles", title = "Multiple Bubbles"), + ), + ), + SidebarSection( + title = "Marker", + items = + listOf( + SidebarItem(id = "marker-basic", title = "Marker"), + SidebarItem(id = "marker-label-position", title = "Marker Label Position"), + SidebarItem(id = "marker-animation", title = "Marker Animation"), + SidebarItem(id = "marker-postoffice", title = "Bunch of Markers"), + SidebarItem(id = "marker-postoffice-cluster", title = "Marker Clustering"), + SidebarItem(id = "marker-streettree", title = "Street Trees"), + ), + ), + SidebarSection( + title = "Circle", + items = + listOf( + SidebarItem(id = "circle", title = "Circle"), + SidebarItem(id = "antenna-horizons", title = "US Antenna Horizons"), + ), + ), + SidebarSection( + title = "Ground Image", + items = listOf(SidebarItem(id = "groundImage", title = "Ground Image")), + ), + SidebarSection( + title = "Polyline", + items = + listOf( + SidebarItem(id = "polyline", title = "Polyline"), + SidebarItem(id = "polyline-click", title = "Polyline Click"), + SidebarItem(id = "boston-roads", title = "Boston Roads"), + ), + ), + SidebarSection( + title = "Polygon", + items = + listOf( + SidebarItem(id = "polygon", title = "Polygon"), + SidebarItem(id = "polygon-click", title = "Polygon Click"), + SidebarItem(id = "polygon-geodesic", title = "Geodesic Polygons"), + SidebarItem(id = "polygon-hole", title = "Hole Polygon"), + SidebarItem(id = "polygons", title = "Polygons"), + SidebarItem(id = "boston-buildings", title = "Boston Buildings"), + ), + ), + SidebarSection( + title = "Raster Layer", + items = listOf(SidebarItem(id = "raster-layer", title = "Raster Layer")), + ), + SidebarSection( + title = "Heatmap Layer", + items = listOf(SidebarItem(id = "heatmap-overlay", title = "Heatmap Overlay")), + ), + SidebarSection( + title = "Vector Tile Layer", + items = + listOf( + SidebarItem(id = "vector-tile", title = "MapLibre Style"), + SidebarItem(id = "vector-style", title = "Style Adjustments"), + SidebarItem(id = "offline-map", title = "Offline Map"), + ), + ), + SidebarSection( + title = "GeoJSON", + items = + listOf( + SidebarItem(id = "geojson-basic", title = "Basic GeoJSON"), + SidebarItem(id = "geojson-layer", title = "GeoJSON Layer"), + ), + ), + SidebarSection( + title = "KML", + items = listOf(SidebarItem(id = "kml-layer", title = "KML Layer")), + ), + ) + + AppTheme { + Box(modifier = Modifier.fillMaxSize()) { + // Main content + Box(modifier = Modifier.fillMaxSize()) { + when (currentPage) { + "startup" -> { + StartUpPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "simple-info-bubble" -> { + SimpleTextBubblePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "styled-info-bubble" -> { + StyledInfoBubblePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "rich-content-info-bubble" -> { + RichContentBubblePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "multiple-info-bubbles" -> { + MultipleBubblesPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "camera-restriction" -> { + CameraRestrictionMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "ui-settings" -> { + UISettingsMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-basic" -> { + StoreMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-design" -> { + MapDesignMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-visibleregion" -> { + VisibleRegionPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) +// ZoomCalibrationPage( +// onToggleSidebar = navigationViewModel::toggleSidebar, +// ) + } + + "map-projected" -> { + ProjectedCoordinatesPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-camerasync" -> { + CameraSyncPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-flyTo" -> { + FlyToMapPage( + icons = flyToMapPageIcons, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "map-fitBounds" -> { + FitBoundsMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-basic" -> { + MarkerBasicPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-label-position" -> { + MarkerLabelPositionPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-animation" -> { + AnimationMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-postoffice" -> { + PostOfficePage( + postOfficeIcon = postOfficeIcon, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-postoffice-cluster" -> { + PostOfficeClusterMapPage( + postOfficeIcon = postOfficeIcon, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "marker-streettree" -> { + StreetTreePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "circle" -> { + CircleMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polyline" -> { + PolylineMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polyline-click" -> { + PolylineClickMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygon" -> { + PolygonMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygon-click" -> { + PolygonClickPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygon-geodesic" -> { + PolygonGeodesicPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygon-hole" -> { + HolePolygonMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "polygons" -> { + PolygonsMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "boston-buildings" -> { + BostonBuildingsPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "antenna-horizons" -> { + AntennaHorizonsPage(onToggleSidebar = navigationViewModel::toggleSidebar) + } + + "boston-roads" -> { + BostonRoadsPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "groundImage" -> { + GroundImageMapPage( + groundImageResources = groundImageResources, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "raster-layer" -> { + RasterLayerMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + // 計測専用。サイドバーには出さない(RasterHeaderInstrumentedTest が使う)。 + "raster-header" -> { + RasterHeaderProbePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "heatmap-overlay" -> { + HeatmapLayerPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "vector-tile" -> { + VectorTilePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "vector-style" -> { + VectorStylePage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "offline-map" -> { + OfflineMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "geojson-basic" -> { + BasicGeoJSONMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "geojson-layer" -> { + GeoJSONLayerMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "kml-layer" -> { + KMLMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + + "tilt-map" -> { + TiltMapPage( + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + } + } + + // Overlay sidebar + Sidebar( + sections = sidebarSections, + selectedItemId = currentPage, + onItemClick = { item -> + navigationViewModel.navigateTo(item.id) + }, + isExpanded = isSidebarExpanded, + onToggleSidebar = navigationViewModel::toggleSidebar, + ) + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/MapViewContainer.kt b/example-app/src/main/java/com/mapconductor/example/MapViewContainer.kt index 604c4ea9b..314f88c60 100644 --- a/example-app/src/main/java/com/mapconductor/example/MapViewContainer.kt +++ b/example-app/src/main/java/com/mapconductor/example/MapViewContainer.kt @@ -11,6 +11,7 @@ import com.mapconductor.core.OnMapEventHandler import com.mapconductor.core.OnMapLoadedHandler import com.mapconductor.core.map.CameraRestriction import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.map.MapViewStyle import com.mapconductor.core.marker.MarkerTilingOptions import com.mapconductor.example.ui.LocalSelectedProviderKey import com.mapconductor.googlemaps.GoogleMapView @@ -50,6 +51,10 @@ fun MapViewContainer( onCameraMoveStart: OnCameraMoveHandler? = null, onCameraMove: OnCameraMoveHandler? = null, onCameraMoveEnd: OnCameraMoveHandler? = null, + // 1 か所でまとめて渡す。全プロバイダが同じ名前で受けるので、ここに分岐は無い + // ——「どのバックエンドで何が起きるか」はスタイル側とプロバイダの能力宣言が決める。 + style: MapViewStyle? = null, + onStyleDiagnostics: ((List) -> Unit)? = null, content: (@Composable MapViewScope.() -> Unit)? = null, ) { @Suppress("UNCHECKED_CAST") @@ -66,6 +71,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) @@ -81,6 +88,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) @@ -96,6 +105,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) @@ -112,6 +123,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) } else { @@ -126,6 +139,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) } @@ -142,6 +157,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) @@ -157,6 +174,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) @@ -172,6 +191,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) @@ -187,6 +208,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) @@ -202,6 +225,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) @@ -217,6 +242,8 @@ fun MapViewContainer( onCameraMoveStart = onCameraMoveStart, onCameraMove = onCameraMove, onCameraMoveEnd = onCameraMoveEnd, + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, ) diff --git a/example-app/src/main/java/com/mapconductor/example/StarCircleView.kt b/example-app/src/main/java/com/mapconductor/example/StarCircleView.kt index 259ccb409..20ea761a1 100644 --- a/example-app/src/main/java/com/mapconductor/example/StarCircleView.kt +++ b/example-app/src/main/java/com/mapconductor/example/StarCircleView.kt @@ -1,69 +1,69 @@ -package com.mapconductor.example - -import android.content.Context -import android.graphics.Canvas -import android.graphics.Color -import android.graphics.Paint -import android.graphics.Path -import android.util.AttributeSet -import android.view.View - -class StarCircleView - @JvmOverloads - constructor( - context: Context, - attrs: AttributeSet? = null, - defStyleAttr: Int = 0, - ) : View(context, attrs, defStyleAttr) { - private val paint = Paint(Paint.ANTI_ALIAS_FLAG) - - override fun onDraw(canvas: Canvas) { - super.onDraw(canvas) - canvas.save() - canvas.scale(10f, 10f) - - // 背景:黄色い円 (#FFD400), 半径12px, 中心(14, 14) - paint.color = Color.parseColor("#FFD400") - paint.style = Paint.Style.FILL - canvas.drawCircle(14f, 14f, 12f, paint) - - // 五芒星座標(SVGの polygon → scale(0.91), translate(1.26, 0.26) を適用済み) - val starPath = Path() - - // スケーリングと平行移動を反映した点列(直接数値を適用) - val points = - arrayOf( - Pair(14f, 4f), - Pair(16.94f, 11.4f), - Pair(24.9f, 11.4f), - Pair(18.48f, 16.1f), - Pair(21.42f, 23.5f), - Pair(14f, 18.8f), - Pair(6.58f, 23.5f), - Pair(9.52f, 16.1f), - Pair(3.1f, 11.4f), - Pair(11.06f, 11.4f), - ) - - // 変換処理:scale(0.91) → x*0.91, y*0.91 / translate(1.26, 0.26) - val transformed = - points.map { (x, y) -> - val scaledX = x * 0.91f + 1.26f - val scaledY = y * 0.91f + 0.26f - Pair(scaledX, scaledY) - } - - // Path構築(moveTo → lineTo) - starPath.moveTo(transformed[0].first, transformed[0].second) - for (i in 1 until transformed.size) { - starPath.lineTo(transformed[i].first, transformed[i].second) - } - starPath.close() - - // 星を白で塗りつぶし - paint.color = Color.WHITE - canvas.drawPath(starPath, paint) - - canvas.restore() - } - } +package com.mapconductor.example + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.util.AttributeSet +import android.view.View + +class StarCircleView + @JvmOverloads + constructor( + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0, + ) : View(context, attrs, defStyleAttr) { + private val paint = Paint(Paint.ANTI_ALIAS_FLAG) + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + canvas.save() + canvas.scale(10f, 10f) + + // 背景:黄色い円 (#FFD400), 半径12px, 中心(14, 14) + paint.color = Color.parseColor("#FFD400") + paint.style = Paint.Style.FILL + canvas.drawCircle(14f, 14f, 12f, paint) + + // 五芒星座標(SVGの polygon → scale(0.91), translate(1.26, 0.26) を適用済み) + val starPath = Path() + + // スケーリングと平行移動を反映した点列(直接数値を適用) + val points = + arrayOf( + Pair(14f, 4f), + Pair(16.94f, 11.4f), + Pair(24.9f, 11.4f), + Pair(18.48f, 16.1f), + Pair(21.42f, 23.5f), + Pair(14f, 18.8f), + Pair(6.58f, 23.5f), + Pair(9.52f, 16.1f), + Pair(3.1f, 11.4f), + Pair(11.06f, 11.4f), + ) + + // 変換処理:scale(0.91) → x*0.91, y*0.91 / translate(1.26, 0.26) + val transformed = + points.map { (x, y) -> + val scaledX = x * 0.91f + 1.26f + val scaledY = y * 0.91f + 0.26f + Pair(scaledX, scaledY) + } + + // Path構築(moveTo → lineTo) + starPath.moveTo(transformed[0].first, transformed[0].second) + for (i in 1 until transformed.size) { + starPath.lineTo(transformed[i].first, transformed[i].second) + } + starPath.close() + + // 星を白で塗りつぶし + paint.color = Color.WHITE + canvas.drawPath(starPath, paint) + + canvas.restore() + } + } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/circle/AntennaHorizonsPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/circle/AntennaHorizonsPage.kt new file mode 100644 index 000000000..794e951ac --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/circle/AntennaHorizonsPage.kt @@ -0,0 +1,252 @@ +package com.mapconductor.example.pages.circle + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.text.ClickableText +import androidx.compose.material3.Checkbox +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.unit.dp +import com.mapconductor.compose.circle.Circles +import com.mapconductor.compose.info.InfoBubble +import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +private val carrierNames = listOf("AT&T", "T-Mobile / Sprint", "Verizon", "Others") +private val carrierColors = listOf(Color(0xFF2563EB), Color(0xFFDB2777), Color(0xFFD97706), Color(0xFF64748B)) + +private data class Antenna( + val lat: Double, + val lon: Double, + val radius: Double, + val registration: Long, + val carrier: Int, +) + +// Keep source records packed. CircleState.extra resolves a row on demand; +// retaining another 723,800 JVM record objects would duplicate the source data. +private class AntennaTable( + bytes: ByteArray, +) : AbstractList() { + private val buffer = ByteBuffer.wrap(bytes).asReadOnlyBuffer().order(ByteOrder.LITTLE_ENDIAN) + override val size: Int + val carrierCounts = IntArray(4) + + init { + require(bytes.size >= 8 && String(bytes, 0, 4, Charsets.US_ASCII) == "MCCE") + size = buffer.getInt(4) + require(size >= 0 && bytes.size.toLong() == 8L + size * 16L) + for (index in 0 until size) { + val row = get(index) + require( + row.lat.isFinite() && + row.lat in -90.0..90.0 && + row.lon.isFinite() && + row.lon in -180.0..180.0 && + row.radius > 0 && + row.radius <= 100000 && + row.carrier in 0..3, + ) + carrierCounts[row.carrier]++ + } + } + + override fun get(index: Int): Antenna { + require(index in 0 until size) + val p = 8 + index * 16 + return Antenna( + buffer.getInt(p) / 100000.0, buffer.getInt(p + 4) / 100000.0, + buffer.getFloat(p + 8).toDouble(), index.toLong(), buffer.getInt(p + 12) / 1000, + ) + } + + fun carrierAt(index: Int): Int = buffer.getInt(8 + index * 16 + 12) / 1000 +} + +@Composable +fun AntennaHorizonsPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val context = LocalContext.current + val uriHandler = LocalUriHandler.current + var carriers by remember { mutableStateOf(setOf(0, 1, 2, 3)) } + var rows by remember { mutableStateOf>(emptyList()) } + var error by remember { mutableStateOf(null) } + var alaska by remember { mutableStateOf(false) } + var mapState by remember { mutableStateOf?>(null) } + var states by remember { mutableStateOf>(emptyList()) } + var allStates by remember { mutableStateOf>(emptyList()) } + var tap by remember { mutableStateOf(null) } + var adding by remember { mutableStateOf?>(null) } + LaunchedEffect(Unit) { + try { + rows = + withContext(Dispatchers.IO) { + val bytes = context.assets.open("antennas/us-antennas.bin").use { it.readBytes() } + AntennaTable(bytes) + } + } catch (e: Exception) { + error = e.message + } + } + LaunchedEffect(rows) { + tap = null + allStates = + withContext(Dispatchers.Default) { + val onCellClick: com.mapconductor.core.circle.OnCircleEventHandler = { event -> + tap = + (event.state.extra as? String)?.removePrefix("asr-")?.toIntOrNull()?.let { rows.getOrNull(it) } + } + rows.map { a -> + val color = carrierColors[a.carrier] + val id = "asr-${a.registration}" + CircleState( + center = GeoPoint(a.lat, a.lon), + radiusMeters = 500.0, + id = id, + geodesic = true, + zIndex = a.registration.toInt(), + strokeWidth = 0.5.dp, + strokeColor = color.copy(alpha = 0.35f), + fillColor = color.copy(alpha = 0.65f), + extra = id, + onClick = onCellClick, + ) + } + } + } + LaunchedEffect(allStates, carriers) { + tap = null + states = + withContext(Dispatchers.Default) { + if (carriers.size == carrierNames.size) { + allStates + } else if (carriers.isEmpty()) { + emptyList() + } else { + allStates.filterIndexed { index, _ -> + ((rows as? AntennaTable)?.carrierAt(index) ?: rows[index].carrier) in carriers + } + } + } + } + val camera = + remember(alaska) { + MapCameraPosition( + position = if (alaska) GeoPoint(64.0, -150.0) else GeoPoint(39.0, -98.0), + zoom = if (alaska) 5.0 else 4.0, + ) + } + key(alaska) { + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(camera), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { mapState = it }, + ) { padding -> + mapState?.let { state -> + MapViewContainer(state = state, modifier = modifier.padding(padding), onMapClick = { tap = null }) { + Circles( + states, + onAddStart = { total -> adding = 0 to total }, + onAddProgress = { added, total -> adding = added to total }, + onAddEnd = { adding = null }, + ) + tap?.let { a -> + InfoBubble( + position = + GeoPoint( + a.lat, + a.lon, + ), + ) { Text("${carrierNames[a.carrier]}\nCell position · Display radius: 500 m") } + } + } + } + Column( + Modifier + .padding(top = padding.calculateTopPadding() + 12.dp, start = 12.dp) + .widthIn(max = 350.dp) + .background(MaterialTheme.colorScheme.surface) + .padding(12.dp), + ) { + Text("US cell positions (MCC 310–314)", style = MaterialTheme.typography.titleMedium) + Text( + error + ?: if (rows.isEmpty()) "Loading OpenCellID data…" else "${states.size} / ${rows.size} circles", + ) + adding?.let { (added, total) -> Text("Adding to the map… $added / $total") } + TextButton(onClick = { alaska = !alaska }) { Text(if (alaska) "US overview" else "Alaska") } + carrierNames.forEachIndexed { index, name -> + Row { + Checkbox( + index in carriers, + { checked -> + carriers = if (checked) carriers + index else carriers - index + }, + ) + Text("$name (${(rows as? AntennaTable)?.carrierCounts?.get(index) ?: 0})") + } + } + Text( + "Cell positions shown as 500 m radius circles; not signal coverage. Showing all cells for the selected carriers. MCC 310–314; not a complete tower inventory.", + style = MaterialTheme.typography.bodySmall, + ) + ClickableText( + text = + buildAnnotatedString { + append("Cell tower data from ") + pushStringAnnotation("URL", "https://opencellid.org") + append("OpenCellID") + pop() + append(" · ") + pushStringAnnotation( + "URL", + "https://creativecommons.org/licenses/by-sa/4.0/", + ) + append("CC BY-SA 4.0") + pop() + }, + style = MaterialTheme.typography.bodySmall.copy(color = MaterialTheme.colorScheme.primary), + onClick = { offset -> + // Link annotations keep both source and license independently tappable. + val url = + if (offset < + 30 + ) { + "https://opencellid.org" + } else { + "https://creativecommons.org/licenses/by-sa/4.0/" + } + uriHandler.openUri(url) + }, + ) + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/circle/CircleMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/circle/CircleMapPage.kt index d6c39d8cf..f103f1039 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/circle/CircleMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/circle/CircleMapPage.kt @@ -20,10 +20,14 @@ import com.mapconductor.example.ui.DemoMapPageScaffold import com.mapconductor.example.ui.MessageCard @Composable -fun CircleMapPage(onToggleSidebar: () -> Unit = {}) { +fun CircleMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel = remember { CirclePageViewModel() } DemoMapPageScaffold( menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = viewModel::onMapViewChanged, ) { paddingValues -> diff --git a/example-app/src/main/java/com/mapconductor/example/pages/circle/CirclePageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/circle/CirclePageViewModel.kt index 35f6eb0a7..7f1d0164d 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/circle/CirclePageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/circle/CirclePageViewModel.kt @@ -236,8 +236,4 @@ class CirclePageViewModel( override fun removeToast(toastMessage: ToastMessage) { this._messages.value = this._messages.value.filter { it != toastMessage } } - - override fun onCleared() { - super.onCleared() - } } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/geojson/basic/BasicGeoJSONMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/geojson/basic/BasicGeoJSONMapPage.kt index aa29b2846..db9670e3b 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/geojson/basic/BasicGeoJSONMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/geojson/basic/BasicGeoJSONMapPage.kt @@ -6,6 +6,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapViewStateInterface @@ -20,7 +21,10 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @Composable -fun BasicGeoJSONMapPage(onToggleSidebar: () -> Unit = {}) { +fun BasicGeoJSONMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val initCameraPosition = remember { MapCameraPosition( @@ -32,10 +36,13 @@ fun BasicGeoJSONMapPage(onToggleSidebar: () -> Unit = {}) { DemoMapPageScaffold( menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = { mapViewState = it }, ) { - BasicGeoJSONMapComponent(mapViewState = mapViewState) + BasicGeoJSONMapComponent( + mapViewState = mapViewState, + ) } } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/geojson/layer/ExampleGeoJSONLayerLoader.kt b/example-app/src/main/java/com/mapconductor/example/pages/geojson/layer/ExampleGeoJSONLayerLoader.kt index 8d8ce56d3..a259ff770 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/geojson/layer/ExampleGeoJSONLayerLoader.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/geojson/layer/ExampleGeoJSONLayerLoader.kt @@ -33,6 +33,7 @@ class ExampleGeoJSONLayerLoader( // GeoJSONParser closes its input, so shield the ZIP stream itself. features = GeoJSONParser.parseStream(NonClosingInputStream(zipInput)) } + fileName.equals(STYLE_ENTRY, ignoreCase = true) -> { styleJson = zipInput.bufferedReader(Charsets.UTF_8).readText() } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/geojson/layer/GeoJSONLayerMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/geojson/layer/GeoJSONLayerMapPage.kt index 679b62385..7cf21797e 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/geojson/layer/GeoJSONLayerMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/geojson/layer/GeoJSONLayerMapPage.kt @@ -70,7 +70,10 @@ private val PROPERTY_LABELS = private const val ENGLISH_SUFFIX = "_en" @Composable -fun GeoJSONLayerMapPage(onToggleSidebar: () -> Unit = {}) { +fun GeoJSONLayerMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val initCameraPosition = remember { MapCameraPosition( @@ -82,10 +85,13 @@ fun GeoJSONLayerMapPage(onToggleSidebar: () -> Unit = {}) { DemoMapPageScaffold( menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = { mapViewState = it }, ) { paddingValues -> - GeoJSONLayerMapComponent(mapViewState = mapViewState) + GeoJSONLayerMapComponent( + mapViewState = mapViewState, + ) MessageCard( title = "GeoJSON Layer", @@ -104,7 +110,10 @@ fun GeoJSONLayerMapPage(onToggleSidebar: () -> Unit = {}) { } @Composable -private fun GeoJSONLayerMapComponent(mapViewState: MapViewStateInterface<*>?) { +private fun GeoJSONLayerMapComponent( + mapViewState: MapViewStateInterface<*>?, + modifier: Modifier = Modifier, +) { val context = LocalContext.current var selectedFeature by remember { mutableStateOf(null) } var tappedPosition by remember { mutableStateOf(null) } @@ -147,6 +156,7 @@ private fun GeoJSONLayerMapComponent(mapViewState: MapViewStateInterface<*>?) { mapViewState?.let { state -> MapViewContainer( state = state, + modifier = modifier, onMapClick = { clicked -> if (!layerState.processClick(clicked, pixelTolerance = 10.0, zoom = state.cameraPosition.zoom)) { tappedPosition = null diff --git a/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPage.kt index 0261a6d0a..c9f9c4bb8 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPage.kt @@ -1,10 +1,12 @@ package com.mapconductor.example.pages.groundimage import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.padding import androidx.compose.material3.Slider +import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState @@ -28,6 +30,7 @@ import kotlinx.coroutines.launch @Composable fun GroundImageMapPage( groundImageResources: GroundImageResources, + modifier: Modifier = Modifier, onToggleSidebar: () -> Unit = {}, ) { val viewModel = remember { GroundImageMapPageViewModel(groundImageResources) } @@ -38,6 +41,7 @@ fun GroundImageMapPage( DemoMapPageScaffold( menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = viewModel::onMapViewChanged, ) { paddingValues -> @@ -61,6 +65,13 @@ fun GroundImageMapPage( title = "GroundImage Example", ) { Column { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("image from URL", modifier = Modifier.weight(1f)) + Switch( + checked = viewModel.useImageUrl, + onCheckedChange = { viewModel.useImageUrl = it }, + ) + } Text("opacity: ${"%.2f".format(sliderOpacity)}") Slider( value = sliderOpacity, diff --git a/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPageViewModel.kt index 13ead3a3c..5023791cf 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/groundimage/GroundImageMapPageViewModel.kt @@ -1,240 +1,255 @@ -package com.mapconductor.example.pages.groundimage - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.dp -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.features.GeoRectBounds -import com.mapconductor.core.groundimage.GroundImageEvent -import com.mapconductor.core.groundimage.GroundImageState -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.polyline.PolylineState -import com.mapconductor.example.toast.ToastMessage -import android.graphics.drawable.Drawable -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -interface GroundImageMapPageViewModelInterface { - val initCameraPosition: MapCameraPosition - val mapViewState: StateFlow?> - val messages: StateFlow> - - val markers: List - val framePolyline: PolylineState - val imageResources: GroundImageResources - val image: Drawable - var opacity: Float - val groundImageState: GroundImageState - - fun onMapViewChanged(state: MapViewStateInterface<*>) - - fun onGroundImageClick(clicked: GroundImageEvent) - - fun onMarkerDrag(dragged: MarkerState) - - fun showToast(text: String) - - fun removeToast(toastMessage: ToastMessage) -} - -class GroundImageMapPageViewModel( - override val imageResources: GroundImageResources, -) : ViewModel(), - GroundImageMapPageViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - // Drone imagery over the University of Eswatini campus. Same content as - // react-sdk/examples/basic and the iOS sample. - position = - GeoPoint.fromLatLong( - latitude = -26.479235, - longitude = 31.306239, - ), - zoom = 15.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - - private val _mapViewState = MutableStateFlow?>(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - override fun onMapViewChanged(state: MapViewStateInterface<*>) { - mapViewState.value?.cameraPosition?.let { - state.moveCameraTo(it) - } - this._mapViewState.value = state - } - - private val _messages: MutableStateFlow> = MutableStateFlow(emptyList()) - override val messages: StateFlow> = _messages.asStateFlow() - - private var southWestPosition by mutableStateOf( - GeoPoint( - latitude = -26.484901389754125, - longitude = 31.2995982170105, - ), - ) - - private var northEastPosition by mutableStateOf( - GeoPoint( - latitude = -26.473569450536356, - longitude = 31.31288051605225, - ), - ) - - private fun calculateMarkerLabels(): Pair { - val swLat = southWestPosition.latitude - val swLng = southWestPosition.longitude - val neLat = northEastPosition.latitude - val neLng = northEastPosition.longitude - - val southWestLabel = - when { - swLat <= neLat && swLng <= neLng -> "SW" // Normal - swLat <= neLat && swLng > neLng -> "SE" // East-West flipped - swLat > neLat && swLng <= neLng -> "NW" // North-South flipped - else -> "NE" // Both flipped - } - - val northEastLabel = - when { - neLat >= swLat && neLng >= swLng -> "NE" // Normal - neLat >= swLat && neLng < swLng -> "NW" // East-West flipped - neLat < swLat && neLng >= swLng -> "SE" // North-South flipped - else -> "SW" // Both flipped - } - - return Pair(southWestLabel, northEastLabel) - } - - override val markers: List - get() { - val (swLabel, neLabel) = calculateMarkerLabels() - return listOf( - MarkerState( - id = "south_west", - position = southWestPosition, - icon = - DefaultMarkerIcon( - fillColor = Color.Blue, - strokeColor = Color.White, - label = swLabel, - labelTextColor = Color.White, - ), - draggable = true, - onDrag = this::onMarkerDrag, - ), - MarkerState( - id = "north_east", - position = northEastPosition, - icon = - DefaultMarkerIcon( - fillColor = Color.Red, - strokeColor = Color.White, - label = neLabel, - labelTextColor = Color.White, - ), - draggable = true, - onDrag = this::onMarkerDrag, - ), - ) - } - - /** - * グラウンドイメージの外周をなぞる矩形。 - * - * NE → NW → SW → SE → NE の順に 5 点で閉じる。SW / NE の 2 点だけでは - * **画像がどこまで載っているのかが見えない**ので、ドラッグで範囲を変えたときの - * 手応えを出すために引いている。react-sdk の `GroundImagePage.tsx` と同じ構成。 - * - * `points` を差し替えるだけで再描画されるので、インスタンスは作り直さない - * (作り直すとドラッグ中に id が変わってちらつく)。 - */ - override val framePolyline: PolylineState = - PolylineState( - id = "groundimage-frame", - points = framePoints(southWestPosition, northEastPosition), - strokeColor = Color.White, - strokeWidth = 3.dp, - clickable = false, - ) - - override var opacity by mutableStateOf(1.0f) - - override var image by mutableStateOf(imageResources.image) - - private var bounds by mutableStateOf( - GeoRectBounds( - southWest = southWestPosition, - northEast = northEastPosition, - ), - ) - - override val groundImageState - get() = - GroundImageState( - id = "groundImage", - bounds = bounds, - image = image, - opacity = opacity, - onClick = this::onGroundImageClick, - ) - - override fun onGroundImageClick(clicked: GroundImageEvent) { - showToast("Ground image clicked.") - } - - override fun onMarkerDrag(dragged: MarkerState) { - // Update the internal position based on which marker was dragged - when (dragged.id) { - "south_west" -> southWestPosition = GeoPoint.from(dragged.position) - "north_east" -> northEastPosition = GeoPoint.from(dragged.position) - } - - // Update bounds using the new positions - bounds = - GeoRectBounds().also { - it.extend(markers[0].position) - it.extend(markers[1].position) - } - - framePolyline.points = framePoints(southWestPosition, northEastPosition) - } - - override fun showToast(text: String) { - this._messages.value = this._messages.value + ToastMessage(text = text) - } - - override fun removeToast(toastMessage: ToastMessage) { - this._messages.value = this._messages.value.filter { it != toastMessage } - } - - override fun onCleared() { - super.onCleared() - } -} - -/** - * 2 つの角から矩形の 4 辺をなぞる点列を作る。NE → NW → SW → SE → NE で閉じる。 - * - * ドラッグで南北・東西が反転しても、常に 2 点を対角とする矩形になる。 - */ -private fun framePoints( - southWest: GeoPoint, - northEast: GeoPoint, -): List = - listOf( - northEast, - GeoPoint(latitude = northEast.latitude, longitude = southWest.longitude), - southWest, - GeoPoint(latitude = southWest.latitude, longitude = northEast.longitude), - northEast, - ) +package com.mapconductor.example.pages.groundimage + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.groundimage.GroundImageEvent +import com.mapconductor.core.groundimage.GroundImageState +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.example.toast.ToastMessage +import android.graphics.drawable.Drawable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +interface GroundImageMapPageViewModelInterface { + val initCameraPosition: MapCameraPosition + val mapViewState: StateFlow?> + val messages: StateFlow> + + val markers: List + val framePolyline: PolylineState + val imageResources: GroundImageResources + val image: Drawable + + /** 画像を Drawable でなく URL で渡す(SDK が読む)。 */ + var useImageUrl: Boolean + var opacity: Float + val groundImageState: GroundImageState + + fun onMapViewChanged(state: MapViewStateInterface<*>) + + fun onGroundImageClick(clicked: GroundImageEvent) + + fun onMarkerDrag(dragged: MarkerState) + + fun showToast(text: String) + + fun removeToast(toastMessage: ToastMessage) +} + +/** `useImageUrl` のときに貼る画像。res/drawable/university_of_eswatini.png と同じもの。 */ +private const val GROUND_IMAGE_URL = + "https://raw.githubusercontent.com/MapConductor/android-sdk/develop/example-app/src/main/res/drawable/university_of_eswatini.png" + +class GroundImageMapPageViewModel( + override val imageResources: GroundImageResources, +) : ViewModel(), + GroundImageMapPageViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + // Drone imagery over the University of Eswatini campus. Same content as + // react-sdk/examples/basic and the iOS sample. + position = + GeoPoint.fromLatLong( + latitude = -26.479235, + longitude = 31.306239, + ), + zoom = 15.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + + private val _mapViewState = MutableStateFlow?>(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + override fun onMapViewChanged(state: MapViewStateInterface<*>) { + mapViewState.value?.cameraPosition?.let { + state.moveCameraTo(it) + } + this._mapViewState.value = state + } + + private val _messages: MutableStateFlow> = MutableStateFlow(emptyList()) + override val messages: StateFlow> = _messages.asStateFlow() + + private var southWestPosition by mutableStateOf( + GeoPoint( + latitude = -26.484901389754125, + longitude = 31.2995982170105, + ), + ) + + private var northEastPosition by mutableStateOf( + GeoPoint( + latitude = -26.473569450536356, + longitude = 31.31288051605225, + ), + ) + + private fun calculateMarkerLabels(): Pair { + val swLat = southWestPosition.latitude + val swLng = southWestPosition.longitude + val neLat = northEastPosition.latitude + val neLng = northEastPosition.longitude + + val southWestLabel = + when { + swLat <= neLat && swLng <= neLng -> "SW" // Normal + swLat <= neLat && swLng > neLng -> "SE" // East-West flipped + swLat > neLat && swLng <= neLng -> "NW" // North-South flipped + else -> "NE" // Both flipped + } + + val northEastLabel = + when { + neLat >= swLat && neLng >= swLng -> "NE" // Normal + neLat >= swLat && neLng < swLng -> "NW" // East-West flipped + neLat < swLat && neLng >= swLng -> "SE" // North-South flipped + else -> "SW" // Both flipped + } + + return Pair(southWestLabel, northEastLabel) + } + + override val markers: List + get() { + val (swLabel, neLabel) = calculateMarkerLabels() + return listOf( + MarkerState( + id = "south_west", + position = southWestPosition, + icon = + DefaultMarkerIcon( + fillColor = Color.Blue, + strokeColor = Color.White, + label = swLabel, + labelTextColor = Color.White, + ), + draggable = true, + onDrag = this::onMarkerDrag, + ), + MarkerState( + id = "north_east", + position = northEastPosition, + icon = + DefaultMarkerIcon( + fillColor = Color.Red, + strokeColor = Color.White, + label = neLabel, + labelTextColor = Color.White, + ), + draggable = true, + onDrag = this::onMarkerDrag, + ), + ) + } + + /** + * グラウンドイメージの外周をなぞる矩形。 + * + * NE → NW → SW → SE → NE の順に 5 点で閉じる。SW / NE の 2 点だけでは + * **画像がどこまで載っているのかが見えない**ので、ドラッグで範囲を変えたときの + * 手応えを出すために引いている。react-sdk の `GroundImagePage.tsx` と同じ構成。 + * + * `points` を差し替えるだけで再描画されるので、インスタンスは作り直さない + * (作り直すとドラッグ中に id が変わってちらつく)。 + */ + override val framePolyline: PolylineState = + PolylineState( + id = "groundimage-frame", + points = framePoints(southWestPosition, northEastPosition), + strokeColor = Color.White, + strokeWidth = 3.dp, + clickable = false, + ) + + override var opacity by mutableStateOf(1.0f) + + override var image by mutableStateOf(imageResources.image) + + override var useImageUrl by mutableStateOf(false) + + private var bounds by mutableStateOf( + GeoRectBounds( + southWest = southWestPosition, + northEast = northEastPosition, + ), + ) + + override val groundImageState + get() = + if (useImageUrl) { + GroundImageState( + id = "groundImage", + bounds = bounds, + imageUrl = GROUND_IMAGE_URL, + opacity = opacity, + onClick = this::onGroundImageClick, + ) + } else { + GroundImageState( + id = "groundImage", + bounds = bounds, + image = image, + opacity = opacity, + onClick = this::onGroundImageClick, + ) + } + + override fun onGroundImageClick(clicked: GroundImageEvent) { + showToast("Ground image clicked.") + } + + override fun onMarkerDrag(dragged: MarkerState) { + // Update the internal position based on which marker was dragged + when (dragged.id) { + "south_west" -> southWestPosition = GeoPoint.from(dragged.position) + "north_east" -> northEastPosition = GeoPoint.from(dragged.position) + } + + // Update bounds using the new positions + bounds = + GeoRectBounds().also { + it.extend(markers[0].position) + it.extend(markers[1].position) + } + + framePolyline.points = framePoints(southWestPosition, northEastPosition) + } + + override fun showToast(text: String) { + this._messages.value = this._messages.value + ToastMessage(text = text) + } + + override fun removeToast(toastMessage: ToastMessage) { + this._messages.value = this._messages.value.filter { it != toastMessage } + } +} + +/** + * 2 つの角から矩形の 4 辺をなぞる点列を作る。NE → NW → SW → SE → NE で閉じる。 + * + * ドラッグで南北・東西が反転しても、常に 2 点を対角とする矩形になる。 + */ +private fun framePoints( + southWest: GeoPoint, + northEast: GeoPoint, +): List = + listOf( + northEast, + GeoPoint(latitude = northEast.latitude, longitude = southWest.longitude), + southWest, + GeoPoint(latitude = southWest.latitude, longitude = northEast.longitude), + northEast, + ) diff --git a/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerMapComponent.kt index 5ab3b655f..6dd3ab8f7 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerMapComponent.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerMapComponent.kt @@ -25,7 +25,7 @@ fun HeatmapLayerMapComponent( ) } } - mapViewState?.let { it -> + mapViewState?.let { MapViewContainer( modifier = modifier, state = it, diff --git a/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPage.kt index 906b13859..1c04c61a2 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPage.kt @@ -18,7 +18,10 @@ import com.mapconductor.postoffice.PostOfficeDataLoader import com.mapconductor.utils.LoadingDialog @Composable -fun HeatmapLayerPage(onToggleSidebar: () -> Unit = {}) { +fun HeatmapLayerPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val context = LocalContext.current val dataLoader = remember { PostOfficeDataLoader(context) } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPageViewModel.kt index bf5712143..a05c25935 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/heatmaplayer/HeatmapLayerPageViewModel.kt @@ -1,98 +1,94 @@ -package com.mapconductor.example.pages.heatmaplayer - -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.heatmap.HeatmapPointState -import com.mapconductor.postoffice.PostOfficeDataLoader -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -interface HeatmapLayerViewModelInterface { - val initCameraPosition: MapCameraPosition - - val points: StateFlow> - val mapViewState: StateFlow?> - val isMapLoaded: StateFlow - val isDataLoading: StateFlow - - fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) - - fun onMapLoaded(mapViewState: MapViewStateInterface<*>) - - fun loadPostOfficeData() -} - -class HeatmapLayerPageViewModel( - private val dataLoader: PostOfficeDataLoader, - private val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Default), -) : ViewModel(), - HeatmapLayerViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 35.68049, - longitude = 139.76669, - ), - zoom = 10.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - private val _points: MutableStateFlow> = MutableStateFlow(emptyList()) - override val points: StateFlow> = _points.asStateFlow() - - private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) - override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() - - private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) - override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() - - private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - private var cameraPosition: MapCameraPosition = initCameraPosition - - override fun loadPostOfficeData() { - if (_points.value.isNotEmpty()) return - - coroutine.launch { - _isDataLoading.value = true - _points.value = dataLoader.loadAllPostOffices().map { HeatmapPointState(it.position) } - _isDataLoading.value = false - } - } - - // Convenience: in case of error paths, ensure the dialog is hidden - private fun markLoadingFinished() { - if (_isDataLoading.value) { - _isDataLoading.value = false - } - } - - override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { - coroutine.launch { - _isMapLoaded.value = true - _mapViewState.value?.moveCameraTo( - cameraPosition = cameraPosition, - ) - } - } - - override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { - cameraPosition = mapViewState.cameraPosition - - _mapViewState.value = mapViewState - _isMapLoaded.value = false - } - - override fun onCleared() { - super.onCleared() - } -} +package com.mapconductor.example.pages.heatmaplayer + +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.heatmap.HeatmapPointState +import com.mapconductor.postoffice.PostOfficeDataLoader +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +interface HeatmapLayerViewModelInterface { + val initCameraPosition: MapCameraPosition + + val points: StateFlow> + val mapViewState: StateFlow?> + val isMapLoaded: StateFlow + val isDataLoading: StateFlow + + fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) + + fun onMapLoaded(mapViewState: MapViewStateInterface<*>) + + fun loadPostOfficeData() +} + +class HeatmapLayerPageViewModel( + private val dataLoader: PostOfficeDataLoader, + private val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Default), +) : ViewModel(), + HeatmapLayerViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 35.68049, + longitude = 139.76669, + ), + zoom = 10.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + private val _points: MutableStateFlow> = MutableStateFlow(emptyList()) + override val points: StateFlow> = _points.asStateFlow() + + private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) + override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() + + private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) + override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() + + private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + private var cameraPosition: MapCameraPosition = initCameraPosition + + override fun loadPostOfficeData() { + if (_points.value.isNotEmpty()) return + + coroutine.launch { + _isDataLoading.value = true + _points.value = dataLoader.loadAllPostOffices().map { HeatmapPointState(it.position) } + _isDataLoading.value = false + } + } + + // Convenience: in case of error paths, ensure the dialog is hidden + private fun markLoadingFinished() { + if (_isDataLoading.value) { + _isDataLoading.value = false + } + } + + override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { + coroutine.launch { + _isMapLoaded.value = true + _mapViewState.value?.moveCameraTo( + cameraPosition = cameraPosition, + ) + } + } + + override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { + cameraPosition = mapViewState.cameraPosition + + _mapViewState.value = mapViewState + _isMapLoaded.value = false + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/MultipleBubblesPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/MultipleBubblesPage.kt index 4cc1cbb2a..858ae91a7 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/MultipleBubblesPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/MultipleBubblesPage.kt @@ -2,7 +2,6 @@ package com.mapconductor.example.pages.infobubble import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -27,7 +26,10 @@ import com.mapconductor.example.ui.DefaultMapViewItems import com.mapconductor.example.ui.DemoMapPageScaffold @Composable -fun MultipleBubblesPage(onToggleSidebar: () -> Unit = {}) { +fun MultipleBubblesPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val initCameraPosition = MapCameraPosition( position = GeoPoint.fromLatLong(37.7749, -122.4194), @@ -72,6 +74,7 @@ fun MultipleBubblesPage(onToggleSidebar: () -> Unit = {}) { DemoMapPageScaffold( menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = { state -> @Suppress("UNCHECKED_CAST") @@ -80,7 +83,6 @@ fun MultipleBubblesPage(onToggleSidebar: () -> Unit = {}) { ) { mapViewState?.let { MapViewContainer( - modifier = Modifier.fillMaxSize(), state = mapViewState, onMapLoaded = { selectedMarkers = markerStates.map { it.id }.toSet() diff --git a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/RichContentBubblePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/RichContentBubblePage.kt index 386c7c8e7..24cd9edf8 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/RichContentBubblePage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/RichContentBubblePage.kt @@ -4,7 +4,6 @@ import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -45,7 +44,10 @@ data class LocationInfo( ) : Serializable @Composable -fun RichContentBubblePage(onToggleSidebar: () -> Unit = {}) { +fun RichContentBubblePage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val initCameraPosition = MapCameraPosition( position = GeoPoint.fromLatLong(37.7749, -122.4194), @@ -72,6 +74,7 @@ fun RichContentBubblePage(onToggleSidebar: () -> Unit = {}) { DemoMapPageScaffold( menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = { state -> @Suppress("UNCHECKED_CAST") @@ -84,7 +87,6 @@ fun RichContentBubblePage(onToggleSidebar: () -> Unit = {}) { mapViewState?.let { MapViewContainer( - modifier = Modifier.fillMaxSize(), state = mapViewState, onMapLoaded = { selectedMarker = markerState diff --git a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/SimpleTextBubblePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/SimpleTextBubblePage.kt index a51cec34b..c7a2dc84d 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/SimpleTextBubblePage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/SimpleTextBubblePage.kt @@ -1,6 +1,5 @@ package com.mapconductor.example.pages.infobubble -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -24,7 +23,10 @@ import com.mapconductor.example.ui.DefaultMapViewItems import com.mapconductor.example.ui.DemoMapPageScaffold @Composable -fun SimpleTextBubblePage(onToggleSidebar: () -> Unit = {}) { +fun SimpleTextBubblePage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val initCameraPosition = MapCameraPosition( position = GeoPoint.fromLatLong(37.7749, -122.4194), @@ -38,12 +40,13 @@ fun SimpleTextBubblePage(onToggleSidebar: () -> Unit = {}) { position = GeoPoint.fromLatLong(37.7749, -122.4194), icon = DefaultMarkerIcon(fillColor = Color.Blue, label = "SF"), extra = "San Francisco - The Golden Gate City", - onClick = { it -> selectedMarker = it }, + onClick = { selectedMarker = it }, ) } DemoMapPageScaffold( menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = { state -> @Suppress("UNCHECKED_CAST") @@ -52,7 +55,6 @@ fun SimpleTextBubblePage(onToggleSidebar: () -> Unit = {}) { ) { mapViewState?.let { MapViewContainer( - modifier = Modifier.fillMaxSize(), state = mapViewState, onMapClick = { selectedMarker = null }, onMapLoaded = { diff --git a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/StyledInfoBubblePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/StyledInfoBubblePage.kt index 7704449b4..7f770563a 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/infobubble/StyledInfoBubblePage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/infobubble/StyledInfoBubblePage.kt @@ -1,199 +1,201 @@ -package com.mapconductor.example.pages.infobubble - -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Card -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Slider -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.key -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.dp -import com.mapconductor.compose.info.InfoBubble -import com.mapconductor.compose.marker.Marker -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold - -/** - * react の StyledInfoBubblePage.tsx / ios の StyledInfoBubblePage.swift と同一仕様: - * マーカー 1 個と常時表示の InfoBubble を置き、パネルの 8 色スウォッチ 4 行 - * (バブル塗り / バブル枠線 / 文字 / マーカー)と 2 本のスライダー - * (枠線幅・マーカースケール 0.5〜2.0、0.25 刻み)でスタイルを組み替える。 - * - * palette は 4 行で共有する 8 色。白と黒を含めておくと - * 塗り=白 / 文字=黒の既定も同じ列で選べる。 - */ - -private val palette = - listOf( - Color(0xFFFFFFFF), - Color(0xFF111827), - Color(0xFFEF4444), - Color(0xFFF97316), - Color(0xFFEAB308), - Color(0xFF22C55E), - Color(0xFF3B82F6), - Color(0xFFA855F7), - ) - -private val startPosition = GeoPoint.fromLatLong(35.6812, 139.7671) - -@Composable -private fun SwatchRow( - label: String, - selected: Color, - onSelect: (Color) -> Unit, -) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - text = label, - style = MaterialTheme.typography.bodySmall, - modifier = Modifier.width(64.dp), - ) - palette.forEach { color -> - Box( - modifier = - Modifier - .padding(end = 6.dp) - .size(22.dp) - .border( - width = if (selected == color) 2.dp else 1.dp, - color = if (selected == color) Color(0xFF2563EB) else Color(0x40111827), - shape = CircleShape, - ).padding(3.dp) - .background(color, CircleShape) - .clickable { onSelect(color) }, - ) - } - } -} - -@Composable -fun StyledInfoBubblePage(onToggleSidebar: () -> Unit = {}) { - val initCameraPosition = - remember { - MapCameraPosition( - position = startPosition, - zoom = 14.0, - ) - } - var mapViewState by remember { mutableStateOf?>(null) } - - var fillColor by remember { mutableStateOf(Color(0xFFFFFFFF)) } - var strokeColor by remember { mutableStateOf(Color(0xFF111827)) } - var fontColor by remember { mutableStateOf(Color(0xFF111827)) } - var markerColor by remember { mutableStateOf(Color(0xFFEF4444)) } - var strokeWidth by remember { mutableFloatStateOf(2.0f) } - var markerScale by remember { mutableFloatStateOf(1.0f) } - - val marker = - remember { - MarkerState( - id = "styled-bubble-marker", - position = startPosition, - icon = DefaultMarkerIcon(fillColor = Color(0xFFEF4444)), - ) - } - - LaunchedEffect(markerColor, markerScale) { - marker.icon = DefaultMarkerIcon(fillColor = markerColor, scale = markerScale) - } - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(initCameraPosition), - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = { state -> - @Suppress("UNCHECKED_CAST") - mapViewState = state as MapViewStateInterface - }, - ) { paddingValues -> - mapViewState?.let { - MapViewContainer( - modifier = Modifier.fillMaxSize(), - state = mapViewState, - ) { - Marker(marker) - // InfoBubble はスタイルとマーカーアイコンを登録時に焼き込むので、 - // 変更のたびに key で登録し直して最新の見た目・配置に揃える。 - key(fillColor, strokeColor, fontColor, strokeWidth, markerScale) { - InfoBubble( - marker = marker, - bubbleColor = fillColor, - borderColor = strokeColor, - borderWidth = strokeWidth.dp, - cornerRadius = 6.dp, - contentPadding = 10.dp, - ) { - Text( - text = "Custom Styled Bubble", - color = fontColor, - style = MaterialTheme.typography.bodyMedium, - ) - } - } - } - } - - // react / ios と同じ左下配置 - Card( - modifier = - Modifier - .align(Alignment.BottomStart) - .padding( - bottom = paddingValues.calculateBottomPadding() + 16.dp, - start = 16.dp, - ), - ) { - Column(modifier = Modifier.padding(12.dp)) { - SwatchRow(label = "Fill", selected = fillColor) { fillColor = it } - SwatchRow(label = "Stroke", selected = strokeColor) { strokeColor = it } - SwatchRow(label = "Font", selected = fontColor) { fontColor = it } - SwatchRow(label = "Marker", selected = markerColor) { markerColor = it } - Text( - text = "Stroke Width: %.2f".format(strokeWidth), - style = MaterialTheme.typography.bodySmall, - ) - Slider( - value = strokeWidth, - onValueChange = { strokeWidth = it }, - valueRange = 0.5f..2.0f, - steps = 5, - ) - Text( - text = "Marker Scale: %.2f".format(markerScale), - style = MaterialTheme.typography.bodySmall, - ) - Slider( - value = markerScale, - onValueChange = { markerScale = it }, - valueRange = 0.5f..2.0f, - steps = 5, - ) - } - } - } -} +package com.mapconductor.example.pages.infobubble + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.Card +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.mapconductor.compose.info.InfoBubble +import com.mapconductor.compose.marker.Marker +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold + +/** + * react の StyledInfoBubblePage.tsx / ios の StyledInfoBubblePage.swift と同一仕様: + * マーカー 1 個と常時表示の InfoBubble を置き、パネルの 8 色スウォッチ 4 行 + * (バブル塗り / バブル枠線 / 文字 / マーカー)と 2 本のスライダー + * (枠線幅・マーカースケール 0.5〜2.0、0.25 刻み)でスタイルを組み替える。 + * + * palette は 4 行で共有する 8 色。白と黒を含めておくと + * 塗り=白 / 文字=黒の既定も同じ列で選べる。 + */ + +private val palette = + listOf( + Color(0xFFFFFFFF), + Color(0xFF111827), + Color(0xFFEF4444), + Color(0xFFF97316), + Color(0xFFEAB308), + Color(0xFF22C55E), + Color(0xFF3B82F6), + Color(0xFFA855F7), + ) + +private val startPosition = GeoPoint.fromLatLong(35.6812, 139.7671) + +@Composable +private fun SwatchRow( + label: String, + selected: Color, + onSelect: (Color) -> Unit, +) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = label, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.width(64.dp), + ) + palette.forEach { color -> + Box( + modifier = + Modifier + .padding(end = 6.dp) + .size(22.dp) + .border( + width = if (selected == color) 2.dp else 1.dp, + color = if (selected == color) Color(0xFF2563EB) else Color(0x40111827), + shape = CircleShape, + ).padding(3.dp) + .background(color, CircleShape) + .clickable { onSelect(color) }, + ) + } + } +} + +@Composable +fun StyledInfoBubblePage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val initCameraPosition = + remember { + MapCameraPosition( + position = startPosition, + zoom = 14.0, + ) + } + var mapViewState by remember { mutableStateOf?>(null) } + + var fillColor by remember { mutableStateOf(Color(0xFFFFFFFF)) } + var strokeColor by remember { mutableStateOf(Color(0xFF111827)) } + var fontColor by remember { mutableStateOf(Color(0xFF111827)) } + var markerColor by remember { mutableStateOf(Color(0xFFEF4444)) } + var strokeWidth by remember { mutableFloatStateOf(2.0f) } + var markerScale by remember { mutableFloatStateOf(1.0f) } + + val marker = + remember { + MarkerState( + id = "styled-bubble-marker", + position = startPosition, + icon = DefaultMarkerIcon(fillColor = Color(0xFFEF4444)), + ) + } + + LaunchedEffect(markerColor, markerScale) { + marker.icon = DefaultMarkerIcon(fillColor = markerColor, scale = markerScale) + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { state -> + @Suppress("UNCHECKED_CAST") + mapViewState = state as MapViewStateInterface + }, + ) { paddingValues -> + mapViewState?.let { + MapViewContainer( + state = mapViewState, + ) { + Marker(marker) + // InfoBubble はスタイルとマーカーアイコンを登録時に焼き込むので、 + // 変更のたびに key で登録し直して最新の見た目・配置に揃える。 + key(fillColor, strokeColor, fontColor, strokeWidth, markerScale) { + InfoBubble( + marker = marker, + bubbleColor = fillColor, + borderColor = strokeColor, + borderWidth = strokeWidth.dp, + cornerRadius = 6.dp, + contentPadding = 10.dp, + ) { + Text( + text = "Custom Styled Bubble", + color = fontColor, + style = MaterialTheme.typography.bodyMedium, + ) + } + } + } + } + + // react / ios と同じ左下配置 + Card( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding( + bottom = paddingValues.calculateBottomPadding() + 16.dp, + start = 16.dp, + ), + ) { + Column(modifier = Modifier.padding(12.dp)) { + SwatchRow(label = "Fill", selected = fillColor) { fillColor = it } + SwatchRow(label = "Stroke", selected = strokeColor) { strokeColor = it } + SwatchRow(label = "Font", selected = fontColor) { fontColor = it } + SwatchRow(label = "Marker", selected = markerColor) { markerColor = it } + Text( + text = "Stroke Width: %.2f".format(strokeWidth), + style = MaterialTheme.typography.bodySmall, + ) + Slider( + value = strokeWidth, + onValueChange = { strokeWidth = it }, + valueRange = 0.5f..2.0f, + steps = 5, + ) + Text( + text = "Marker Scale: %.2f".format(markerScale), + style = MaterialTheme.typography.bodySmall, + ) + Slider( + value = markerScale, + onValueChange = { markerScale = it }, + valueRange = 0.5f..2.0f, + steps = 5, + ) + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/kml/KMLMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/kml/KMLMapPage.kt index d55c2d954..d467a1f03 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/kml/KMLMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/kml/KMLMapPage.kt @@ -45,7 +45,10 @@ import kotlinx.coroutines.withContext private const val KML_ASSET = "sample.kml" @Composable -fun KMLMapPage(onToggleSidebar: () -> Unit = {}) { +fun KMLMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val initCameraPosition = remember { MapCameraPosition( @@ -57,10 +60,13 @@ fun KMLMapPage(onToggleSidebar: () -> Unit = {}) { DemoMapPageScaffold( menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = { mapViewState = it }, ) { paddingValues -> - KMLMapComponent(mapViewState = mapViewState) + KMLMapComponent( + mapViewState = mapViewState, + ) MessageCard( title = "KML Layer", @@ -79,7 +85,10 @@ fun KMLMapPage(onToggleSidebar: () -> Unit = {}) { } @Composable -private fun KMLMapComponent(mapViewState: MapViewStateInterface<*>?) { +private fun KMLMapComponent( + mapViewState: MapViewStateInterface<*>?, + modifier: Modifier = Modifier, +) { val context = LocalContext.current var selectedFeature by remember { mutableStateOf(null) } var tappedPosition by remember { mutableStateOf(null) } @@ -119,6 +128,7 @@ private fun KMLMapComponent(mapViewState: MapViewStateInterface<*>?) { mapViewState?.let { state -> MapViewContainer( state = state, + modifier = modifier, onMapClick = { clicked -> if (!layerState.processClick(clicked, pixelTolerance = 12.0, zoom = state.cameraPosition.zoom)) { tappedPosition = null diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/basic/StoreMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/basic/StoreMapPage.kt index a5dfa4c9b..a62e26d1a 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/basic/StoreMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/basic/StoreMapPage.kt @@ -3,17 +3,22 @@ package com.mapconductor.example.pages.map.basic import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import com.mapconductor.example.ui.DefaultMapViewItems import com.mapconductor.example.ui.DemoMapPageScaffold @Composable -fun StoreMapPage(onToggleSidebar: () -> Unit = {}) { +fun StoreMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel = remember { StoreMapPageViewModel() } val context = LocalContext.current DemoMapPageScaffold( menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = viewModel::onMapViewChanged, ) { @@ -23,12 +28,18 @@ fun StoreMapPage(onToggleSidebar: () -> Unit = {}) { StoreMapComponent( mapViewState = mapViewState.value, markers = viewModel.markerList, + selectedMarker = selectedMarker.value, +// mapPaddings = MapPaddings( +// top = paddings.calculateTopPadding().value.toDouble(), +// bottom = paddings.calculateBottomPadding().value.toDouble(), +// left = paddings.calculateLeftPadding(LayoutDirection.Ltr).value.toDouble(), +// right = paddings.calculateRightPadding(LayoutDirection.Ltr).value.toDouble(), +// ), onDirectionButtonClick = { state -> val intent = viewModel.onDirectionButtonClick(state) context.startActivity(intent) }, onMapClick = viewModel::onMapClick, - selectedMarker = selectedMarker.value, ) } } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/camerarestriction/CameraRestrictionMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/camerarestriction/CameraRestrictionMapPage.kt index e9276eca3..05495d349 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/camerarestriction/CameraRestrictionMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/camerarestriction/CameraRestrictionMapPage.kt @@ -78,7 +78,10 @@ private val boundsPolygon = ) @Composable -fun CameraRestrictionMapPage(onToggleSidebar: () -> Unit = {}) { +fun CameraRestrictionMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val initCameraPosition = remember { MapCameraPosition( @@ -111,6 +114,7 @@ fun CameraRestrictionMapPage(onToggleSidebar: () -> Unit = {}) { DemoMapPageScaffold( menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = { state -> mapViewState?.cameraPosition?.let { state.moveCameraTo(it) } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/camerasync/CameraSyncPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/camerasync/CameraSyncPage.kt index a6098dfe8..b955b6712 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/camerasync/CameraSyncPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/camerasync/CameraSyncPage.kt @@ -1,800 +1,825 @@ -package com.mapconductor.example.pages.map.camerasync - -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Menu -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.layout.onSizeChanged -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.IntSize -import androidx.compose.ui.unit.dp -import com.mapconductor.compose.polygon.Polygon -import com.mapconductor.compose.polyline.Polyline -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.features.GeoRectBounds -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.polygon.PolygonState -import com.mapconductor.core.polyline.PolylineState -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.IconSelectMenu -import java.util.Locale -import android.os.SystemClock -import kotlinx.coroutines.launch - -private data class CameraLocationInfo( - val name: String, - val bounds: GeoRectBounds, - val center: GeoPoint, - val zoom: Double, -) - -private enum class ActiveMapPane { - Left, - Right, -} - -@Composable -fun CameraSyncPage(onToggleSidebar: () -> Unit = {}) { - val initCameraPosition = - remember { - MapCameraPosition( - position = GeoPoint(latitude = 35.6812, longitude = 139.7671, altitude = 0.0), // Tokyo - zoom = 12.0, - bearing = 0.0, - tilt = 0.0, - ) - } - - val locations = remember { defaultLocations() } - val boundsPolylines = remember(locations) { locations.map(::boundsPolyline) } - val referenceRectangles = remember(locations) { referenceRectangles(locations) } - - val leftMenuItems = DefaultMapViewItems(initCameraPosition) - val rightMenuItems = DefaultMapViewItems(initCameraPosition) - - // Default to Google Maps vs Longdo for zoom calibration. - // 添字直書きは DefaultMapViewItems の並びが変わるたびに壊れる(実際 arcgis2d を - // 挿入したときにずれた)ので、キーで引く。 - val leftDefaultIndex = - remember(leftMenuItems) { leftMenuItems.indexOfFirst { it.key == "google" }.coerceAtLeast(0) } - val rightDefaultIndex = - remember(rightMenuItems) { rightMenuItems.indexOfFirst { it.key == "longdo" }.coerceAtLeast(0) } - var leftSelectedIndex by rememberSaveable { mutableIntStateOf(leftDefaultIndex) } - var rightSelectedIndex by rememberSaveable { mutableIntStateOf(rightDefaultIndex) } - - @Suppress("UNCHECKED_CAST") - val leftState = leftMenuItems[leftSelectedIndex].value as MapViewStateInterface<*> - - @Suppress("UNCHECKED_CAST") - val rightState = rightMenuItems[rightSelectedIndex].value as MapViewStateInterface<*> - - // Use rememberUpdatedState to ensure callbacks always reference the current state, - // not the state captured when the callback lambda was created. - val currentLeftState by rememberUpdatedState(leftState) - val currentRightState by rememberUpdatedState(rightState) - - var leftCameraPosition by remember { mutableStateOf(initCameraPosition) } - var rightCameraPosition by remember { mutableStateOf(initCameraPosition) } - val mainScope = rememberCoroutineScope() - - // Guard against feedback loops for programmatic sync: - // when we move a map by code, ignore the next camera callbacks that correspond to that same target. - var programmaticLeftKey by remember { mutableStateOf(null) } - var programmaticLeftTarget by remember { mutableStateOf(null) } - var programmaticLeftUntilMs by remember { mutableStateOf(0L) } - var programmaticLeftSinceMs by remember { mutableStateOf(0L) } - var programmaticRightKey by remember { mutableStateOf(null) } - var programmaticRightTarget by remember { mutableStateOf(null) } - var programmaticRightUntilMs by remember { mutableStateOf(0L) } - var programmaticRightSinceMs by remember { mutableStateOf(0L) } - val programmaticTtlMs = 1200L - val programmaticGraceMs = 250L - - // Move-time sync throttling to keep the UI responsive and avoid overwhelming SDKs. - var lastLeftMoveSyncAtMs by remember { mutableStateOf(0L) } - var lastRightMoveSyncAtMs by remember { mutableStateOf(0L) } - val moveSyncIntervalMs = 33L // ~30fps - - fun cameraKey(camera: MapCameraPosition): Long { - val latE5 = (camera.position.latitude * 1e5).toInt() - val lonE5 = (camera.position.longitude * 1e5).toInt() - val zoom100 = (camera.zoom * 100).toInt() - val bearing10 = (camera.bearing * 10).toInt() - return (((latE5 * 31 + lonE5) * 31 + zoom100) * 31 + bearing10).toLong() - } - - fun markProgrammaticMove( - pane: ActiveMapPane, - target: MapCameraPosition, - nowMs: Long, - ) { - val key = cameraKey(target) - when (pane) { - ActiveMapPane.Left -> { - programmaticLeftKey = key - programmaticLeftTarget = target - programmaticLeftSinceMs = nowMs - programmaticLeftUntilMs = nowMs + programmaticTtlMs - } - ActiveMapPane.Right -> { - programmaticRightKey = key - programmaticRightTarget = target - programmaticRightSinceMs = nowMs - programmaticRightUntilMs = nowMs + programmaticTtlMs - } - } - } - - fun clearProgrammaticMove(pane: ActiveMapPane) { - when (pane) { - ActiveMapPane.Left -> { - programmaticLeftKey = null - programmaticLeftTarget = null - programmaticLeftSinceMs = 0L - programmaticLeftUntilMs = 0L - } - ActiveMapPane.Right -> { - programmaticRightKey = null - programmaticRightTarget = null - programmaticRightSinceMs = 0L - programmaticRightUntilMs = 0L - } - } - } - - fun bearingDeltaDeg( - a: Double, - b: Double, - ): Double { - val d = ((a - b) % 360.0 + 360.0) % 360.0 - return if (d > 180.0) 360.0 - d else d - } - - fun isCloseToTarget( - camera: MapCameraPosition, - target: MapCameraPosition, - ): Boolean { - val dLat = kotlin.math.abs(camera.position.latitude - target.position.latitude) - val dLon = kotlin.math.abs(camera.position.longitude - target.position.longitude) - val dZoom = kotlin.math.abs(camera.zoom - target.zoom) - val dBearing = bearingDeltaDeg(camera.bearing, target.bearing) - val dTilt = kotlin.math.abs(camera.tilt - target.tilt) - - // Tolerances are intentionally a bit loose: different SDKs can't represent the exact same camera. - return dLat < 0.0012 && dLon < 0.0012 && dZoom < 0.75 && dBearing < 12.0 && dTilt < 6.0 - } - - fun isProgrammaticMove( - pane: ActiveMapPane, - camera: MapCameraPosition, - nowMs: Long, - ): Boolean { - val (key, target, until) = - when (pane) { - ActiveMapPane.Left -> Triple(programmaticLeftKey, programmaticLeftTarget, programmaticLeftUntilMs) - ActiveMapPane.Right -> Triple(programmaticRightKey, programmaticRightTarget, programmaticRightUntilMs) - } - val k = key ?: return false - if (nowMs > until) return false - if (cameraKey(camera) == k) return true - return target?.let { isCloseToTarget(camera, it) } ?: false - } - - Scaffold { paddingValues -> - Column(modifier = Modifier.fillMaxSize().padding(paddingValues)) { - Card( - modifier = Modifier.fillMaxWidth().padding(10.dp), - elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), - ) { - Row( - modifier = Modifier.padding(16.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Icon( - imageVector = Icons.Default.Menu, - contentDescription = "Toggle sidebar", - modifier = - Modifier - .clickable(onClick = onToggleSidebar) - .size(32.dp) - .padding(end = 4.dp), - tint = MaterialTheme.colorScheme.onSurface, - ) - - Text( - text = "Camera Sync", - style = MaterialTheme.typography.titleMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - - @OptIn(ExperimentalLayoutApi::class) - FlowRow( - modifier = - Modifier - .fillMaxWidth() - .padding(horizontal = 10.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - maxLines = 2, - ) { - locations.forEach { location -> - Button( - onClick = { - val now = SystemClock.uptimeMillis() - val position = - MapCameraPosition( - position = location.center, - zoom = location.zoom, - bearing = 0.0, - tilt = 0.0, - ) - currentLeftState.moveCameraTo(position, durationMillis = 1000) - currentRightState.moveCameraTo(position, durationMillis = 1000) - leftCameraPosition = position - rightCameraPosition = position - // Both maps will emit camera callbacks; treat them as programmatic during the animation. - markProgrammaticMove(ActiveMapPane.Left, position, now) - markProgrammaticMove(ActiveMapPane.Right, position, now) - programmaticLeftUntilMs = now + 1000L + programmaticTtlMs - programmaticRightUntilMs = now + 1000L + programmaticTtlMs - }, - ) { - Text(text = location.name, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - } - } - - HorizontalDivider(modifier = Modifier.padding(top = 10.dp)) - - BoxWithConstraints(modifier = Modifier.fillMaxSize()) { - val stackVertically = maxHeight > maxWidth - - if (stackVertically) { - Column(modifier = Modifier.fillMaxSize()) { - CameraSyncMapPane( - modifier = Modifier.weight(1f).fillMaxWidth(), - menuContent = { - IconSelectMenu( - itemList = leftMenuItems, - selectedIndex = leftSelectedIndex, - onSelect = { index, _ -> leftSelectedIndex = index }, - ) - }, - mapViewState = leftState, - providerKey = leftMenuItems[leftSelectedIndex].key, - label = "Source Camera", - cameraPosition = leftCameraPosition, - onCameraMove = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - // Ignore feedback from programmatic moves (but stop ignoring if the user deviates). - if (programmaticLeftKey != null) { - if (now > programmaticLeftUntilMs) { - clearProgrammaticMove(ActiveMapPane.Left) - } else { - val age = now - programmaticLeftSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Left, position, now) - ) { - leftCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Left) - } - } - - if (now - lastLeftMoveSyncAtMs < moveSyncIntervalMs) return@launch - lastLeftMoveSyncAtMs = now - - leftCameraPosition = position - rightCameraPosition = position - markProgrammaticMove(ActiveMapPane.Right, position, now) - currentRightState.moveCameraTo(position, durationMillis = 0) - } - }, - onCameraMoveEnd = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticLeftKey != null) { - if (now > programmaticLeftUntilMs) { - clearProgrammaticMove(ActiveMapPane.Left) - } else { - val age = now - programmaticLeftSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Left, position, now) - ) { - leftCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Left) - } - } - leftCameraPosition = position - rightCameraPosition = position - markProgrammaticMove(ActiveMapPane.Right, position, now) - currentRightState.moveCameraTo(position, durationMillis = 0) - } - }, - boundsPolylines = boundsPolylines, - referenceRectangles = referenceRectangles, - ) - - Box( - modifier = - Modifier - .fillMaxWidth() - .height(1.dp) - .background(MaterialTheme.colorScheme.outline), - ) - - CameraSyncMapPane( - modifier = Modifier.weight(1f).fillMaxWidth(), - menuContent = { - IconSelectMenu( - itemList = rightMenuItems, - selectedIndex = rightSelectedIndex, - onSelect = { index, _ -> rightSelectedIndex = index }, - ) - }, - mapViewState = rightState, - providerKey = rightMenuItems[rightSelectedIndex].key, - label = "Synced Camera", - cameraPosition = rightCameraPosition, - onCameraMove = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticRightKey != null) { - if (now > programmaticRightUntilMs) { - clearProgrammaticMove(ActiveMapPane.Right) - } else { - val age = now - programmaticRightSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Right, position, now) - ) { - rightCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Right) - } - } - - if (now - lastRightMoveSyncAtMs < moveSyncIntervalMs) return@launch - lastRightMoveSyncAtMs = now - - rightCameraPosition = position - leftCameraPosition = position - markProgrammaticMove(ActiveMapPane.Left, position, now) - currentLeftState.moveCameraTo(position, durationMillis = 0) - } - }, - onCameraMoveEnd = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticRightKey != null) { - if (now > programmaticRightUntilMs) { - clearProgrammaticMove(ActiveMapPane.Right) - } else { - val age = now - programmaticRightSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Right, position, now) - ) { - rightCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Right) - } - } - rightCameraPosition = position - leftCameraPosition = position - markProgrammaticMove(ActiveMapPane.Left, position, now) - currentLeftState.moveCameraTo(position, durationMillis = 0) - } - }, - boundsPolylines = boundsPolylines, - referenceRectangles = referenceRectangles, - ) - } - } else { - Row(modifier = Modifier.fillMaxSize()) { - CameraSyncMapPane( - modifier = Modifier.weight(1f).fillMaxHeight(), - menuContent = { - IconSelectMenu( - itemList = leftMenuItems, - selectedIndex = leftSelectedIndex, - onSelect = { index, _ -> leftSelectedIndex = index }, - ) - }, - mapViewState = leftState, - providerKey = leftMenuItems[leftSelectedIndex].key, - label = "Source Camera", - cameraPosition = leftCameraPosition, - onCameraMove = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticLeftKey != null) { - if (now > programmaticLeftUntilMs) { - clearProgrammaticMove(ActiveMapPane.Left) - } else { - val age = now - programmaticLeftSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Left, position, now) - ) { - leftCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Left) - } - } - - if (now - lastLeftMoveSyncAtMs < moveSyncIntervalMs) return@launch - lastLeftMoveSyncAtMs = now - - leftCameraPosition = position - rightCameraPosition = position - markProgrammaticMove(ActiveMapPane.Right, position, now) - currentRightState.moveCameraTo(position, durationMillis = 0) - } - }, - onCameraMoveEnd = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticLeftKey != null) { - if (now > programmaticLeftUntilMs) { - clearProgrammaticMove(ActiveMapPane.Left) - } else { - val age = now - programmaticLeftSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Left, position, now) - ) { - leftCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Left) - } - } - leftCameraPosition = position - rightCameraPosition = position - markProgrammaticMove(ActiveMapPane.Right, position, now) - currentRightState.moveCameraTo(position, durationMillis = 0) - } - }, - boundsPolylines = boundsPolylines, - referenceRectangles = referenceRectangles, - ) - - Box( - modifier = - Modifier - .fillMaxHeight() - .width(1.dp) - .background(MaterialTheme.colorScheme.outline), - ) - - CameraSyncMapPane( - modifier = Modifier.weight(1f).fillMaxHeight(), - menuContent = { - IconSelectMenu( - itemList = rightMenuItems, - selectedIndex = rightSelectedIndex, - onSelect = { index, _ -> rightSelectedIndex = index }, - ) - }, - mapViewState = rightState, - providerKey = rightMenuItems[rightSelectedIndex].key, - label = "Synced Camera", - cameraPosition = rightCameraPosition, - onCameraMove = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticRightKey != null) { - if (now > programmaticRightUntilMs) { - clearProgrammaticMove(ActiveMapPane.Right) - } else { - val age = now - programmaticRightSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Right, position, now) - ) { - rightCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Right) - } - } - - if (now - lastRightMoveSyncAtMs < moveSyncIntervalMs) return@launch - lastRightMoveSyncAtMs = now - - rightCameraPosition = position - leftCameraPosition = position - markProgrammaticMove(ActiveMapPane.Left, position, now) - currentLeftState.moveCameraTo(position, durationMillis = 0) - } - }, - onCameraMoveEnd = { position -> - mainScope.launch { - val now = SystemClock.uptimeMillis() - if (programmaticRightKey != null) { - if (now > programmaticRightUntilMs) { - clearProgrammaticMove(ActiveMapPane.Right) - } else { - val age = now - programmaticRightSinceMs - if (age <= programmaticGraceMs || - isProgrammaticMove(ActiveMapPane.Right, position, now) - ) { - rightCameraPosition = position - return@launch - } - clearProgrammaticMove(ActiveMapPane.Right) - } - } - rightCameraPosition = position - leftCameraPosition = position - markProgrammaticMove(ActiveMapPane.Left, position, now) - currentLeftState.moveCameraTo(position, durationMillis = 0) - } - }, - boundsPolylines = boundsPolylines, - referenceRectangles = referenceRectangles, - ) - } - } - } - } - } -} - -@Composable -private fun CameraSyncMapPane( - modifier: Modifier, - menuContent: (@Composable () -> Unit)? = null, - mapViewState: MapViewStateInterface<*>, - // このペインで選択中のプロバイダキー。ArcGIS は 2D / 3D が同じ状態型なので、 - // これを渡さないと ArcGIS 2D を選んでも 3D(SceneView)が描かれてしまう。 - providerKey: String, - label: String, - cameraPosition: MapCameraPosition, - onCameraMoveStart: (() -> Unit)? = null, - onCameraMove: ((MapCameraPosition) -> Unit)? = null, - onCameraMoveEnd: (MapCameraPosition) -> Unit, - boundsPolylines: List, - referenceRectangles: List, -) { - var mapSize by remember { mutableStateOf(IntSize.Zero) } - Box(modifier = modifier) { - // Base: Map (full available size). Overlays are drawn on top to maximize map area. - MapViewContainer( - modifier = Modifier.fillMaxSize().onSizeChanged { mapSize = it }, - state = mapViewState, - providerKey = providerKey, - onCameraMoveStart = { onCameraMoveStart?.invoke() }, - onCameraMove = { pos -> onCameraMove?.invoke(pos) }, - onCameraMoveEnd = onCameraMoveEnd, - ) { - boundsPolylines.forEach { Polyline(it) } - referenceRectangles.forEach { Polygon(it) } - } - - // Top overlay: SDK selector (interactive) - if (menuContent != null) { - Box( - modifier = - Modifier - .align(Alignment.TopStart) - .padding(10.dp) - .fillMaxWidth(0.72f), - ) { - menuContent() - } - } - - // Bottom overlay: camera state display (read-only) - CameraInfoCard( - modifier = - Modifier - .align(Alignment.BottomStart) - .padding(10.dp), - label = label, - position = cameraPosition, - mapSize = mapSize, - ) - } -} - -@Composable -private fun CameraInfoCard( - modifier: Modifier, - label: String, - position: MapCameraPosition, - mapSize: IntSize, -) { - val fmt = remember { Locale.US } - val density = LocalDensity.current - val widthDp = with(density) { mapSize.width.toDp().value } - val heightDp = with(density) { mapSize.height.toDp().value } - Card(modifier = modifier) { - Column(modifier = Modifier.padding(10.dp)) { - Text( - text = label, - style = MaterialTheme.typography.labelMedium, - ) - Text( - text = "Lat: ${String.format(fmt, "%.5f", position.position.latitude)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Lng: ${String.format(fmt, "%.5f", position.position.longitude)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Zoom: ${String.format(fmt, "%.2f", position.zoom)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Tilt: ${String.format(fmt, "%.1f°", position.tilt)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Bearing: ${String.format(fmt, "%.1f°", position.bearing)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Alt: ${String.format(fmt, "%.0f m", position.position.altitude)}", - style = MaterialTheme.typography.bodySmall, - ) - Text( - text = "Size: ${String.format(fmt, "%.0f × %.0f dp", widthDp, heightDp)}", - style = MaterialTheme.typography.bodySmall, - ) - } - } -} - -private fun defaultLocations(): List = - listOf( - CameraLocationInfo( - name = "Tokyo", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = 35.62, longitude = 139.70, altitude = 0.0), - northEast = GeoPoint(latitude = 35.74, longitude = 139.84, altitude = 0.0), - ), - center = GeoPoint(latitude = 35.6812, longitude = 139.7671, altitude = 0.0), - zoom = 12.0, - ), - CameraLocationInfo( - name = "French Southern and Antarctic Lands", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = -49.5, longitude = 50.0, altitude = 0.0), - northEast = GeoPoint(latitude = -37.5, longitude = 77.0, altitude = 0.0), - ), - center = GeoPoint(latitude = -43.5, longitude = 63.5, altitude = 0.0), - zoom = 4.0, - ), - CameraLocationInfo( - name = "Finland", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = 59.8, longitude = 19.1, altitude = 0.0), - northEast = GeoPoint(latitude = 70.1, longitude = 31.6, altitude = 0.0), - ), - center = GeoPoint(latitude = 64.95, longitude = 25.35, altitude = 0.0), - zoom = 5.0, - ), - CameraLocationInfo( - name = "Iceland", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = 63.3, longitude = -24.5, altitude = 0.0), - northEast = GeoPoint(latitude = 66.6, longitude = -13.5, altitude = 0.0), - ), - center = GeoPoint(latitude = 64.95, longitude = -19.0, altitude = 0.0), - zoom = 6.0, - ), - CameraLocationInfo( - name = "Kiribati", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = -11.5, longitude = -174.5, altitude = 0.0), - northEast = GeoPoint(latitude = 5.0, longitude = -147.0, altitude = 0.0), - ), - center = GeoPoint(latitude = -3.25, longitude = -160.75, altitude = 0.0), - zoom = 4.5, - ), - CameraLocationInfo( - name = "Oahu Island", - bounds = - GeoRectBounds( - southWest = GeoPoint(latitude = 21.25, longitude = -158.3, altitude = 0.0), - northEast = GeoPoint(latitude = 21.7, longitude = -157.65, altitude = 0.0), - ), - center = GeoPoint(latitude = 21.475, longitude = -157.975, altitude = 0.0), - zoom = 9.5, - ), - ) - -private fun boundsPolyline(location: CameraLocationInfo): PolylineState { - val sw = location.bounds.southWest ?: return PolylineState(points = emptyList()) - val ne = location.bounds.northEast ?: return PolylineState(points = emptyList()) - val points = - listOf( - sw, - GeoPoint(latitude = sw.latitude, longitude = ne.longitude, altitude = 0.0), - ne, - GeoPoint(latitude = ne.latitude, longitude = sw.longitude, altitude = 0.0), - sw, - ) - return PolylineState( - points = points, - strokeColor = Color.Red, - strokeWidth = 3.dp, - geodesic = true, - ) -} - -private fun referenceRectangles(locations: List): List { - val size = 1.0 // approx 100km at equator - return locations.mapIndexed { index, location -> - val lat = location.center.latitude - val lng = location.center.longitude - val points = - listOf( - GeoPoint(latitude = lat - size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), - GeoPoint(latitude = lat - size / 2.0, longitude = lng + size / 2.0, altitude = 0.0), - GeoPoint(latitude = lat + size / 2.0, longitude = lng + size / 2.0, altitude = 0.0), - GeoPoint(latitude = lat + size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), - GeoPoint(latitude = lat - size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), - ) - PolygonState( - points = points, - id = "camera_sync_reference_$index", - strokeColor = Color.Blue, - strokeWidth = 2.dp, - fillColor = Color.Blue.copy(alpha = 0.1f), - geodesic = false, - zIndex = 1, - ) - } -} +package com.mapconductor.example.pages.map.camerasync + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Menu +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import com.mapconductor.compose.polygon.Polygon +import com.mapconductor.compose.polyline.Polyline +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.IconSelectMenu +import java.util.Locale +import android.os.SystemClock +import kotlinx.coroutines.launch + +private data class CameraLocationInfo( + val name: String, + val bounds: GeoRectBounds, + val center: GeoPoint, + val zoom: Double, +) + +private enum class ActiveMapPane { + Left, + Right, +} + +@Composable +fun CameraSyncPage(onToggleSidebar: () -> Unit = {}) { + val initCameraPosition = + remember { + MapCameraPosition( + position = GeoPoint(latitude = 35.6812, longitude = 139.7671, altitude = 0.0), // Tokyo + zoom = 12.0, + bearing = 0.0, + tilt = 0.0, + ) + } + + val locations = remember { defaultLocations() } + val boundsPolylines = remember(locations) { locations.map(::boundsPolyline) } + val referenceRectangles = remember(locations) { referenceRectangles(locations) } + + val leftMenuItems = DefaultMapViewItems(initCameraPosition) + val rightMenuItems = DefaultMapViewItems(initCameraPosition) + + // Default to Google Maps vs Longdo for zoom calibration. + // 添字直書きは DefaultMapViewItems の並びが変わるたびに壊れる(実際 arcgis2d を + // 挿入したときにずれた)ので、キーで引く。 + val leftDefaultIndex = + remember(leftMenuItems) { leftMenuItems.indexOfFirst { it.key == "google" }.coerceAtLeast(0) } + val rightDefaultIndex = + remember(rightMenuItems) { rightMenuItems.indexOfFirst { it.key == "longdo" }.coerceAtLeast(0) } + var leftSelectedIndex by rememberSaveable { mutableIntStateOf(leftDefaultIndex) } + var rightSelectedIndex by rememberSaveable { mutableIntStateOf(rightDefaultIndex) } + + @Suppress("UNCHECKED_CAST") + val leftState = leftMenuItems[leftSelectedIndex].value as MapViewStateInterface<*> + + @Suppress("UNCHECKED_CAST") + val rightState = rightMenuItems[rightSelectedIndex].value as MapViewStateInterface<*> + + // Use rememberUpdatedState to ensure callbacks always reference the current state, + // not the state captured when the callback lambda was created. + val currentLeftState by rememberUpdatedState(leftState) + val currentRightState by rememberUpdatedState(rightState) + + var leftCameraPosition by remember { mutableStateOf(initCameraPosition) } + var rightCameraPosition by remember { mutableStateOf(initCameraPosition) } + val mainScope = rememberCoroutineScope() + + // Guard against feedback loops for programmatic sync: + // when we move a map by code, ignore the next camera callbacks that correspond to that same target. + var programmaticLeftKey by remember { mutableStateOf(null) } + var programmaticLeftTarget by remember { mutableStateOf(null) } + var programmaticLeftUntilMs by remember { mutableStateOf(0L) } + var programmaticLeftSinceMs by remember { mutableStateOf(0L) } + var programmaticRightKey by remember { mutableStateOf(null) } + var programmaticRightTarget by remember { mutableStateOf(null) } + var programmaticRightUntilMs by remember { mutableStateOf(0L) } + var programmaticRightSinceMs by remember { mutableStateOf(0L) } + val programmaticTtlMs = 1200L + val programmaticGraceMs = 250L + + // Move-time sync throttling to keep the UI responsive and avoid overwhelming SDKs. + var lastLeftMoveSyncAtMs by remember { mutableStateOf(0L) } + var lastRightMoveSyncAtMs by remember { mutableStateOf(0L) } + val moveSyncIntervalMs = 33L // ~30fps + + fun cameraKey(camera: MapCameraPosition): Long { + val latE5 = (camera.position.latitude * 1e5).toInt() + val lonE5 = (camera.position.longitude * 1e5).toInt() + val zoom100 = (camera.zoom * 100).toInt() + val bearing10 = (camera.bearing * 10).toInt() + return (((latE5 * 31 + lonE5) * 31 + zoom100) * 31 + bearing10).toLong() + } + + fun markProgrammaticMove( + pane: ActiveMapPane, + target: MapCameraPosition, + nowMs: Long, + ) { + val key = cameraKey(target) + when (pane) { + ActiveMapPane.Left -> { + programmaticLeftKey = key + programmaticLeftTarget = target + programmaticLeftSinceMs = nowMs + programmaticLeftUntilMs = nowMs + programmaticTtlMs + } + + ActiveMapPane.Right -> { + programmaticRightKey = key + programmaticRightTarget = target + programmaticRightSinceMs = nowMs + programmaticRightUntilMs = nowMs + programmaticTtlMs + } + } + } + + fun clearProgrammaticMove(pane: ActiveMapPane) { + when (pane) { + ActiveMapPane.Left -> { + programmaticLeftKey = null + programmaticLeftTarget = null + programmaticLeftSinceMs = 0L + programmaticLeftUntilMs = 0L + } + + ActiveMapPane.Right -> { + programmaticRightKey = null + programmaticRightTarget = null + programmaticRightSinceMs = 0L + programmaticRightUntilMs = 0L + } + } + } + + fun bearingDeltaDeg( + a: Double, + b: Double, + ): Double { + val d = ((a - b) % 360.0 + 360.0) % 360.0 + return if (d > 180.0) 360.0 - d else d + } + + fun isCloseToTarget( + camera: MapCameraPosition, + target: MapCameraPosition, + ): Boolean { + val dLat = kotlin.math.abs(camera.position.latitude - target.position.latitude) + val dLon = kotlin.math.abs(camera.position.longitude - target.position.longitude) + val dZoom = kotlin.math.abs(camera.zoom - target.zoom) + val dBearing = bearingDeltaDeg(camera.bearing, target.bearing) + val dTilt = kotlin.math.abs(camera.tilt - target.tilt) + + // Tolerances are intentionally a bit loose: different SDKs can't represent the exact same camera. + return dLat < 0.0012 && dLon < 0.0012 && dZoom < 0.75 && dBearing < 12.0 && dTilt < 6.0 + } + + fun isProgrammaticMove( + pane: ActiveMapPane, + camera: MapCameraPosition, + nowMs: Long, + ): Boolean { + val (key, target, until) = + when (pane) { + ActiveMapPane.Left -> Triple(programmaticLeftKey, programmaticLeftTarget, programmaticLeftUntilMs) + ActiveMapPane.Right -> Triple(programmaticRightKey, programmaticRightTarget, programmaticRightUntilMs) + } + val k = key ?: return false + if (nowMs > until) return false + if (cameraKey(camera) == k) return true + return target?.let { isCloseToTarget(camera, it) } ?: false + } + + Scaffold { paddingValues -> + Column( + modifier = + Modifier + .fillMaxSize() + .padding(paddingValues), + ) { + Card( + modifier = + Modifier + .fillMaxWidth() + .padding(10.dp), + elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), + ) { + Row( + modifier = Modifier.padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Icon( + imageVector = Icons.Default.Menu, + contentDescription = "Toggle sidebar", + modifier = + Modifier + .clickable(onClick = onToggleSidebar) + .size(32.dp) + .padding(end = 4.dp), + tint = MaterialTheme.colorScheme.onSurface, + ) + + Text( + text = "Camera Sync", + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + + @OptIn(ExperimentalLayoutApi::class) + FlowRow( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 10.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + maxLines = 2, + ) { + locations.forEach { location -> + Button( + onClick = { + val now = SystemClock.uptimeMillis() + val position = + MapCameraPosition( + position = location.center, + zoom = location.zoom, + bearing = 0.0, + tilt = 0.0, + ) + currentLeftState.moveCameraTo(position, durationMillis = 1000) + currentRightState.moveCameraTo(position, durationMillis = 1000) + leftCameraPosition = position + rightCameraPosition = position + // Both maps will emit camera callbacks; treat them as programmatic during the animation. + markProgrammaticMove(ActiveMapPane.Left, position, now) + markProgrammaticMove(ActiveMapPane.Right, position, now) + programmaticLeftUntilMs = now + 1000L + programmaticTtlMs + programmaticRightUntilMs = now + 1000L + programmaticTtlMs + }, + ) { + Text(text = location.name, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } + + HorizontalDivider(modifier = Modifier.padding(top = 10.dp)) + + BoxWithConstraints(modifier = Modifier.fillMaxSize()) { + val stackVertically = maxHeight > maxWidth + + if (stackVertically) { + Column(modifier = Modifier.fillMaxSize()) { + CameraSyncMapPane( + modifier = + Modifier + .weight(1f) + .fillMaxWidth(), + menuContent = { + IconSelectMenu( + itemList = leftMenuItems, + selectedIndex = leftSelectedIndex, + onSelect = { index, _ -> leftSelectedIndex = index }, + ) + }, + mapViewState = leftState, + providerKey = leftMenuItems[leftSelectedIndex].key, + label = "Source Camera", + cameraPosition = leftCameraPosition, + onCameraMove = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + // Ignore feedback from programmatic moves (but stop ignoring if the user deviates). + if (programmaticLeftKey != null) { + if (now > programmaticLeftUntilMs) { + clearProgrammaticMove(ActiveMapPane.Left) + } else { + val age = now - programmaticLeftSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Left, position, now) + ) { + leftCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Left) + } + } + + if (now - lastLeftMoveSyncAtMs < moveSyncIntervalMs) return@launch + lastLeftMoveSyncAtMs = now + + leftCameraPosition = position + rightCameraPosition = position + markProgrammaticMove(ActiveMapPane.Right, position, now) + currentRightState.moveCameraTo(position, durationMillis = 0) + } + }, + onCameraMoveEnd = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticLeftKey != null) { + if (now > programmaticLeftUntilMs) { + clearProgrammaticMove(ActiveMapPane.Left) + } else { + val age = now - programmaticLeftSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Left, position, now) + ) { + leftCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Left) + } + } + leftCameraPosition = position + rightCameraPosition = position + markProgrammaticMove(ActiveMapPane.Right, position, now) + currentRightState.moveCameraTo(position, durationMillis = 0) + } + }, + boundsPolylines = boundsPolylines, + referenceRectangles = referenceRectangles, + ) + + Box( + modifier = + Modifier + .fillMaxWidth() + .height(1.dp) + .background(MaterialTheme.colorScheme.outline), + ) + + CameraSyncMapPane( + modifier = + Modifier + .weight(1f) + .fillMaxWidth(), + menuContent = { + IconSelectMenu( + itemList = rightMenuItems, + selectedIndex = rightSelectedIndex, + onSelect = { index, _ -> rightSelectedIndex = index }, + ) + }, + mapViewState = rightState, + providerKey = rightMenuItems[rightSelectedIndex].key, + label = "Synced Camera", + cameraPosition = rightCameraPosition, + onCameraMove = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticRightKey != null) { + if (now > programmaticRightUntilMs) { + clearProgrammaticMove(ActiveMapPane.Right) + } else { + val age = now - programmaticRightSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Right, position, now) + ) { + rightCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Right) + } + } + + if (now - lastRightMoveSyncAtMs < moveSyncIntervalMs) return@launch + lastRightMoveSyncAtMs = now + + rightCameraPosition = position + leftCameraPosition = position + markProgrammaticMove(ActiveMapPane.Left, position, now) + currentLeftState.moveCameraTo(position, durationMillis = 0) + } + }, + onCameraMoveEnd = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticRightKey != null) { + if (now > programmaticRightUntilMs) { + clearProgrammaticMove(ActiveMapPane.Right) + } else { + val age = now - programmaticRightSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Right, position, now) + ) { + rightCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Right) + } + } + rightCameraPosition = position + leftCameraPosition = position + markProgrammaticMove(ActiveMapPane.Left, position, now) + currentLeftState.moveCameraTo(position, durationMillis = 0) + } + }, + boundsPolylines = boundsPolylines, + referenceRectangles = referenceRectangles, + ) + } + } else { + Row(modifier = Modifier.fillMaxSize()) { + CameraSyncMapPane( + modifier = + Modifier + .weight(1f) + .fillMaxHeight(), + menuContent = { + IconSelectMenu( + itemList = leftMenuItems, + selectedIndex = leftSelectedIndex, + onSelect = { index, _ -> leftSelectedIndex = index }, + ) + }, + mapViewState = leftState, + providerKey = leftMenuItems[leftSelectedIndex].key, + label = "Source Camera", + cameraPosition = leftCameraPosition, + onCameraMove = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticLeftKey != null) { + if (now > programmaticLeftUntilMs) { + clearProgrammaticMove(ActiveMapPane.Left) + } else { + val age = now - programmaticLeftSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Left, position, now) + ) { + leftCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Left) + } + } + + if (now - lastLeftMoveSyncAtMs < moveSyncIntervalMs) return@launch + lastLeftMoveSyncAtMs = now + + leftCameraPosition = position + rightCameraPosition = position + markProgrammaticMove(ActiveMapPane.Right, position, now) + currentRightState.moveCameraTo(position, durationMillis = 0) + } + }, + onCameraMoveEnd = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticLeftKey != null) { + if (now > programmaticLeftUntilMs) { + clearProgrammaticMove(ActiveMapPane.Left) + } else { + val age = now - programmaticLeftSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Left, position, now) + ) { + leftCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Left) + } + } + leftCameraPosition = position + rightCameraPosition = position + markProgrammaticMove(ActiveMapPane.Right, position, now) + currentRightState.moveCameraTo(position, durationMillis = 0) + } + }, + boundsPolylines = boundsPolylines, + referenceRectangles = referenceRectangles, + ) + + Box( + modifier = + Modifier + .fillMaxHeight() + .width(1.dp) + .background(MaterialTheme.colorScheme.outline), + ) + + CameraSyncMapPane( + modifier = + Modifier + .weight(1f) + .fillMaxHeight(), + menuContent = { + IconSelectMenu( + itemList = rightMenuItems, + selectedIndex = rightSelectedIndex, + onSelect = { index, _ -> rightSelectedIndex = index }, + ) + }, + mapViewState = rightState, + providerKey = rightMenuItems[rightSelectedIndex].key, + label = "Synced Camera", + cameraPosition = rightCameraPosition, + onCameraMove = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticRightKey != null) { + if (now > programmaticRightUntilMs) { + clearProgrammaticMove(ActiveMapPane.Right) + } else { + val age = now - programmaticRightSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Right, position, now) + ) { + rightCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Right) + } + } + + if (now - lastRightMoveSyncAtMs < moveSyncIntervalMs) return@launch + lastRightMoveSyncAtMs = now + + rightCameraPosition = position + leftCameraPosition = position + markProgrammaticMove(ActiveMapPane.Left, position, now) + currentLeftState.moveCameraTo(position, durationMillis = 0) + } + }, + onCameraMoveEnd = { position -> + mainScope.launch { + val now = SystemClock.uptimeMillis() + if (programmaticRightKey != null) { + if (now > programmaticRightUntilMs) { + clearProgrammaticMove(ActiveMapPane.Right) + } else { + val age = now - programmaticRightSinceMs + if (age <= programmaticGraceMs || + isProgrammaticMove(ActiveMapPane.Right, position, now) + ) { + rightCameraPosition = position + return@launch + } + clearProgrammaticMove(ActiveMapPane.Right) + } + } + rightCameraPosition = position + leftCameraPosition = position + markProgrammaticMove(ActiveMapPane.Left, position, now) + currentLeftState.moveCameraTo(position, durationMillis = 0) + } + }, + boundsPolylines = boundsPolylines, + referenceRectangles = referenceRectangles, + ) + } + } + } + } + } +} + +@Composable +private fun CameraSyncMapPane( + modifier: Modifier, + menuContent: (@Composable () -> Unit)? = null, + mapViewState: MapViewStateInterface<*>, + // このペインで選択中のプロバイダキー。ArcGIS は 2D / 3D が同じ状態型なので、 + // これを渡さないと ArcGIS 2D を選んでも 3D(SceneView)が描かれてしまう。 + providerKey: String, + label: String, + cameraPosition: MapCameraPosition, + onCameraMoveStart: (() -> Unit)? = null, + onCameraMove: ((MapCameraPosition) -> Unit)? = null, + onCameraMoveEnd: (MapCameraPosition) -> Unit, + boundsPolylines: List, + referenceRectangles: List, +) { + var mapSize by remember { mutableStateOf(IntSize.Zero) } + Box(modifier = modifier) { + // Base: Map (full available size). Overlays are drawn on top to maximize map area. + MapViewContainer( + modifier = + Modifier + .fillMaxSize() + .onSizeChanged { mapSize = it }, + state = mapViewState, + providerKey = providerKey, + onCameraMoveStart = { onCameraMoveStart?.invoke() }, + onCameraMove = { pos -> onCameraMove?.invoke(pos) }, + onCameraMoveEnd = onCameraMoveEnd, + ) { + boundsPolylines.forEach { Polyline(it) } + referenceRectangles.forEach { Polygon(it) } + } + + // Top overlay: SDK selector (interactive) + if (menuContent != null) { + Box( + modifier = + Modifier + .align(Alignment.TopStart) + .padding(10.dp) + .fillMaxWidth(0.72f), + ) { + menuContent() + } + } + + // Bottom overlay: camera state display (read-only) + CameraInfoCard( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding(10.dp), + label = label, + position = cameraPosition, + mapSize = mapSize, + ) + } +} + +@Composable +private fun CameraInfoCard( + modifier: Modifier, + label: String, + position: MapCameraPosition, + mapSize: IntSize, +) { + val fmt = remember { Locale.US } + val density = LocalDensity.current + val widthDp = with(density) { mapSize.width.toDp().value } + val heightDp = with(density) { mapSize.height.toDp().value } + Card(modifier = modifier) { + Column(modifier = Modifier.padding(10.dp)) { + Text( + text = label, + style = MaterialTheme.typography.labelMedium, + ) + Text( + text = "Lat: ${String.format(fmt, "%.5f", position.position.latitude)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Lng: ${String.format(fmt, "%.5f", position.position.longitude)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Zoom: ${String.format(fmt, "%.2f", position.zoom)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Tilt: ${String.format(fmt, "%.1f°", position.tilt)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Bearing: ${String.format(fmt, "%.1f°", position.bearing)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Alt: ${String.format(fmt, "%.0f m", position.position.altitude)}", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "Size: ${String.format(fmt, "%.0f × %.0f dp", widthDp, heightDp)}", + style = MaterialTheme.typography.bodySmall, + ) + } + } +} + +private fun defaultLocations(): List = + listOf( + CameraLocationInfo( + name = "Tokyo", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = 35.62, longitude = 139.70, altitude = 0.0), + northEast = GeoPoint(latitude = 35.74, longitude = 139.84, altitude = 0.0), + ), + center = GeoPoint(latitude = 35.6812, longitude = 139.7671, altitude = 0.0), + zoom = 12.0, + ), + CameraLocationInfo( + name = "French Southern and Antarctic Lands", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = -49.5, longitude = 50.0, altitude = 0.0), + northEast = GeoPoint(latitude = -37.5, longitude = 77.0, altitude = 0.0), + ), + center = GeoPoint(latitude = -43.5, longitude = 63.5, altitude = 0.0), + zoom = 4.0, + ), + CameraLocationInfo( + name = "Finland", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = 59.8, longitude = 19.1, altitude = 0.0), + northEast = GeoPoint(latitude = 70.1, longitude = 31.6, altitude = 0.0), + ), + center = GeoPoint(latitude = 64.95, longitude = 25.35, altitude = 0.0), + zoom = 5.0, + ), + CameraLocationInfo( + name = "Iceland", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = 63.3, longitude = -24.5, altitude = 0.0), + northEast = GeoPoint(latitude = 66.6, longitude = -13.5, altitude = 0.0), + ), + center = GeoPoint(latitude = 64.95, longitude = -19.0, altitude = 0.0), + zoom = 6.0, + ), + CameraLocationInfo( + name = "Kiribati", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = -11.5, longitude = -174.5, altitude = 0.0), + northEast = GeoPoint(latitude = 5.0, longitude = -147.0, altitude = 0.0), + ), + center = GeoPoint(latitude = -3.25, longitude = -160.75, altitude = 0.0), + zoom = 4.5, + ), + CameraLocationInfo( + name = "Oahu Island", + bounds = + GeoRectBounds( + southWest = GeoPoint(latitude = 21.25, longitude = -158.3, altitude = 0.0), + northEast = GeoPoint(latitude = 21.7, longitude = -157.65, altitude = 0.0), + ), + center = GeoPoint(latitude = 21.475, longitude = -157.975, altitude = 0.0), + zoom = 9.5, + ), + ) + +private fun boundsPolyline(location: CameraLocationInfo): PolylineState { + val sw = location.bounds.southWest ?: return PolylineState(points = emptyList()) + val ne = location.bounds.northEast ?: return PolylineState(points = emptyList()) + val points = + listOf( + sw, + GeoPoint(latitude = sw.latitude, longitude = ne.longitude, altitude = 0.0), + ne, + GeoPoint(latitude = ne.latitude, longitude = sw.longitude, altitude = 0.0), + sw, + ) + return PolylineState( + points = points, + strokeColor = Color.Red, + strokeWidth = 3.dp, + geodesic = true, + ) +} + +private fun referenceRectangles(locations: List): List { + val size = 1.0 // approx 100km at equator + return locations.mapIndexed { index, location -> + val lat = location.center.latitude + val lng = location.center.longitude + val points = + listOf( + GeoPoint(latitude = lat - size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), + GeoPoint(latitude = lat - size / 2.0, longitude = lng + size / 2.0, altitude = 0.0), + GeoPoint(latitude = lat + size / 2.0, longitude = lng + size / 2.0, altitude = 0.0), + GeoPoint(latitude = lat + size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), + GeoPoint(latitude = lat - size / 2.0, longitude = lng - size / 2.0, altitude = 0.0), + ) + PolygonState( + points = points, + id = "camera_sync_reference_$index", + strokeColor = Color.Blue, + strokeWidth = 2.dp, + fillColor = Color.Blue.copy(alpha = 0.1f), + geodesic = false, + zIndex = 1, + ) + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/design/MapDesignMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/design/MapDesignMapPage.kt index 160cf90ff..79405f911 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/design/MapDesignMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/design/MapDesignMapPage.kt @@ -45,11 +45,15 @@ import com.mapconductor.tomtom.TomTomMapViewStateInterface @OptIn(ExperimentalMaterial3Api::class) @Composable -fun MapDesignMapPage(onToggleSidebar: () -> Unit = {}) { +fun MapDesignMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel = remember { MapDesignPageViewModel() } DemoMapPageScaffold( menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = viewModel::onMapViewChanged, ) { paddingValues -> @@ -96,7 +100,7 @@ fun MapDesignTypeSelector( mutableStateOf(mapDesignOptions.firstOrNull()?.label ?: "") } - val onClick: (MapDesignOption) -> Unit = fun (mapDesignOption: MapDesignOption) { + val onClick: (MapDesignOption) -> Unit = fun(mapDesignOption: MapDesignOption) { selectedLabel = mapDesignOption.label expanded = false when (state) { @@ -104,35 +108,44 @@ fun MapDesignTypeSelector( @Suppress("UNCHECKED_CAST") state.mapDesignType = mapDesignOption.design as GoogleMapDesignType } + is HereViewStateInterface -> { @Suppress("UNCHECKED_CAST") state.mapDesignType = mapDesignOption.design as HereMapDesignType } + is ArcGISMapViewStateInterface -> { @Suppress("UNCHECKED_CAST") state.mapDesignType = mapDesignOption.design as ArcGISDesignTypeInterface } + is MapboxViewStateInterface -> { @Suppress("UNCHECKED_CAST") state.mapDesignType = mapDesignOption.design as MapboxDesignType } + is MapLibreViewStateInterface -> { @Suppress("UNCHECKED_CAST") state.mapDesignType = mapDesignOption.design as MapLibreDesign } + is TomTomMapViewStateInterface -> { @Suppress("UNCHECKED_CAST") state.mapDesignType = mapDesignOption.design as TomTomMapDesignType } + is MapTilerViewStateInterface -> { state.mapDesignType = mapDesignOption.design as MapTilerMapDesignTypeInterface } + is LongdoViewStateInterface -> { state.mapDesignType = mapDesignOption.design as LongdoMapDesignTypeInterface } + is MapplsViewStateInterface -> { state.mapDesignType = mapDesignOption.design as MapplsMapDesignTypeInterface } + else -> throw IllegalArgumentException("Not implemented yet") } } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/design/MapDesignPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/design/MapDesignPageViewModel.kt index 3b7c77ba3..cf55b2ee8 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/design/MapDesignPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/design/MapDesignPageViewModel.kt @@ -69,27 +69,35 @@ class MapDesignPageViewModel : is GoogleMapViewStateInterface -> { _mapDesignOptions.value = googleMapDesigns } + is HereViewStateInterface -> { _mapDesignOptions.value = hereMapDesigns } + is MapboxViewStateInterface -> { _mapDesignOptions.value = mapboxMapDesigns } + is ArcGISMapViewStateInterface -> { _mapDesignOptions.value = arcGISMapDesigns } + is MapLibreViewStateInterface -> { _mapDesignOptions.value = mapLibreDesigns } + is TomTomMapViewStateInterface -> { _mapDesignOptions.value = tomTomMapDesigns } + is MapTilerViewStateInterface -> { _mapDesignOptions.value = mapTilerDesigns } + is LongdoViewStateInterface -> { _mapDesignOptions.value = longdoMapDesigns } + is MapplsViewStateInterface -> { _mapDesignOptions.value = mapplsDesigns } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/fitbounds/FitBoundsMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/fitbounds/FitBoundsMapPage.kt index c6fee64a0..e00faeb36 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/fitbounds/FitBoundsMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/fitbounds/FitBoundsMapPage.kt @@ -15,11 +15,15 @@ import com.mapconductor.example.ui.DemoMapPageScaffold import com.mapconductor.example.ui.MessageCard @Composable -fun FitBoundsMapPage(onToggleSidebar: () -> Unit = {}) { +fun FitBoundsMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel: FitBoundsPageViewModelInterface = remember { FitBoundsPageViewModel() } DemoMapPageScaffold( menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = viewModel::onMapViewChanged, ) { paddingValues -> @@ -30,6 +34,7 @@ fun FitBoundsMapPage(onToggleSidebar: () -> Unit = {}) { mapViewState = mapViewState.value, marker = viewModel.marker, boundsPolygon = boundsPolygon.value, + modifier = Modifier.padding(paddingValues), ) MessageCard( diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/flyto/FlyToMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/flyto/FlyToMapPage.kt index 102819118..7da51e8da 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/flyto/FlyToMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/flyto/FlyToMapPage.kt @@ -30,12 +30,14 @@ import com.mapconductor.example.ui.MessageCard @Composable fun FlyToMapPage( icons: FlyToMapIcons, + modifier: Modifier = Modifier, onToggleSidebar: () -> Unit = {}, ) { val viewModel: FlyToPageViewModelInterface = remember { FlyToPageViewModel(icons) } DemoMapPageScaffold( menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = viewModel::onMapViewChanged, ) { paddingValues -> @@ -45,6 +47,7 @@ fun FlyToMapPage( mapViewState = mapViewState.value, polylines = viewModel.polylines, markers = viewModel.markers, + modifier = Modifier.padding(paddingValues), ) // Control Panel diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/flyto/FlyToPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/flyto/FlyToPageViewModel.kt index cc21bf509..1d8bfbc77 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/flyto/FlyToPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/flyto/FlyToPageViewModel.kt @@ -128,7 +128,8 @@ class FlyToPageViewModel( id = "honolulu_to_sydney", points = listOf(honoluluLocation, sydneyLocation), strokeColor = - Color( // lime + Color( + // lime red = 0.7f, green = 0f, blue = 0f, @@ -142,7 +143,8 @@ class FlyToPageViewModel( id = "tokyo_to_london", points = listOf(tokyoLocation, londonLocation), strokeColor = - Color( // Fuchsia + Color( + // Fuchsia red = 1.0f, green = 0f, blue = 1.0f, @@ -164,7 +166,8 @@ class FlyToPageViewModel( id = "tokyo_to_honolulu", points = listOf(tokyoLocation, honoluluLocation), strokeColor = - Color( // Neon orange + Color( + // Neon orange red = 1.0f, green = 0.35f, blue = 0.12f, @@ -178,7 +181,8 @@ class FlyToPageViewModel( id = "london_to_newyork", points = listOf(londonLocation, newYorkLocation), strokeColor = - Color( // maroon + Color( + // maroon red = 0.75f, green = 0f, blue = 0f, diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/projected/ProjectedCoordinatesPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/projected/ProjectedCoordinatesPage.kt new file mode 100644 index 000000000..5d636fece --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/projected/ProjectedCoordinatesPage.kt @@ -0,0 +1,194 @@ +package com.mapconductor.example.pages.map.projected + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.mapconductor.compose.marker.Marker +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewHolderInterface +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerAnimation +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.projection.MapCoordinateSystem +import com.mapconductor.core.spherical.Spherical +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold + +/** + * 投影座標(地図エンジンの座標系での x / y)を見るサンプル。**画面座標ではない。** + * + * `MapViewHolder.toProjectedPoint` / `fromProjectedPoint` と `coordinateSystem` を + * 使う。地図の中心と、タップした地点について、 + * + * - 地図エンジンの座標系での x / y + * - その x / y を緯度経度へ戻した値と、元の地点とのずれ(メートル) + * + * を出す。ずれが 0 に近ければ往復できている。 + * + * react-sdk / ios-sdk の同ページと同じカメラ・同じ項目にしてある。 + */ +@Composable +fun ProjectedCoordinatesPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val initCameraPosition = + MapCameraPosition( + position = GeoPoint(latitude = 35.681236, longitude = 139.767125), + zoom = 12.0, + ) + var mapViewState by remember { mutableStateOf?>(null) } + + DemoMapPageScaffold( + initSelect = 0, + menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { mapViewState = it }, + ) { + mapViewState?.let { ProjectedCoordinatesMapComponent(mapViewState = it) } + } +} + +@Composable +private fun ProjectedCoordinatesMapComponent(mapViewState: MapViewStateInterface<*>) { + var center by remember(mapViewState) { mutableStateOf(null) } + var tapped by remember(mapViewState) { mutableStateOf(null) } + // ホルダは地図が出来てから付く。読み出しを合成に任せると、付いた後に組み直しが + // 起きず(onMapLoaded の中心が初期値と同じだと state が変わらない)表示が + // 取り残されるので、地図の通知で取り直して state に持つ。 + var holder by remember(mapViewState) { mutableStateOf(mapViewState.getMapViewHolder()) } + var markers by remember(mapViewState) { mutableStateOf(emptyList()) } + + Box(modifier = Modifier.fillMaxSize()) { + MapViewContainer( + modifier = Modifier.fillMaxSize(), + state = mapViewState, + onMapLoaded = { + holder = mapViewState.getMapViewHolder() + center = mapViewState.cameraPosition.position + }, + onCameraMove = { position -> + holder = mapViewState.getMapViewHolder() + center = position.position + }, + onMapClick = { point -> + holder = mapViewState.getMapViewHolder() + tapped = point + markers = dropMarkers(point, holder) + }, + ) { + markers.forEach { Marker(it) } + } + + Card( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding(16.dp) + .widthIn(max = 380.dp), + elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text( + text = "Projected Coordinates", + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.padding(bottom = 8.dp), + ) + InfoLine("Tap the map to project the tapped point.") + InfoLine("Markers: red T = tapped, blue P = back from the projected point.") + InfoLine("Coordinate system: ${holder?.coordinateSystem?.let(::formatSystem) ?: UNAVAILABLE}") + ProjectionLines("Center", center, holder) + ProjectionLines("Tapped", tapped, holder) + } + } + } +} + +/** + * タップした地点(赤)と、その投影座標を緯度経度へ戻した地点(青・小)に落とすマーカー。 + * + * 投影と逆投影が合っていれば、青は赤のピン先に重なる。青は `iconSize` で小さくし、 + * `zIndex = 1` で赤より手前に描く(重なり順は追加した順ではなく zIndex で決まる)。 + * タップのたびに新しいマーカーにするので、Drop がそのつど再生される。 + */ +private fun dropMarkers( + tapped: GeoPointInterface, + holder: MapViewHolderInterface<*, *>?, +): List { + val back = holder?.toProjectedPoint(tapped)?.let { holder.fromProjectedPoint(it) } + return listOfNotNull( + MarkerState( + position = tapped, + icon = DefaultMarkerIcon(fillColor = Color(0xFFE53935), label = "T"), + animation = MarkerAnimation.Drop, + ), + back?.let { + MarkerState( + position = it, + icon = DefaultMarkerIcon(fillColor = Color(0xFF1E88E5), label = "P", iconSize = 28.dp), + animation = MarkerAnimation.Drop, + zIndex = 1, + ) + }, + ) +} + +/** 1 地点ぶん: 緯度経度、投影座標、戻した緯度経度と元とのずれ。 */ +@Composable +private fun ProjectionLines( + label: String, + point: GeoPointInterface?, + holder: MapViewHolderInterface<*, *>?, +) { + val projected = point?.let { holder?.toProjectedPoint(it) } + val back = projected?.let { holder?.fromProjectedPoint(it) } + InfoLine("$label: ${formatPoint(point)}") + InfoLine(" Projected: ${projected?.let { "x=%.2f, y=%.2f".format(it.x, it.y) } ?: UNAVAILABLE}") + InfoLine( + " Back: ${formatPoint(back)}" + + if (point != null && back != null) { + " (error %.3f m)".format(Spherical.computeDistanceBetween(point, back)) + } else { + "" + }, + ) +} + +@Composable +private fun InfoLine(text: String) { + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(vertical = 1.dp), + ) +} + +/** 取得できないときの表示。react / ios の同ページと揃える。 */ +private const val UNAVAILABLE = "Unavailable" + +private fun formatSystem(system: MapCoordinateSystem): String = "${system.code ?: "(engine-defined)"} (${system.unit})" + +private fun formatPoint(point: GeoPointInterface?): String = + point?.let { GeoPoint.from(it).toUrlValue(6) } ?: UNAVAILABLE diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPage.kt index 890384b57..baed617b6 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPage.kt @@ -1,197 +1,201 @@ -package com.mapconductor.example.pages.map.tilt - -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.calculateEndPadding -import androidx.compose.foundation.layout.calculateStartPadding -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.sizeIn -import androidx.compose.material3.Card -import androidx.compose.material3.Slider -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.StrokeCap -import androidx.compose.ui.graphics.drawscope.Stroke -import androidx.compose.ui.unit.LayoutDirection -import androidx.compose.ui.unit.dp -import com.mapconductor.compose.circle.Circle -import com.mapconductor.compose.marker.Marker -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold -import kotlin.math.PI -import kotlin.math.abs -import kotlin.math.tan -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch - -@Composable -fun TiltMapPage(onToggleSidebar: () -> Unit = {}) { - val coroutineScope = rememberCoroutineScope() - val debounceMs = 80L - val viewModel = remember { TiltMapPageViewModel() } - - val tilt = viewModel.tilt - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(viewModel.initCameraPosition), - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = viewModel::onMapViewChanged, - ) { paddingValues -> - val mapViewState = viewModel.mapViewState.collectAsState().value - - mapViewState?.let { - MapViewContainer( - state = mapViewState, - ) { - viewModel.anchorCircleStates.forEach { circleState -> - Circle(circleState) - } - viewModel.markerStates.forEach { markerState -> - Marker(markerState) - } - } - } - - // Message Card - Card( - modifier = - Modifier - .align(Alignment.BottomStart) - .padding( - bottom = paddingValues.calculateBottomPadding() + 16.dp, - start = paddingValues.calculateStartPadding(LayoutDirection.Ltr) + 16.dp, - end = paddingValues.calculateEndPadding(LayoutDirection.Ltr) + 16.dp, - ).sizeIn( - maxWidth = 600.dp, - ), - ) { - Column(modifier = Modifier.padding(6.dp)) { - TiltCameraDiagram( - tilt = tilt, - modifier = - Modifier - .fillMaxWidth() - .height(120.dp), - ) - Spacer(modifier = Modifier.height(6.dp)) - Row { - Text("tilt: ${"%.2f".format(tilt)}") - Slider( - value = viewModel.tilt.toFloat(), - onValueChange = { newValue -> - coroutineScope.launch { - delay(debounceMs) - viewModel.tilt = newValue.toDouble() - } - }, - onValueChangeFinished = { - }, - valueRange = -89.0f..89.0f, // スライダー範囲 - steps = 0, - ) - } - } - } - } -} - -@Composable -private fun TiltCameraDiagram( - tilt: Double, - modifier: Modifier = Modifier, -) { - Canvas(modifier = modifier) { - val width = size.width - val height = size.height - val groundY = height * 0.78f - val originX = width * 0.5f - val originY = groundY - val baseCameraY = height * 0.22f - val maxTilt = 90.0 - val tiltAbs = abs(tilt).coerceIn(0.0, maxTilt) - val tiltRad = (tiltAbs * PI / 180.0).toFloat() - val altitudePx = groundY - baseCameraY - val targetDistance = - (altitudePx * tan(tiltRad)) - .coerceAtMost(width * 0.44f) - val targetX = if (tilt < 0.0) originX - targetDistance else originX - val targetY = groundY - val cameraX = if (tilt > 0.0) originX + targetDistance else originX - val cameraY = baseCameraY - val sightEndX = - if (tilt == 0.0) { - cameraX - } else { - targetX - } - val sightEndY = targetY - - drawLine( - color = Color(0xFFE4E0EC), - start = Offset(width * 0.08f, groundY), - end = Offset(width * 0.94f, groundY), - strokeWidth = 3f, - cap = StrokeCap.Round, - ) - drawLine( - color = Color(0xFF8E879A), - start = Offset(cameraX, cameraY), - end = Offset(cameraX, groundY), - strokeWidth = 2f, - ) - drawCircle( - color = Color(0xFF5DA7FF), - radius = 8f, - center = Offset(cameraX, cameraY), - ) - drawCircle( - color = Color(0xFFFF6259), - radius = 7f, - center = Offset(targetX, targetY), - ) - drawLine( - color = Color(0xFFFFC857), - start = Offset(cameraX, cameraY), - end = Offset(sightEndX, sightEndY), - strokeWidth = 4f, - cap = StrokeCap.Round, - ) - - val cameraBody = - Path().apply { - moveTo(cameraX - 12f, cameraY - 8f) - lineTo(cameraX + 14f, cameraY - 4f) - lineTo(cameraX + 10f, cameraY + 10f) - lineTo(cameraX - 12f, cameraY + 8f) - close() - } - drawPath(cameraBody, Color(0xFF2F2A38)) - drawPath(cameraBody, Color.White.copy(alpha = 0.7f), style = Stroke(width = 1.5f)) - - drawCircle( - color = Color(0xFF8E879A), - radius = 3.5f, - center = Offset(originX, originY), - ) - drawLine( - color = Color(0xFFB8AFCA), - start = Offset(minOf(cameraX, targetX), groundY + 12f), - end = Offset(maxOf(cameraX, targetX), groundY + 12f), - strokeWidth = 2f, - cap = StrokeCap.Round, - ) - } -} +package com.mapconductor.example.pages.map.tilt + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.calculateEndPadding +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.sizeIn +import androidx.compose.material3.Card +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import com.mapconductor.compose.circle.Circle +import com.mapconductor.compose.marker.Marker +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.tan +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +@Composable +fun TiltMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val coroutineScope = rememberCoroutineScope() + val debounceMs = 80L + val viewModel = remember { TiltMapPageViewModel() } + + val tilt = viewModel.tilt + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + modifier = modifier, + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = viewModel::onMapViewChanged, + ) { paddingValues -> + val mapViewState = viewModel.mapViewState.collectAsState().value + + mapViewState?.let { + MapViewContainer( + state = mapViewState, + ) { + viewModel.anchorCircleStates.forEach { circleState -> + Circle(circleState) + } + viewModel.markerStates.forEach { markerState -> + Marker(markerState) + } + } + } + + // Message Card + Card( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding( + bottom = paddingValues.calculateBottomPadding(), + start = paddingValues.calculateStartPadding(LayoutDirection.Ltr) + 16.dp, + end = paddingValues.calculateEndPadding(LayoutDirection.Ltr) + 16.dp, + ).sizeIn( + maxWidth = 600.dp, + ), + ) { + Column(modifier = Modifier.padding(6.dp)) { + TiltCameraDiagram( + tilt = tilt, + modifier = + Modifier + .fillMaxWidth() + .height(120.dp), + ) + Spacer(modifier = Modifier.height(6.dp)) + Row { + Text("tilt: ${"%.2f".format(tilt)}") + Slider( + value = viewModel.tilt.toFloat(), + onValueChange = { newValue -> + coroutineScope.launch { + delay(debounceMs) + viewModel.tilt = newValue.toDouble() + } + }, + onValueChangeFinished = { + }, + valueRange = -89.0f..89.0f, // スライダー範囲 + steps = 0, + ) + } + } + } + } +} + +@Composable +private fun TiltCameraDiagram( + tilt: Double, + modifier: Modifier = Modifier, +) { + Canvas(modifier = modifier) { + val width = size.width + val height = size.height + val groundY = height * 0.78f + val originX = width * 0.5f + val originY = groundY + val baseCameraY = height * 0.22f + val maxTilt = 90.0 + val tiltAbs = abs(tilt).coerceIn(0.0, maxTilt) + val tiltRad = (tiltAbs * PI / 180.0).toFloat() + val altitudePx = groundY - baseCameraY + val targetDistance = + (altitudePx * tan(tiltRad)) + .coerceAtMost(width * 0.44f) + val targetX = if (tilt < 0.0) originX - targetDistance else originX + val targetY = groundY + val cameraX = if (tilt > 0.0) originX + targetDistance else originX + val cameraY = baseCameraY + val sightEndX = + if (tilt == 0.0) { + cameraX + } else { + targetX + } + val sightEndY = targetY + + drawLine( + color = Color(0xFFE4E0EC), + start = Offset(width * 0.08f, groundY), + end = Offset(width * 0.94f, groundY), + strokeWidth = 3f, + cap = StrokeCap.Round, + ) + drawLine( + color = Color(0xFF8E879A), + start = Offset(cameraX, cameraY), + end = Offset(cameraX, groundY), + strokeWidth = 2f, + ) + drawCircle( + color = Color(0xFF5DA7FF), + radius = 8f, + center = Offset(cameraX, cameraY), + ) + drawCircle( + color = Color(0xFFFF6259), + radius = 7f, + center = Offset(targetX, targetY), + ) + drawLine( + color = Color(0xFFFFC857), + start = Offset(cameraX, cameraY), + end = Offset(sightEndX, sightEndY), + strokeWidth = 4f, + cap = StrokeCap.Round, + ) + + val cameraBody = + Path().apply { + moveTo(cameraX - 12f, cameraY - 8f) + lineTo(cameraX + 14f, cameraY - 4f) + lineTo(cameraX + 10f, cameraY + 10f) + lineTo(cameraX - 12f, cameraY + 8f) + close() + } + drawPath(cameraBody, Color(0xFF2F2A38)) + drawPath(cameraBody, Color.White.copy(alpha = 0.7f), style = Stroke(width = 1.5f)) + + drawCircle( + color = Color(0xFF8E879A), + radius = 3.5f, + center = Offset(originX, originY), + ) + drawLine( + color = Color(0xFFB8AFCA), + start = Offset(minOf(cameraX, targetX), groundY + 12f), + end = Offset(maxOf(cameraX, targetX), groundY + 12f), + strokeWidth = 2f, + cap = StrokeCap.Round, + ) + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPageViewModel.kt index 30e250bf5..3a43296bb 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/tilt/TiltMapPageViewModel.kt @@ -112,7 +112,6 @@ class TiltMapPageViewModel : override var tilt: Double get(): Double = _tilt - set(angle) { if (_disableSlider.value) return _tilt = angle diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/uisettings/UISettingsMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/uisettings/UISettingsMapPage.kt index 6942b0f52..1797b04fc 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/uisettings/UISettingsMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/uisettings/UISettingsMapPage.kt @@ -1,156 +1,184 @@ -package com.mapconductor.example.pages.map.uisettings - -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.sizeIn -import androidx.compose.material3.Card -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp -import com.mapconductor.core.map.MapUISettings -import com.mapconductor.example.MapViewContainer -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold -import com.mapconductor.tomtom.TomTomMapViewState -import android.util.Log -import kotlinx.coroutines.delay - -/** - * Exercises [MapUISettings] against a live map. - * - * Four switches flip the gesture flags; after each change the page reads the - * values back off the provider's own map object and logs them under the - * `MCUISettings` tag, so a device run can be verified from logcat without having - * to touch the screen. On start it also cycles None -> Default automatically. - */ -@Composable -fun UISettingsMapPage(onToggleSidebar: () -> Unit = {}) { - val viewModel = remember { UISettingsMapPageViewModel() } - // A UI test presets the flags through an intent extra rather than tapping the - // switches, which is far more reliable than driving a Compose Switch by coordinate. - var settings by remember { - mutableStateOf( - if (com.mapconductor.example.MainActivity.gesturesExtra == "none") { - MapUISettings.None - } else { - MapUISettings.Default - }, - ) - } - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(viewModel.initCameraPosition), - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = viewModel::onMapViewChanged, - ) { paddingValues -> - val mapViewState = viewModel.mapViewState.collectAsState().value - - mapViewState?.let { state -> - state.uiSettings = settings - MapViewContainer( - state = state, - onCameraMove = { c -> - Log.i("MCCamera", "%.5f,%.5f".format(c.position.latitude, c.position.longitude)) - }, - ) - - // Read back after every change, so manual toggles are verifiable too. - androidx.compose.runtime.LaunchedEffect(settings, state) { - delay(800) - report("settings=$settings", state) - } - } - - // ios / react と同じ左下配置(react の .control-panel、ios の bottomLeading と揃える) - Card( - modifier = - Modifier - .align(Alignment.BottomStart) - .padding( - bottom = paddingValues.calculateBottomPadding() + 16.dp, - start = 16.dp, - ).sizeIn(maxWidth = 360.dp), - ) { - Column(modifier = Modifier.padding(12.dp)) { - GestureSwitch("scrollGesture", settings.scrollGesture) { - settings = settings.copy(scrollGesture = it) - } - GestureSwitch("zoomGesture", settings.zoomGesture) { - settings = settings.copy(zoomGesture = it) - } - GestureSwitch("rotateGesture", settings.rotateGesture) { - settings = settings.copy(rotateGesture = it) - } - GestureSwitch("tiltGesture", settings.tiltGesture) { - settings = settings.copy(tiltGesture = it) - } - } - } - } -} - -@Composable -private fun GestureSwitch( - label: String, - checked: Boolean, - onChange: (Boolean) -> Unit, -) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - ) { - Text(text = label, modifier = Modifier.padding(end = 12.dp)) - Switch(checked = checked, onCheckedChange = onChange) - } -} - -/** Reads the gesture flags back off the native map so logcat shows ground truth. */ -private fun report( - phase: String, - state: Any, -) { - val holder = (state as? com.mapconductor.core.map.MapViewStateInterface<*>)?.getMapViewHolder() - val map = holder?.map - val actual = - when (state) { - is TomTomMapViewState -> { - val ttMap = map as? com.tomtom.sdk.map.display.TomTomMap - if (ttMap == null) { - "map unavailable" - } else { - "scroll=${ttMap.isScrollEnabled} zoom=${ttMap.isZoomEnabled} " + - "rotate=${ttMap.isRotationEnabled} tilt=${ttMap.isTiltEnabled}" - } - } - is com.mapconductor.googlemaps.GoogleMapViewState -> { - val ui = (map as? com.google.android.gms.maps.GoogleMap)?.uiSettings - if (ui == null) { - "map unavailable" - } else { - "scroll=${ui.isScrollGesturesEnabled} zoom=${ui.isZoomGesturesEnabled} " + - "rotate=${ui.isRotateGesturesEnabled} tilt=${ui.isTiltGesturesEnabled}" - } - } - is com.mapconductor.maplibre.MapLibreViewState -> { - val ui = (map as? org.maplibre.android.maps.MapLibreMap)?.uiSettings - if (ui == null) { - "map unavailable" - } else { - "scroll=${ui.isScrollGesturesEnabled} zoom=${ui.isZoomGesturesEnabled} " + - "rotate=${ui.isRotateGesturesEnabled} tilt=${ui.isTiltGesturesEnabled}" - } - } - else -> "applied (no native reader for ${state::class.simpleName})" - } - Log.i("MCUISettings", "$phase | ${state::class.simpleName} | $actual") -} +package com.mapconductor.example.pages.map.uisettings + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.sizeIn +import androidx.compose.material3.Card +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.mapconductor.core.map.MapUISettings +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.tomtom.TomTomMapViewState +import kotlin.time.Duration.Companion.milliseconds +import android.util.Log +import kotlinx.coroutines.delay + +/** + * Exercises [MapUISettings] against a live map. + * + * Four switches flip the gesture flags; after each change the page reads the + * values back off the provider's own map object and logs them under the + * `MCUISettings` tag, so a device run can be verified from logcat without having + * to touch the screen. On start it also cycles None -> Default automatically. + */ +@Composable +fun UISettingsMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val viewModel = remember { UISettingsMapPageViewModel() } + // A UI test presets the flags through an intent extra rather than tapping the + // switches, which is far more reliable than driving a Compose Switch by coordinate. + val preset = + if (com.mapconductor.example.MainActivity.gesturesExtra == "none") { + MapUISettings.None + } else { + null + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = viewModel::onMapViewChanged, + ) { paddingValues -> + val mapViewState = viewModel.mapViewState.collectAsState().value + + mapViewState?.let { state -> + // The flags live on the map state, not in this page: rememberXxxMapViewState + // saves them, so they survive a rotation. A page-local `remember` would + // come back all-true and overwrite the restored state. + // The intent preset is applied once per state (rememberSaveable keyed by its + // id), so a rotation does not re-apply it over what the user toggled since. + var presetApplied by rememberSaveable(state.id) { mutableStateOf(false) } + LaunchedEffect(state) { + if (!presetApplied && preset != null) state.uiSettings = preset + presetApplied = true + } + MapViewContainer( + state = state, + modifier = modifier, + onCameraMove = { c -> + Log.i("MCCamera", "%.5f,%.5f".format(c.position.latitude, c.position.longitude)) + }, + ) + + // Read back after every change, so manual toggles are verifiable too. + LaunchedEffect(state.uiSettings, state) { + delay(800.milliseconds) + report("settings=${state.uiSettings}", state) + } + } + + // ios / react と同じ左下配置(react の .control-panel、ios の bottomLeading と揃える) + Card( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding( + bottom = paddingValues.calculateBottomPadding() + 16.dp, + start = 16.dp, + ).sizeIn(maxWidth = 360.dp), + ) { + Column(modifier = Modifier.padding(12.dp)) { + val state = mapViewState + val settings = state?.uiSettings ?: MapUISettings.Default + val update: (MapUISettings) -> Unit = { state?.uiSettings = it } + GestureSwitch("scrollGesture", settings.scrollGesture) { + update(settings.copy(scrollGesture = it)) + } + GestureSwitch("zoomGesture", settings.zoomGesture) { + update(settings.copy(zoomGesture = it)) + } + GestureSwitch("rotateGesture", settings.rotateGesture) { + update(settings.copy(rotateGesture = it)) + } + GestureSwitch("tiltGesture", settings.tiltGesture) { + update(settings.copy(tiltGesture = it)) + } + } + } + } +} + +@Composable +private fun GestureSwitch( + label: String, + checked: Boolean, + onChange: (Boolean) -> Unit, +) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(text = label, modifier = Modifier.padding(end = 12.dp)) + Switch(checked = checked, onCheckedChange = onChange) + } +} + +/** + * Reads the gesture flags back off the native map so logcat shows ground truth. + * + * TomTom marks `TomTomMap` as its own library group's, which is what Android + * Lint objects to. Reading a vendor's map object is the whole point here: the + * escape hatch `getMapViewHolder().map` exists so a sample can check what the + * SDK actually told the native map, and a diagnostic that trusted our own + * state instead would be worth nothing. + */ +@Suppress("RestrictedApi") +private fun report( + phase: String, + state: Any, +) { + val holder = (state as? com.mapconductor.core.map.MapViewStateInterface<*>)?.getMapViewHolder() + val map = holder?.map + val actual = + when (state) { + is TomTomMapViewState -> { + val ttMap = map as? com.tomtom.sdk.map.display.TomTomMap + if (ttMap == null) { + "map unavailable" + } else { + "scroll=${ttMap.isScrollEnabled} zoom=${ttMap.isZoomEnabled} " + + "rotate=${ttMap.isRotationEnabled} tilt=${ttMap.isTiltEnabled}" + } + } + + is com.mapconductor.googlemaps.GoogleMapViewState -> { + val ui = (map as? com.google.android.gms.maps.GoogleMap)?.uiSettings + if (ui == null) { + "map unavailable" + } else { + "scroll=${ui.isScrollGesturesEnabled} zoom=${ui.isZoomGesturesEnabled} " + + "rotate=${ui.isRotateGesturesEnabled} tilt=${ui.isTiltGesturesEnabled}" + } + } + + is com.mapconductor.maplibre.MapLibreViewState -> { + val ui = (map as? org.maplibre.android.maps.MapLibreMap)?.uiSettings + if (ui == null) { + "map unavailable" + } else { + "scroll=${ui.isScrollGesturesEnabled} zoom=${ui.isZoomGesturesEnabled} " + + "rotate=${ui.isRotateGesturesEnabled} tilt=${ui.isTiltGesturesEnabled}" + } + } + + else -> "applied (no native reader for ${state::class.simpleName})" + } + Log.i("MCUISettings", "$phase | ${state::class.simpleName} | $actual") +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/VisibleRegionPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/VisibleRegionPage.kt index 15cec41e9..f2ed81330 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/VisibleRegionPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/VisibleRegionPage.kt @@ -2,13 +2,17 @@ package com.mapconductor.example.pages.map.visibleregion import androidx.compose.runtime.Composable import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.example.ui.DefaultMapViewItems import com.mapconductor.example.ui.DemoMapPageScaffold @Composable -fun VisibleRegionPage(onToggleSidebar: () -> Unit = {}) { +fun VisibleRegionPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { // react-sdk / ios の同ページと同じカメラ。並べて数値を突き合わせるため揃えてある。 val initCameraPosition = MapCameraPosition( @@ -21,6 +25,7 @@ fun VisibleRegionPage(onToggleSidebar: () -> Unit = {}) { DemoMapPageScaffold( initSelect = 0, menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = viewModel::onMapViewStateChanged, ) { diff --git a/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/ZoomCalibrationPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/ZoomCalibrationPage.kt index 2caebdc5e..c455beca5 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/ZoomCalibrationPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/map/visibleregion/ZoomCalibrationPage.kt @@ -1,600 +1,610 @@ -package com.mapconductor.example.pages.map.visibleregion - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Slider -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.mapconductor.arcgis.ArcGISMapView -import com.mapconductor.arcgis.rememberArcGISMapViewState -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.spherical.WGS84Geodesic.computeDistanceBetween -import com.mapconductor.googlemaps.GoogleMapView -import com.mapconductor.googlemaps.rememberGoogleMapViewState -import android.annotation.SuppressLint - -@SuppressLint("DefaultLocale") -@Composable -fun ZoomCalibrationPage(onToggleSidebar: () -> Unit = {}) { - val testLocation = GeoPoint.fromLongLat(139.6917, 35.6895) // Tokyo Station - val testZoomLevels = - listOf( - 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, - 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, - 15.0, 16.0, 17.0, 18.0, 10.0, 20.0, - ) - - var currentZoomLevel by rememberSaveable { mutableStateOf(0.0) } - var googleMapResults by rememberSaveable { mutableStateOf>(emptyMap()) } - var arcgisResults by rememberSaveable { mutableStateOf>(emptyMap()) } - var measurementInProgress by remember { mutableStateOf(false) } - var measurementMessage by remember { mutableStateOf("") } - // Map view states with initial camera position - val initialCameraPosition = - MapCameraPosition( - position = testLocation, - zoom = currentZoomLevel, - bearing = 0.0, - tilt = 0.0, - ) - - val googleMapViewState = - rememberGoogleMapViewState( - cameraPosition = initialCameraPosition, - ) - val arcGisMapViewState = - rememberArcGISMapViewState( - cameraPosition = initialCameraPosition, - ) - - // Update camera positions when zoom level changes - LaunchedEffect(currentZoomLevel) { - val newCameraPosition = - MapCameraPosition( - position = testLocation, - zoom = currentZoomLevel, - bearing = 0.0, - tilt = 0.0, - ) - googleMapViewState.moveCameraTo(newCameraPosition) - arcGisMapViewState.moveCameraTo(newCameraPosition) - } - - Column( - modifier = - Modifier - .fillMaxSize() - .padding(16.dp) - .verticalScroll(rememberScrollState()), - ) { - Card( - modifier = Modifier.fillMaxWidth(), - elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), - ) { - Column( - modifier = Modifier.padding(16.dp), - ) { - Text( - text = "Zoom Level Calibration Tool", - fontSize = 20.sp, - fontWeight = FontWeight.Bold, - ) - - Spacer(modifier = Modifier.height(8.dp)) - - Text( - text = "Location: Tokyo Station (35.6895°N, 139.6917°E)", - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - Spacer(modifier = Modifier.height(16.dp)) - - Text( - text = "Current Zoom Level: ${String.format("%.1f", currentZoomLevel)}", - fontSize = 16.sp, - fontWeight = FontWeight.Medium, - ) - - Slider( - value = currentZoomLevel.toFloat(), - onValueChange = { currentZoomLevel = it.toDouble() }, - valueRange = 0f..20f, - steps = 19, - modifier = Modifier.fillMaxWidth(), - ) - } - } - - Spacer(modifier = Modifier.height(16.dp)) - - // Map views section - Text( - text = "Live Map Comparison (Zoom: ${String.format("%.1f", currentZoomLevel)})", - fontSize = 16.sp, - fontWeight = FontWeight.Medium, - modifier = Modifier.padding(bottom = 8.dp), - ) - - Row( - modifier = - Modifier - .fillMaxWidth() - .height(280.dp), - ) { - Column( - modifier = Modifier.weight(1.5f), - ) { - Text( - text = "Google Maps", - fontSize = 14.sp, - fontWeight = FontWeight.Medium, - modifier = Modifier.padding(bottom = 4.dp), - ) - GoogleMapView( - state = googleMapViewState, - modifier = Modifier.fillMaxSize(), - ) - } - - Spacer(modifier = Modifier.width(16.dp)) - - Column( - modifier = Modifier.weight(1.5f), - ) { - Text( - text = "ArcGIS", - fontSize = 14.sp, - fontWeight = FontWeight.Medium, - modifier = Modifier.padding(bottom = 4.dp), - ) - ArcGISMapView( - state = arcGisMapViewState, - modifier = Modifier.fillMaxSize(), - ) - } - } - - Spacer(modifier = Modifier.height(16.dp)) - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Button( - onClick = { - // Extract visible region data from Google Maps view - googleMapViewState.cameraPosition.visibleRegion?.let { visibleRegion -> - val info = createVisibleRegionInfo(visibleRegion) - googleMapResults = googleMapResults + (currentZoomLevel to info) - measurementMessage = - String.format("Google Maps data captured: %.2f, %.2f km", info.widthKm, info.heightKm) - measurementInProgress = true - } ?: run { - measurementMessage = - "Google Maps visible region not available yet. Please wait for map to load." - measurementInProgress = true - } - }, - enabled = !measurementInProgress, - modifier = Modifier.weight(1f), - ) { - Text("Capture Google Maps") - } - - Button( - onClick = { - // Extract visible region data from ArcGIS view - arcGisMapViewState.cameraPosition.visibleRegion?.let { visibleRegion -> - val info = createVisibleRegionInfo(visibleRegion) - arcgisResults = arcgisResults + (currentZoomLevel to info) - measurementMessage = - "ArcGIS data captured: ${String.format("%.2f", info.widthKm)} × ${String.format("%.2f", info.heightKm)} km" - measurementInProgress = true - } ?: run { - measurementMessage = "ArcGIS visible region not available yet. Please wait for map to load." - measurementInProgress = true - } - }, - enabled = !measurementInProgress, - modifier = Modifier.weight(1f), - ) { - Text("Capture ArcGIS") - } - } - - Spacer(modifier = Modifier.height(16.dp)) - - CalibrationResultsTable( - testZoomLevels = testZoomLevels, - googleMapResults = googleMapResults, - arcgisResults = arcgisResults, - ) - - Spacer(modifier = Modifier.height(16.dp)) - - CalibrationRecommendations( - googleMapResults = googleMapResults, - arcgisResults = arcgisResults, - ) - - // Clear all data button - if (googleMapResults.isNotEmpty() || arcgisResults.isNotEmpty()) { - Spacer(modifier = Modifier.height(16.dp)) - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.Center, - ) { - OutlinedButton( - onClick = { - googleMapResults = emptyMap() - arcgisResults = emptyMap() - measurementMessage = "All calibration data cleared" - measurementInProgress = true - }, - ) { - Text("Clear All Data") - } - } - } - - // Instructions for better calibration - Spacer(modifier = Modifier.height(16.dp)) - - Card( - colors = - CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), - ) { - Column( - modifier = Modifier.padding(16.dp), - ) { - Text( - text = "Calibration Instructions", - fontSize = 16.sp, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - Spacer(modifier = Modifier.height(8.dp)) - - Text( - text = - "• Adjust zoom level with the slider above\n" + - "• Wait for both maps to load completely\n" + - "• Tap 'Capture' buttons to automatically extract visible region data\n" + - "• Collect data for multiple zoom levels to improve accuracy\n" + - "• Compare the results in the table below", - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - lineHeight = 20.sp, - ) - } - } - - if (measurementInProgress && measurementMessage.isNotEmpty()) { - Spacer(modifier = Modifier.height(16.dp)) - Card( - colors = - CardDefaults.cardColors( - containerColor = - if (measurementMessage.contains("captured")) { - MaterialTheme.colorScheme.primaryContainer - } else { - MaterialTheme.colorScheme.errorContainer - }, - ), - ) { - Text( - text = measurementMessage, - modifier = Modifier.padding(16.dp), - color = - if (measurementMessage.contains("captured")) { - MaterialTheme.colorScheme.onPrimaryContainer - } else { - MaterialTheme.colorScheme.onErrorContainer - }, - ) - - Row( - modifier = - Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), - horizontalArrangement = Arrangement.End, - ) { - TextButton( - onClick = { - measurementInProgress = false - measurementMessage = "" - }, - ) { - Text("OK") - } - } - } - } - - // Auto-dismiss successful measurements after 3 seconds - LaunchedEffect(measurementMessage) { - if (measurementMessage.contains("captured")) { - kotlinx.coroutines.delay(3000) - measurementInProgress = false - measurementMessage = "" - } - } - } -} - -@Composable -fun CalibrationResultsTable( - testZoomLevels: List, - googleMapResults: Map, - arcgisResults: Map, -) { - Card( - modifier = Modifier.fillMaxWidth(), - elevation = CardDefaults.cardElevation(defaultElevation = 4.dp), - ) { - Column( - modifier = Modifier.padding(16.dp), - ) { - Text( - text = "Calibration Results", - fontSize = 18.sp, - fontWeight = FontWeight.Bold, - ) - - Spacer(modifier = Modifier.height(12.dp)) - - // Table headers - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text("Zoom", fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) - Text("Google Maps (km)", fontWeight = FontWeight.Bold, modifier = Modifier.weight(2f)) - Text("ArcGIS (km)", fontWeight = FontWeight.Bold, modifier = Modifier.weight(2f)) - Text("Ratio", fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) - } - - HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) - - testZoomLevels.forEach { zoomLevel -> - val googleData = googleMapResults[zoomLevel] - val arcgisData = arcgisResults[zoomLevel] - val ratio = - if (googleData != null && arcgisData != null) { - val googleArea = googleData.widthKm * googleData.heightKm - val arcgisArea = arcgisData.widthKm * arcgisData.heightKm - if (arcgisArea > 0) googleArea / arcgisArea else 0.0 - } else { - null - } - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text( - text = String.format("%.1f", zoomLevel), - fontFamily = FontFamily.Monospace, - modifier = Modifier.weight(1f), - ) - Text( - text = - googleData?.let { - "${String.format("%.1f", it.widthKm)} × ${String.format("%.1f", it.heightKm)}" - } - ?: "-", - fontFamily = FontFamily.Monospace, - modifier = Modifier.weight(2f), - ) - Text( - text = - arcgisData?.let { - "${String.format("%.1f", it.widthKm)} × ${String.format("%.1f", it.heightKm)}" - } - ?: "-", - fontFamily = FontFamily.Monospace, - modifier = Modifier.weight(2f), - ) - Text( - text = ratio?.let { String.format("%.2f", it) } ?: "-", - fontFamily = FontFamily.Monospace, - modifier = Modifier.weight(1f), - ) - } - } - } - } -} - -@Composable -fun CalibrationRecommendations( - googleMapResults: Map, - arcgisResults: Map, -) { - if (googleMapResults.isEmpty() || arcgisResults.isEmpty()) return - - val averageRatio = calculateAverageRatio(googleMapResults, arcgisResults) - val currentZoom0Altitude = 198_506_928.2 // Use current value from ZoomAltitudeConverter - val recommendedZoom0Altitude = currentZoom0Altitude / averageRatio // Invert the ratio! - - Card( - modifier = Modifier.fillMaxWidth(), - colors = - CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.primaryContainer, - ), - ) { - Column( - modifier = Modifier.padding(16.dp), - ) { - Text( - text = "Calibration Recommendations", - fontSize = 18.sp, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onPrimaryContainer, - ) - - Spacer(modifier = Modifier.height(12.dp)) - - Text( - text = "Average Area Ratio (ArcGIS/Google): ${String.format("%.3f", averageRatio)}", - fontFamily = FontFamily.Monospace, - ) - - Text( - text = - if (averageRatio > 1.0) { - "ArcGIS shows ${String.format("%.1f", (averageRatio - 1.0) * 100)}% larger area (zoom too low)" - } else { - "ArcGIS shows ${String.format("%.1f", (1.0 - averageRatio) * 100)}% smaller area (zoom too high)" - }, - fontSize = 12.sp, - color = MaterialTheme.colorScheme.onPrimaryContainer, - ) - - Text( - text = "Current DEFAULT_ZOOM0_ALTITUDE: ${String.format("%.0f", currentZoom0Altitude)}", - fontFamily = FontFamily.Monospace, - ) - - Text( - text = "Recommended DEFAULT_ZOOM0_ALTITUDE: ${String.format("%.0f", recommendedZoom0Altitude)}", - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary, - ) - - Spacer(modifier = Modifier.height(8.dp)) - - val percentChange = ((recommendedZoom0Altitude - currentZoom0Altitude) / currentZoom0Altitude) * 100 - Text( - text = "Change: ${if (percentChange > 0) "+" else ""}${String.format("%.1f", percentChange)}%", - fontWeight = FontWeight.Medium, - ) - - Spacer(modifier = Modifier.height(12.dp)) - - Card( - colors = - CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surface, - ), - ) { - Column( - modifier = Modifier.padding(12.dp), - ) { - Text( - text = "Code to Update:", - fontWeight = FontWeight.Bold, - fontSize = 14.sp, - ) - - Spacer(modifier = Modifier.height(8.dp)) - - Text( - text = "const val DEFAULT_ZOOM0_ALTITUDE = ${String.format("%.1f", recommendedZoom0Altitude)}", - fontFamily = FontFamily.Monospace, - fontSize = 12.sp, - color = MaterialTheme.colorScheme.primary, - ) - - Text( - text = "// Location: ZoomAltitudeConverter.kt", - fontFamily = FontFamily.Monospace, - fontSize = 10.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } - } -} - -private fun calculateAverageRatio( - googleMapResults: Map, - arcgisResults: Map, -): Double { - val ratios = mutableListOf() - - googleMapResults.forEach { (zoomLevel, googleData) -> - arcgisResults[zoomLevel]?.let { arcgisData -> - val googleArea = googleData.widthKm * googleData.heightKm - val arcgisArea = arcgisData.widthKm * arcgisData.heightKm - if (arcgisArea > 0 && googleArea > 0) { - // Calculate the ratio of ArcGIS area to Google area - // If ArcGIS shows larger area, ratio > 1.0 (zoom conversion too low) - // If ArcGIS shows smaller area, ratio < 1.0 (zoom conversion too high) - val areaRatio = arcgisArea / googleArea - ratios.add(areaRatio) - } - } - } - - return if (ratios.isEmpty()) 1.0 else ratios.average() -} - -/** - * 表示領域の実寸(km)。ズーム較正はプロバイダ間で「同じズームのときの見えている - * 広さ」を比べるページなので、必要なのは幅と高さだけ。 - * - * 以前は表示領域サンプルと共有していたが、あちらを react と同じ「数値を並べるだけ」の - * 形に揃えた際に使わなくなったので、唯一の利用者であるここへ移した。 - */ -data class VisibleRegionInfo( - val widthKm: Double, - val heightKm: Double, -) - -private fun createVisibleRegionInfo(visibleRegion: com.mapconductor.core.map.VisibleRegion): VisibleRegionInfo { - val bounds = visibleRegion.bounds - if (bounds.isEmpty || bounds.southWest == null || bounds.northEast == null) { - return VisibleRegionInfo(widthKm = 0.0, heightKm = 0.0) - } - - val widthKm = - computeDistanceBetween( - bounds.southWest!!, - GeoPoint(bounds.southWest!!.latitude, bounds.northEast!!.longitude), - ) - val heightKm = - computeDistanceBetween( - bounds.southWest!!, - GeoPoint(bounds.northEast!!.latitude, bounds.southWest!!.longitude), - ) - - return VisibleRegionInfo(widthKm = widthKm, heightKm = heightKm) -} +package com.mapconductor.example.pages.map.visibleregion + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.arcgis.ArcGISMapView +import com.mapconductor.arcgis.rememberArcGISMapViewState +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.spherical.WGS84Geodesic.computeDistanceBetween +import com.mapconductor.googlemaps.GoogleMapView +import com.mapconductor.googlemaps.rememberGoogleMapViewState +import android.annotation.SuppressLint + +@SuppressLint("DefaultLocale") +@Composable +fun ZoomCalibrationPage(onToggleSidebar: () -> Unit = {}) { + val testLocation = GeoPoint.fromLongLat(139.6917, 35.6895) // Tokyo Station + val testZoomLevels = + listOf( + 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, + 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, + 15.0, 16.0, 17.0, 18.0, 10.0, 20.0, + ) + + var currentZoomLevel by rememberSaveable { mutableStateOf(0.0) } + var googleMapResults by rememberSaveable { mutableStateOf>(emptyMap()) } + var arcgisResults by rememberSaveable { mutableStateOf>(emptyMap()) } + var measurementInProgress by remember { mutableStateOf(false) } + var measurementMessage by remember { mutableStateOf("") } + // Map view states with initial camera position + val initialCameraPosition = + MapCameraPosition( + position = testLocation, + zoom = currentZoomLevel, + bearing = 0.0, + tilt = 0.0, + ) + + val googleMapViewState = + rememberGoogleMapViewState( + cameraPosition = initialCameraPosition, + ) + val arcGisMapViewState = + rememberArcGISMapViewState( + cameraPosition = initialCameraPosition, + ) + + // Update camera positions when zoom level changes + LaunchedEffect(currentZoomLevel) { + val newCameraPosition = + MapCameraPosition( + position = testLocation, + zoom = currentZoomLevel, + bearing = 0.0, + tilt = 0.0, + ) + googleMapViewState.moveCameraTo(newCameraPosition) + arcGisMapViewState.moveCameraTo(newCameraPosition) + } + + Column( + modifier = + Modifier + .fillMaxSize() + .padding(16.dp) + .verticalScroll(rememberScrollState()), + ) { + Card( + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(defaultElevation = 8.dp), + ) { + Column( + modifier = Modifier.padding(16.dp), + ) { + Text( + text = "Zoom Level Calibration Tool", + fontSize = 20.sp, + fontWeight = FontWeight.Bold, + ) + + Spacer(modifier = Modifier.height(8.dp)) + + Text( + text = "Location: Tokyo Station (35.6895°N, 139.6917°E)", + fontSize = 14.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Spacer(modifier = Modifier.height(16.dp)) + + Text( + text = "Current Zoom Level: ${String.format("%.1f", currentZoomLevel)}", + fontSize = 16.sp, + fontWeight = FontWeight.Medium, + ) + + Slider( + value = currentZoomLevel.toFloat(), + onValueChange = { currentZoomLevel = it.toDouble() }, + valueRange = 0f..20f, + steps = 19, + modifier = Modifier.fillMaxWidth(), + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + // Map views section + Text( + text = "Live Map Comparison (Zoom: ${String.format("%.1f", currentZoomLevel)})", + fontSize = 16.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(bottom = 8.dp), + ) + + Row( + modifier = + Modifier + .fillMaxWidth() + .height(280.dp), + ) { + Column( + modifier = Modifier.weight(1.5f), + ) { + Text( + text = "Google Maps", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(bottom = 4.dp), + ) + GoogleMapView( + state = googleMapViewState, + modifier = Modifier.fillMaxSize(), + ) + } + + Spacer(modifier = Modifier.width(16.dp)) + + Column( + modifier = Modifier.weight(1.5f), + ) { + Text( + text = "ArcGIS", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(bottom = 4.dp), + ) + ArcGISMapView( + state = arcGisMapViewState, + modifier = Modifier.fillMaxSize(), + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button( + onClick = { + // Extract visible region data from Google Maps view + googleMapViewState.cameraPosition.visibleRegion?.let { visibleRegion -> + val info = createVisibleRegionInfo(visibleRegion) + googleMapResults = googleMapResults + (currentZoomLevel to info) + measurementMessage = + String.format("Google Maps data captured: %.2f, %.2f km", info.widthKm, info.heightKm) + measurementInProgress = true + } ?: run { + measurementMessage = + "Google Maps visible region not available yet. Please wait for map to load." + measurementInProgress = true + } + }, + enabled = !measurementInProgress, + modifier = Modifier.weight(1f), + ) { + Text("Capture Google Maps") + } + + Button( + onClick = { + // Extract visible region data from ArcGIS view + arcGisMapViewState.cameraPosition.visibleRegion?.let { visibleRegion -> + val info = createVisibleRegionInfo(visibleRegion) + arcgisResults = arcgisResults + (currentZoomLevel to info) + measurementMessage = + "ArcGIS data captured: ${String.format("%.2f", info.widthKm)} × ${ + String.format( + "%.2f", + info.heightKm, + ) + } km" + measurementInProgress = true + } ?: run { + measurementMessage = "ArcGIS visible region not available yet. Please wait for map to load." + measurementInProgress = true + } + }, + enabled = !measurementInProgress, + modifier = Modifier.weight(1f), + ) { + Text("Capture ArcGIS") + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + CalibrationResultsTable( + testZoomLevels = testZoomLevels, + googleMapResults = googleMapResults, + arcgisResults = arcgisResults, + ) + + Spacer(modifier = Modifier.height(16.dp)) + + CalibrationRecommendations( + googleMapResults = googleMapResults, + arcgisResults = arcgisResults, + ) + + // Clear all data button + if (googleMapResults.isNotEmpty() || arcgisResults.isNotEmpty()) { + Spacer(modifier = Modifier.height(16.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.Center, + ) { + OutlinedButton( + onClick = { + googleMapResults = emptyMap() + arcgisResults = emptyMap() + measurementMessage = "All calibration data cleared" + measurementInProgress = true + }, + ) { + Text("Clear All Data") + } + } + } + + // Instructions for better calibration + Spacer(modifier = Modifier.height(16.dp)) + + Card( + colors = + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column( + modifier = Modifier.padding(16.dp), + ) { + Text( + text = "Calibration Instructions", + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Spacer(modifier = Modifier.height(8.dp)) + + Text( + text = + "• Adjust zoom level with the slider above\n" + + "• Wait for both maps to load completely\n" + + "• Tap 'Capture' buttons to automatically extract visible region data\n" + + "• Collect data for multiple zoom levels to improve accuracy\n" + + "• Compare the results in the table below", + fontSize = 14.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 20.sp, + ) + } + } + + if (measurementInProgress && measurementMessage.isNotEmpty()) { + Spacer(modifier = Modifier.height(16.dp)) + Card( + colors = + CardDefaults.cardColors( + containerColor = + if (measurementMessage.contains("captured")) { + MaterialTheme.colorScheme.primaryContainer + } else { + MaterialTheme.colorScheme.errorContainer + }, + ), + ) { + Text( + text = measurementMessage, + modifier = Modifier.padding(16.dp), + color = + if (measurementMessage.contains("captured")) { + MaterialTheme.colorScheme.onPrimaryContainer + } else { + MaterialTheme.colorScheme.onErrorContainer + }, + ) + + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.End, + ) { + TextButton( + onClick = { + measurementInProgress = false + measurementMessage = "" + }, + ) { + Text("OK") + } + } + } + } + + // Auto-dismiss successful measurements after 3 seconds + LaunchedEffect(measurementMessage) { + if (measurementMessage.contains("captured")) { + kotlinx.coroutines.delay(3000) + measurementInProgress = false + measurementMessage = "" + } + } + } +} + +@Composable +fun CalibrationResultsTable( + testZoomLevels: List, + googleMapResults: Map, + arcgisResults: Map, +) { + Card( + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(defaultElevation = 4.dp), + ) { + Column( + modifier = Modifier.padding(16.dp), + ) { + Text( + text = "Calibration Results", + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + ) + + Spacer(modifier = Modifier.height(12.dp)) + + // Table headers + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text("Zoom", fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) + Text("Google Maps (km)", fontWeight = FontWeight.Bold, modifier = Modifier.weight(2f)) + Text("ArcGIS (km)", fontWeight = FontWeight.Bold, modifier = Modifier.weight(2f)) + Text("Ratio", fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) + } + + HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) + + testZoomLevels.forEach { zoomLevel -> + val googleData = googleMapResults[zoomLevel] + val arcgisData = arcgisResults[zoomLevel] + val ratio = + if (googleData != null && arcgisData != null) { + val googleArea = googleData.widthKm * googleData.heightKm + val arcgisArea = arcgisData.widthKm * arcgisData.heightKm + if (arcgisArea > 0) googleArea / arcgisArea else 0.0 + } else { + null + } + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = String.format("%.1f", zoomLevel), + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(1f), + ) + Text( + text = + googleData?.let { + "${String.format("%.1f", it.widthKm)} × ${String.format("%.1f", it.heightKm)}" + } + ?: "-", + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(2f), + ) + Text( + text = + arcgisData?.let { + "${String.format("%.1f", it.widthKm)} × ${String.format("%.1f", it.heightKm)}" + } + ?: "-", + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(2f), + ) + Text( + text = ratio?.let { String.format("%.2f", it) } ?: "-", + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(1f), + ) + } + } + } + } +} + +@Composable +fun CalibrationRecommendations( + googleMapResults: Map, + arcgisResults: Map, +) { + if (googleMapResults.isEmpty() || arcgisResults.isEmpty()) return + + val averageRatio = calculateAverageRatio(googleMapResults, arcgisResults) + val currentZoom0Altitude = 198_506_928.2 // Use current value from ZoomAltitudeConverter + val recommendedZoom0Altitude = currentZoom0Altitude / averageRatio // Invert the ratio! + + Card( + modifier = Modifier.fillMaxWidth(), + colors = + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.primaryContainer, + ), + ) { + Column( + modifier = Modifier.padding(16.dp), + ) { + Text( + text = "Calibration Recommendations", + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onPrimaryContainer, + ) + + Spacer(modifier = Modifier.height(12.dp)) + + Text( + text = "Average Area Ratio (ArcGIS/Google): ${String.format("%.3f", averageRatio)}", + fontFamily = FontFamily.Monospace, + ) + + Text( + text = + if (averageRatio > 1.0) { + "ArcGIS shows ${String.format("%.1f", (averageRatio - 1.0) * 100)}% larger area (zoom too low)" + } else { + "ArcGIS shows ${ + String.format( + "%.1f", + (1.0 - averageRatio) * 100, + ) + }% smaller area (zoom too high)" + }, + fontSize = 12.sp, + color = MaterialTheme.colorScheme.onPrimaryContainer, + ) + + Text( + text = "Current DEFAULT_ZOOM0_ALTITUDE: ${String.format("%.0f", currentZoom0Altitude)}", + fontFamily = FontFamily.Monospace, + ) + + Text( + text = "Recommended DEFAULT_ZOOM0_ALTITUDE: ${String.format("%.0f", recommendedZoom0Altitude)}", + fontFamily = FontFamily.Monospace, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary, + ) + + Spacer(modifier = Modifier.height(8.dp)) + + val percentChange = ((recommendedZoom0Altitude - currentZoom0Altitude) / currentZoom0Altitude) * 100 + Text( + text = "Change: ${if (percentChange > 0) "+" else ""}${String.format("%.1f", percentChange)}%", + fontWeight = FontWeight.Medium, + ) + + Spacer(modifier = Modifier.height(12.dp)) + + Card( + colors = + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface, + ), + ) { + Column( + modifier = Modifier.padding(12.dp), + ) { + Text( + text = "Code to Update:", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + ) + + Spacer(modifier = Modifier.height(8.dp)) + + Text( + text = "const val DEFAULT_ZOOM0_ALTITUDE = ${String.format("%.1f", recommendedZoom0Altitude)}", + fontFamily = FontFamily.Monospace, + fontSize = 12.sp, + color = MaterialTheme.colorScheme.primary, + ) + + Text( + text = "// Location: ZoomAltitudeConverter.kt", + fontFamily = FontFamily.Monospace, + fontSize = 10.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } +} + +private fun calculateAverageRatio( + googleMapResults: Map, + arcgisResults: Map, +): Double { + val ratios = mutableListOf() + + googleMapResults.forEach { (zoomLevel, googleData) -> + arcgisResults[zoomLevel]?.let { arcgisData -> + val googleArea = googleData.widthKm * googleData.heightKm + val arcgisArea = arcgisData.widthKm * arcgisData.heightKm + if (arcgisArea > 0 && googleArea > 0) { + // Calculate the ratio of ArcGIS area to Google area + // If ArcGIS shows larger area, ratio > 1.0 (zoom conversion too low) + // If ArcGIS shows smaller area, ratio < 1.0 (zoom conversion too high) + val areaRatio = arcgisArea / googleArea + ratios.add(areaRatio) + } + } + } + + return if (ratios.isEmpty()) 1.0 else ratios.average() +} + +/** + * 表示領域の実寸(km)。ズーム較正はプロバイダ間で「同じズームのときの見えている + * 広さ」を比べるページなので、必要なのは幅と高さだけ。 + * + * 以前は表示領域サンプルと共有していたが、あちらを react と同じ「数値を並べるだけ」の + * 形に揃えた際に使わなくなったので、唯一の利用者であるここへ移した。 + */ +data class VisibleRegionInfo( + val widthKm: Double, + val heightKm: Double, +) + +private fun createVisibleRegionInfo(visibleRegion: com.mapconductor.core.map.VisibleRegion): VisibleRegionInfo { + val bounds = visibleRegion.bounds + if (bounds.isEmpty || bounds.southWest == null || bounds.northEast == null) { + return VisibleRegionInfo(widthKm = 0.0, heightKm = 0.0) + } + + val widthKm = + computeDistanceBetween( + bounds.southWest!!, + GeoPoint(bounds.southWest!!.latitude, bounds.northEast!!.longitude), + ) + val heightKm = + computeDistanceBetween( + bounds.southWest!!, + GeoPoint(bounds.northEast!!.latitude, bounds.southWest!!.longitude), + ) + + return VisibleRegionInfo(widthKm = widthKm, heightKm = heightKm) +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/animation/AnimationMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/animation/AnimationMapPage.kt index 8856d22d0..e860703c8 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/animation/AnimationMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/animation/AnimationMapPage.kt @@ -21,11 +21,13 @@ import com.mapconductor.example.ui.MessageCard @Composable fun AnimationMapPage( + modifier: Modifier = Modifier, viewModel: AnimationPageViewModelInterface = AnimationPageViewModel(), onToggleSidebar: () -> Unit = {}, ) { DemoMapPageScaffold( menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = viewModel::onMapViewChanged, ) { paddingValues -> diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/icons/MarkerBasicMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/icons/MarkerBasicMapComponent.kt index 0387a929d..e1786064c 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/icons/MarkerBasicMapComponent.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/icons/MarkerBasicMapComponent.kt @@ -40,6 +40,10 @@ import android.graphics.Canvas import android.graphics.Paint import android.graphics.drawable.BitmapDrawable +/** `ImageIcon(imageUrl = …)` の見本に使う画像。example-app の assets と同じもの。 */ +private const val CLUSTER_ICON_URL = + "https://raw.githubusercontent.com/MapConductor/android-sdk/develop/example-app/src/main/assets/cluster_red.png" + @Composable fun MarkerBasicMapComponent( mapViewState: MapViewStateInterface<*>, @@ -261,6 +265,27 @@ fun MarkerBasicMapComponent( """.trimIndent(), ) } + // 画像を URL で渡す。SDK が読み、届くまでは透明(ラベルは先に出る)。 + Marker( + position = GeoPoint.fromLatLong(0.002, 0.012), + icon = + ImageIcon( + imageUrl = CLUSTER_ICON_URL, + scale = 0.6f, + label = "URL", + labelPosition = "bottom", + ), + extra = + """ + ImageIcon( + imageUrl = "https://…/cluster_red.png", + scale = 0.6f, + label = "URL", + labelPosition = "bottom", + ) + """.trimIndent(), + ) + (selected?.extra as? String)?.let { snippet -> InfoBubble( marker = selected!!, diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/icons/MarkerBasicPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/icons/MarkerBasicPage.kt index 3d541afe6..0cd42025a 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/icons/MarkerBasicPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/icons/MarkerBasicPage.kt @@ -1,6 +1,5 @@ package com.mapconductor.example.pages.marker.icons -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -14,7 +13,10 @@ import com.mapconductor.example.ui.DefaultMapViewItems import com.mapconductor.example.ui.DemoMapPageScaffold @Composable -fun MarkerBasicPage(onToggleSidebar: () -> Unit = {}) { +fun MarkerBasicPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val initCameraPosition = remember { MapCameraPosition( @@ -27,15 +29,15 @@ fun MarkerBasicPage(onToggleSidebar: () -> Unit = {}) { DemoMapPageScaffold( menuItems = DefaultMapViewItems(initCameraPosition), + modifier = modifier, onToggleSidebar = onToggleSidebar, onMapViewStateChanged = { newMapViewState -> mapViewState = newMapViewState }, - ) { paddingValues -> + ) { mapViewState?.let { MarkerBasicMapComponent( mapViewState = it, - modifier = Modifier.fillMaxSize(), ) } } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/labelposition/MarkerLabelPositionPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/labelposition/MarkerLabelPositionPage.kt new file mode 100644 index 000000000..9f6ead838 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/labelposition/MarkerLabelPositionPage.kt @@ -0,0 +1,101 @@ +package com.mapconductor.example.pages.marker.labelposition + +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontFamily +import com.mapconductor.compose.info.InfoBubble +import com.mapconductor.compose.marker.Marker +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.OnMarkerEventHandler +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold + +// 信州大学(松本キャンパス)周辺に 3 × 3 で並べ、それぞれ違う labelPosition を付ける。 +// react-sdk の marker-label-position、ios-sdk の MarkerLabelPositionMapComponent と同じ配置。 +private val CENTER = GeoPoint.fromLatLong(36.2526, 137.9828) +private const val STEP_LATITUDE = 0.004 +private const val STEP_LONGITUDE = 0.007 + +private val POSITIONS = + listOf( + listOf("left top", "center top", "right top"), + listOf("left center", "center center", "right center"), + listOf("left bottom", "center bottom", "right bottom"), + ) + +@Composable +fun MarkerLabelPositionPage(onToggleSidebar: () -> Unit = {}) { + val initCameraPosition = + MapCameraPosition( + position = CENTER, + zoom = 14.0, + ) + var selectedId by remember { mutableStateOf(null) } + var mapViewState by remember { mutableStateOf?>(null) } + val onMarkerClick: OnMarkerEventHandler = { markerState -> selectedId = markerState.id } + val markerStates = + remember { + POSITIONS.flatMapIndexed { rowIndex, row -> + row.mapIndexed { columnIndex, labelPosition -> + MarkerState( + id = labelPosition, + position = + GeoPoint.fromLatLong( + CENTER.latitude + (1 - rowIndex) * STEP_LATITUDE, + CENTER.longitude + (columnIndex - 1) * STEP_LONGITUDE, + ), + icon = + DefaultMarkerIcon( + label = if (labelPosition == "center center") "信" else "信州大学", + labelPosition = labelPosition, + debug = true, + ), + extra = labelPosition, + onClick = onMarkerClick, + ) + } + } + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { state -> + @Suppress("UNCHECKED_CAST") + mapViewState = state as MapViewStateInterface + }, + ) { + mapViewState?.let { + MapViewContainer( + state = mapViewState, + onMapClick = { selectedId = null }, + ) { + markerStates.forEach { markerState -> + Marker(markerState) + if (markerState.id == selectedId) { + InfoBubble( + marker = markerState, + bubbleColor = Color.White, + borderColor = Color.Black, + ) { + Text( + text = "labelPosition: \"${markerState.extra}\"", + fontFamily = FontFamily.Monospace, + ) + } + } + } + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeMapComponent.kt index 4d9934249..977c310b9 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeMapComponent.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeMapComponent.kt @@ -20,11 +20,11 @@ import com.mapconductor.postoffice.PostOfficeInfoView @Composable fun PostOfficeMapComponent( - modifier: Modifier = Modifier, mapViewState: MapViewStateInterface<*>, - markerTiling: MarkerTilingOptions? = null, selectedMarker: MarkerState?, + modifier: Modifier = Modifier, markers: List = emptyList(), + markerTiling: MarkerTilingOptions? = null, onMapLoaded: OnMapLoadedHandler? = null, onMapClick: OnMapEventHandler? = null, onInfoWndClick: ((PostOffice) -> Unit)? = null, diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficePage.kt index 01094fa6f..cdd71d128 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficePage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficePage.kt @@ -20,6 +20,7 @@ import com.mapconductor.utils.LoadingDialog @Composable fun PostOfficePage( postOfficeIcon: ImageIcon, + modifier: Modifier = Modifier, onToggleSidebar: () -> Unit = {}, ) { val context = LocalContext.current @@ -44,7 +45,7 @@ fun PostOfficePage( // Show loading dialog while map or data is loading; start data load once Box( - modifier = Modifier.fillMaxSize(), + modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { val selectedMarker = viewModel.selectedMarker.collectAsState().value diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeViewModel.kt index e50c9313a..fda6c6b7a 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/postoffice/PostOfficeViewModel.kt @@ -1,165 +1,161 @@ -package com.mapconductor.example.pages.marker.postoffice - -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.ImageIcon -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.marker.MarkerTilingOptions -import com.mapconductor.postoffice.PostOffice -import com.mapconductor.postoffice.PostOfficeDataLoader -import java.lang.Thread.sleep -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -interface PostOfficeViewModelInterface { - val initCameraPosition: MapCameraPosition - val selectedMarker: StateFlow - val markerList: StateFlow> - val mapViewState: StateFlow?> - val isMapLoaded: StateFlow - val isDataLoading: StateFlow - val markerTiling: MarkerTilingOptions - - fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) - - fun onMarkerClick(clicked: MarkerState) - - fun onMapClick(clicked: GeoPoint) - - fun onMapLoaded(mapViewState: MapViewStateInterface<*>) - - fun onInfoClick(postOffice: PostOffice) - - // fun loadPostOfficeData() -} - -class PostOfficeViewModel( - private val postOfficeIcon: ImageIcon, - private val dataLoader: PostOfficeDataLoader, - private val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Default), -) : ViewModel(), - PostOfficeViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 35.68049, - longitude = 139.76669, - ), - zoom = 10.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - private val _markerList: MutableStateFlow> = MutableStateFlow(emptyList()) - override val markerList: StateFlow> = _markerList.asStateFlow() - - override val markerTiling: MarkerTilingOptions = - MarkerTilingOptions.Default.copy( - iconScaleCallback = { _, zoom -> - if (zoom > 12.0) { - return@copy 1.3 - } else if (zoom > 10.0) { - return@copy 1.0 - } else if (zoom > 8.0) { - return@copy 0.8 - } else if (zoom > 5.0) { - return@copy 0.5 - } else { - return@copy 0.2 - } - }, - ) - - private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) - override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() - - private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) - override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() - - private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - private var _selectedMarker: MutableStateFlow = MutableStateFlow(null) - override val selectedMarker: StateFlow = _selectedMarker.asStateFlow() - - private var cameraPosition: MapCameraPosition = initCameraPosition - - fun loadPostOfficeData() { - if (_markerList.value.isNotEmpty()) return - - coroutine.launch { - sleep(1000) - _isDataLoading.value = true - val postOffices = dataLoader.loadAllPostOffices() - - val markerStates = - postOffices.map { it -> - MarkerState( - position = it.position, - id = it.hashCode().toString(), - icon = postOfficeIcon, - extra = it, - onClick = this@PostOfficeViewModel::onMarkerClick, - ) - } - _markerList.value = markerStates - _isDataLoading.value = false - } - } - - // Convenience: in case of error paths, ensure the dialog is hidden - private fun markLoadingFinished() { - if (_isDataLoading.value) { - _isDataLoading.value = false - } - } - - override fun onMarkerClick(clicked: MarkerState) { - this._selectedMarker.value = clicked - } - - override fun onMapClick(clicked: GeoPoint) { - this._selectedMarker.value = null - } - - override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { - coroutine.launch { - _isMapLoaded.value = true - _mapViewState.value?.moveCameraTo( - cameraPosition = cameraPosition, - ) - loadPostOfficeData() - } - } - - override fun onInfoClick(postOffice: PostOffice) { - _mapViewState.value?.moveCameraTo( - cameraPosition = - MapCameraPosition( - position = postOffice.position, - zoom = 18.0, - tilt = 30.0, - ), - durationMillis = 2000, - ) - } - - override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { - cameraPosition = mapViewState.cameraPosition - - this._selectedMarker.value = null - _mapViewState.value = mapViewState - _isMapLoaded.value = false - } - - override fun onCleared() { - super.onCleared() - } -} +package com.mapconductor.example.pages.marker.postoffice + +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.ImageIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTilingOptions +import com.mapconductor.postoffice.PostOffice +import com.mapconductor.postoffice.PostOfficeDataLoader +import java.lang.Thread.sleep +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +interface PostOfficeViewModelInterface { + val initCameraPosition: MapCameraPosition + val selectedMarker: StateFlow + val markerList: StateFlow> + val mapViewState: StateFlow?> + val isMapLoaded: StateFlow + val isDataLoading: StateFlow + val markerTiling: MarkerTilingOptions + + fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) + + fun onMarkerClick(clicked: MarkerState) + + fun onMapClick(clicked: GeoPoint) + + fun onMapLoaded(mapViewState: MapViewStateInterface<*>) + + fun onInfoClick(postOffice: PostOffice) + + // fun loadPostOfficeData() +} + +class PostOfficeViewModel( + private val postOfficeIcon: ImageIcon, + private val dataLoader: PostOfficeDataLoader, + private val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Default), +) : ViewModel(), + PostOfficeViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 35.68049, + longitude = 139.76669, + ), + zoom = 10.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + private val _markerList: MutableStateFlow> = MutableStateFlow(emptyList()) + override val markerList: StateFlow> = _markerList.asStateFlow() + + override val markerTiling: MarkerTilingOptions = + MarkerTilingOptions.Default.copy( + iconScaleCallback = { _, zoom -> + if (zoom > 12.0) { + return@copy 1.3 + } else if (zoom > 10.0) { + return@copy 1.0 + } else if (zoom > 8.0) { + return@copy 0.8 + } else if (zoom > 5.0) { + return@copy 0.5 + } else { + return@copy 0.2 + } + }, + ) + + private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) + override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() + + private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) + override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() + + private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + private var _selectedMarker: MutableStateFlow = MutableStateFlow(null) + override val selectedMarker: StateFlow = _selectedMarker.asStateFlow() + + private var cameraPosition: MapCameraPosition = initCameraPosition + + fun loadPostOfficeData() { + if (_markerList.value.isNotEmpty()) return + + coroutine.launch { + sleep(1000) + _isDataLoading.value = true + val postOffices = dataLoader.loadAllPostOffices() + + val markerStates = + postOffices.map { + MarkerState( + position = it.position, + id = it.hashCode().toString(), + icon = postOfficeIcon, + extra = it, + onClick = this@PostOfficeViewModel::onMarkerClick, + ) + } + _markerList.value = markerStates + _isDataLoading.value = false + } + } + + // Convenience: in case of error paths, ensure the dialog is hidden + private fun markLoadingFinished() { + if (_isDataLoading.value) { + _isDataLoading.value = false + } + } + + override fun onMarkerClick(clicked: MarkerState) { + this._selectedMarker.value = clicked + } + + override fun onMapClick(clicked: GeoPoint) { + this._selectedMarker.value = null + } + + override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { + coroutine.launch { + _isMapLoaded.value = true + _mapViewState.value?.moveCameraTo( + cameraPosition = cameraPosition, + ) + loadPostOfficeData() + } + } + + override fun onInfoClick(postOffice: PostOffice) { + _mapViewState.value?.moveCameraTo( + cameraPosition = + MapCameraPosition( + position = postOffice.position, + zoom = 18.0, + tilt = 30.0, + ), + durationMillis = 2000, + ) + } + + override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { + cameraPosition = mapViewState.cameraPosition + + this._selectedMarker.value = null + _mapViewState.value = mapViewState + _isMapLoaded.value = false + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapComponent.kt index 15111cd11..0bdc80780 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapComponent.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapComponent.kt @@ -20,14 +20,14 @@ import com.mapconductor.postoffice.PostOfficeInfoView @Composable fun MarkerClusterMapComponent( - modifier: Modifier = Modifier, mapViewState: MapViewStateInterface<*>, selectedMarker: MarkerState?, + modifier: Modifier = Modifier, + clusterGroupState: MarkerClusterGroupState? = null, markers: List = emptyList(), onMapLoaded: OnMapLoadedHandler? = null, onMapClick: OnMapEventHandler? = null, onInfoWndClick: ((PostOffice) -> Unit)? = null, - clusterGroupState: MarkerClusterGroupState? = null, ) { val darkTheme: Boolean = isSystemInDarkTheme() val bubbleColor by remember { diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPage.kt index 42cf4263d..1a6c73152 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPage.kt @@ -48,6 +48,7 @@ import android.graphics.Rect @Composable fun MarkerClusterMapPage( postOfficeIcon: ImageIcon, + modifier: Modifier = Modifier, onToggleSidebar: () -> Unit = {}, ) { val context = LocalContext.current @@ -115,7 +116,7 @@ fun MarkerClusterMapPage( // Show loading dialog while map or data is loading; start data load once Box( - modifier = Modifier.fillMaxSize(), + modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { val selectedMarker = viewModel.selectedMarker.collectAsState().value diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPageViewModel.kt index ea5fc2ff9..030c34718 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/postofficecluster/MarkerClusterMapPageViewModel.kt @@ -1,185 +1,179 @@ -package com.mapconductor.example.pages.marker.postofficecluster - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.ImageIcon -import com.mapconductor.core.marker.MarkerRenderingStrategyInterface -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.marker.clustering.MarkerCluster -import com.mapconductor.postoffice.PostOffice -import com.mapconductor.postoffice.PostOfficeDataLoader -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -interface MarkerClusterMapPageViewModelInterface { - val initCameraPosition: MapCameraPosition - val selectedMarker: StateFlow - val markerList: StateFlow> - val mapViewState: StateFlow?> - val isMapLoaded: StateFlow - val isDataLoading: StateFlow - - val renderingStrategy: StateFlow?> - var debugHullPolygons: Boolean - - fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) - - fun onMarkerClick(clicked: MarkerState) - - fun onMapClick(clicked: GeoPoint) - - fun onMapLoaded(mapViewState: MapViewStateInterface<*>) - - fun onInfoClick(postOffice: PostOffice) - - fun onClusterClicked(cluster: MarkerCluster) -} - -class MarkerClusterMapPageViewModel( - private val postOfficeIcon: ImageIcon, - private val dataLoader: PostOfficeDataLoader, -) : ViewModel(), - MarkerClusterMapPageViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 35.68049, - longitude = 139.76669, - ), - zoom = 10.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - private val _markerList: MutableStateFlow> = MutableStateFlow(emptyList()) - override val markerList: StateFlow> = _markerList.asStateFlow() - - private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) - override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() - - private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) - override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() - - private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - private var _selectedMarker: MutableStateFlow = MutableStateFlow(null) - override val selectedMarker: StateFlow = _selectedMarker.asStateFlow() - - private var cameraPosition: MapCameraPosition = initCameraPosition - - private val _renderingStrategy: MutableStateFlow?> = - MutableStateFlow(null) - override val renderingStrategy: StateFlow?> = _renderingStrategy.asStateFlow() - - override var debugHullPolygons by mutableStateOf(false) - - fun loadPostOfficeData() { - if (_markerList.value.isNotEmpty()) return - - viewModelScope.launch(Dispatchers.Default) { - _isDataLoading.value = true - try { - delay(1000) - val postOffices = dataLoader.loadAllPostOffices() - - val markerStates = - postOffices.map { it -> - MarkerState( - position = it.position, - id = it.hashCode().toString(), - icon = postOfficeIcon, - extra = it, - onClick = this@MarkerClusterMapPageViewModel::onMarkerClick, - ) - } - _markerList.value = markerStates - } catch (t: Throwable) { - _markerList.value = emptyList() - } finally { - _isDataLoading.value = false - } - } - } - - // Convenience: in case of error paths, ensure the dialog is hidden - private fun markLoadingFinished() { - if (_isDataLoading.value) { - _isDataLoading.value = false - } - } - - override fun onMarkerClick(clicked: MarkerState) { - this._selectedMarker.value = clicked - } - - override fun onMapClick(clicked: GeoPoint) { - this._selectedMarker.value = null - } - - override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { - viewModelScope.launch(Dispatchers.Default) { - _isMapLoaded.value = true - _mapViewState.value?.moveCameraTo( - cameraPosition = cameraPosition, - ) - loadPostOfficeData() - } - } - - override fun onInfoClick(postOffice: PostOffice) { - _mapViewState.value?.moveCameraTo( - cameraPosition = - MapCameraPosition( - position = postOffice.position, - zoom = 18.0, - tilt = 30.0, - ), - durationMillis = 2000, - ) - } - - // クラスターをクリックしたら、クラスター内マーカーの重心へズームインする(React と同じロジック)。 - override fun onClusterClicked(cluster: MarkerCluster) { - val byId = _markerList.value.associateBy { it.id } - val positions = cluster.markerIds.mapNotNull { byId[it]?.position } - if (positions.isEmpty()) return - val lat = positions.sumOf { it.latitude } / positions.size - val lng = positions.sumOf { it.longitude } / positions.size - val currentZoom = _mapViewState.value?.cameraPosition?.zoom ?: 10.0 - _mapViewState.value?.moveCameraTo( - cameraPosition = - MapCameraPosition( - position = GeoPoint.fromLatLong(lat, lng), - zoom = minOf(currentZoom + 2.0, 18.0), - ), - durationMillis = 600, - ) - } - - override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { - cameraPosition = mapViewState.cameraPosition - - renderingStrategy.value?.clear() - this._selectedMarker.value = null - _mapViewState.value = mapViewState - _isMapLoaded.value = false - } - - override fun onCleared() { - super.onCleared() - // Clean up remote strategy if it's being used -// (renderingStrategy as? RemoteSpatialMarkerStrategy<*>)?.destroy() - } -} +package com.mapconductor.example.pages.marker.postofficecluster + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.ImageIcon +import com.mapconductor.core.marker.MarkerRenderingStrategyInterface +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.marker.clustering.MarkerCluster +import com.mapconductor.postoffice.PostOffice +import com.mapconductor.postoffice.PostOfficeDataLoader +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +interface MarkerClusterMapPageViewModelInterface { + val initCameraPosition: MapCameraPosition + val selectedMarker: StateFlow + val markerList: StateFlow> + val mapViewState: StateFlow?> + val isMapLoaded: StateFlow + val isDataLoading: StateFlow + + val renderingStrategy: StateFlow?> + var debugHullPolygons: Boolean + + fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) + + fun onMarkerClick(clicked: MarkerState) + + fun onMapClick(clicked: GeoPoint) + + fun onMapLoaded(mapViewState: MapViewStateInterface<*>) + + fun onInfoClick(postOffice: PostOffice) + + fun onClusterClicked(cluster: MarkerCluster) +} + +class MarkerClusterMapPageViewModel( + private val postOfficeIcon: ImageIcon, + private val dataLoader: PostOfficeDataLoader, +) : ViewModel(), + MarkerClusterMapPageViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 35.68049, + longitude = 139.76669, + ), + zoom = 10.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + private val _markerList: MutableStateFlow> = MutableStateFlow(emptyList()) + override val markerList: StateFlow> = _markerList.asStateFlow() + + private val _isMapLoaded: MutableStateFlow = MutableStateFlow(false) + override val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() + + private val _isDataLoading: MutableStateFlow = MutableStateFlow(false) + override val isDataLoading: StateFlow = _isDataLoading.asStateFlow() + + private var _mapViewState: MutableStateFlow?> = MutableStateFlow(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + private var _selectedMarker: MutableStateFlow = MutableStateFlow(null) + override val selectedMarker: StateFlow = _selectedMarker.asStateFlow() + + private var cameraPosition: MapCameraPosition = initCameraPosition + + private val _renderingStrategy: MutableStateFlow?> = + MutableStateFlow(null) + override val renderingStrategy: StateFlow?> = _renderingStrategy.asStateFlow() + + override var debugHullPolygons by mutableStateOf(false) + + fun loadPostOfficeData() { + if (_markerList.value.isNotEmpty()) return + + viewModelScope.launch(Dispatchers.Default) { + _isDataLoading.value = true + try { + delay(1000) + val postOffices = dataLoader.loadAllPostOffices() + + val markerStates = + postOffices.map { + MarkerState( + position = it.position, + id = it.hashCode().toString(), + icon = postOfficeIcon, + extra = it, + onClick = this@MarkerClusterMapPageViewModel::onMarkerClick, + ) + } + _markerList.value = markerStates + } catch (t: Throwable) { + _markerList.value = emptyList() + } finally { + _isDataLoading.value = false + } + } + } + + // Convenience: in case of error paths, ensure the dialog is hidden + private fun markLoadingFinished() { + if (_isDataLoading.value) { + _isDataLoading.value = false + } + } + + override fun onMarkerClick(clicked: MarkerState) { + this._selectedMarker.value = clicked + } + + override fun onMapClick(clicked: GeoPoint) { + this._selectedMarker.value = null + } + + override fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { + viewModelScope.launch(Dispatchers.Default) { + _isMapLoaded.value = true + _mapViewState.value?.moveCameraTo( + cameraPosition = cameraPosition, + ) + loadPostOfficeData() + } + } + + override fun onInfoClick(postOffice: PostOffice) { + _mapViewState.value?.moveCameraTo( + cameraPosition = + MapCameraPosition( + position = postOffice.position, + zoom = 18.0, + tilt = 30.0, + ), + durationMillis = 2000, + ) + } + + // クラスターをクリックしたら、クラスター内マーカーの重心へズームインする(React と同じロジック)。 + override fun onClusterClicked(cluster: MarkerCluster) { + val byId = _markerList.value.associateBy { it.id } + val positions = cluster.markerIds.mapNotNull { byId[it]?.position } + if (positions.isEmpty()) return + val lat = positions.sumOf { it.latitude } / positions.size + val lng = positions.sumOf { it.longitude } / positions.size + val currentZoom = _mapViewState.value?.cameraPosition?.zoom ?: 10.0 + _mapViewState.value?.moveCameraTo( + cameraPosition = + MapCameraPosition( + position = GeoPoint.fromLatLong(lat, lng), + zoom = minOf(currentZoom + 2.0, 18.0), + ), + durationMillis = 600, + ) + } + + override fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { + cameraPosition = mapViewState.cameraPosition + + renderingStrategy.value?.clear() + this._selectedMarker.value = null + _mapViewState.value = mapViewState + _isMapLoaded.value = false + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/streettree/StreetTreeMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/streettree/StreetTreeMapComponent.kt new file mode 100644 index 000000000..607f064bc --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/streettree/StreetTreeMapComponent.kt @@ -0,0 +1,50 @@ +package com.mapconductor.example.pages.marker.streettree + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import com.mapconductor.compose.info.InfoBubble +import com.mapconductor.compose.marker.Markers +import com.mapconductor.core.OnCameraMoveHandler +import com.mapconductor.core.OnMapEventHandler +import com.mapconductor.core.OnMapLoadedHandler +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTilingOptions +import com.mapconductor.example.MapViewContainer +import com.mapconductor.streettree.StreetTree +import com.mapconductor.streettree.StreetTreeInfoView + +@Composable +fun StreetTreeMapComponent( + mapViewState: MapViewStateInterface<*>, + selectedMarker: MarkerState?, + modifier: Modifier = Modifier, + markers: List = emptyList(), + markerTiling: MarkerTilingOptions? = null, + onMapLoaded: OnMapLoadedHandler? = null, + onMapClick: OnMapEventHandler? = null, + onCameraMoveEnd: OnCameraMoveHandler? = null, +) { + val bubbleColor = if (isSystemInDarkTheme()) Color.Black else Color.White + + MapViewContainer( + modifier = modifier, + state = mapViewState, + markerTiling = markerTiling, + onMapLoaded = onMapLoaded, + onMapClick = onMapClick, + onCameraMoveEnd = onCameraMoveEnd, + ) { + Markers(markers) + + selectedMarker?.let { marker -> + (marker.extra as? StreetTree)?.let { tree -> + InfoBubble(bubbleColor = bubbleColor, marker = marker) { + StreetTreeInfoView(tree = tree) + } + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/streettree/StreetTreePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/streettree/StreetTreePage.kt new file mode 100644 index 000000000..6f04e57ae --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/streettree/StreetTreePage.kt @@ -0,0 +1,83 @@ +package com.mapconductor.example.pages.marker.streettree + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewmodel.compose.viewModel +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.streettree.StreetTreeDataLoader +import com.mapconductor.utils.LoadingDialog +import android.app.Activity + +/** + * 144,183 street trees, one colour per species, drawn as raster tiles. + * + * The point of the page is scale: the same abstraction that carries a handful + * of markers carries this, because past a threshold the markers stop being + * individual overlays and become tiles the backend sees as an ordinary raster + * layer. + */ +@Composable +fun StreetTreePage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val context = LocalContext.current + val dataLoader = remember { StreetTreeDataLoader(context) } + // 再現用の入口。`adb shell am start ... --es camera "35.698,139.766,17.5"` のように渡すと、 + // その場・そのズームで開く(ios-sdk の `MAPCONDUCTOR_SAMPLE_INIT_CAMERA` と同じ)。 + val initCamera = remember { (context as? Activity)?.intent?.getStringExtra("camera") } + + val viewModel: StreetTreeViewModel = + viewModel( + factory = + object : ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") + override fun create(modelClass: Class): T = + StreetTreeViewModel(dataLoader, initCamera = initCamera) as T + }, + ) + + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + val selectedMarker = viewModel.selectedMarker.collectAsState().value + val markers = viewModel.markerList.collectAsState().value + val mapViewState = viewModel.mapViewState.collectAsState().value + val isMapLoaded = viewModel.isMapLoaded.collectAsState().value + val isDataLoading = viewModel.isDataLoading.collectAsState().value + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = viewModel::onMapViewChanged, + ) { paddingValues -> + mapViewState?.let { state -> + StreetTreeMapComponent( + markerTiling = viewModel.markerTiling, + mapViewState = state, + selectedMarker = selectedMarker, + markers = markers, + modifier = modifier.padding(paddingValues), + onMapLoaded = viewModel::onMapLoaded, + onMapClick = viewModel::onMapClick, + onCameraMoveEnd = viewModel::onCameraMoveEnd, + ) + } + } + + if (!isMapLoaded || isDataLoading) { + LoadingDialog( + title = "Loading Street Trees", + message = if (!isMapLoaded) "Preparing map..." else "144,183 trees...", + ) + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/marker/streettree/StreetTreeViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/marker/streettree/StreetTreeViewModel.kt new file mode 100644 index 000000000..ecf358d9f --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/marker/streettree/StreetTreeViewModel.kt @@ -0,0 +1,235 @@ +package com.mapconductor.example.pages.marker.streettree + +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.ImageIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTilingOptions +import com.mapconductor.maplibre.MapLibreDesign +import com.mapconductor.maplibre.MapLibreViewStateInterface +import com.mapconductor.streettree.LabelSide +import com.mapconductor.streettree.StreetTree +import com.mapconductor.streettree.StreetTreeData +import com.mapconductor.streettree.StreetTreeDataLoader +import com.mapconductor.streettree.StreetTreeIcons +import com.mapconductor.streettree.StreetTreeLabels +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +/** + * Tokyo's 144,183 street trees, one colour per species. + * + * The set is six times the post office sample's and packed into one + * metropolitan area rather than spread over a country, so it is what the marker + * tiling path looks like under real pressure. + */ +class StreetTreeViewModel( + private val dataLoader: StreetTreeDataLoader, + private val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Default), + /** `"緯度,経度,ズーム"`。継ぎ目の不具合などを特定の場所で再現するための入口。 */ + initCamera: String? = null, +) : ViewModel() { + val initCameraPosition = + initCamera + ?.split(",") + ?.mapNotNull { it.trim().toDoubleOrNull() } + ?.takeIf { it.size == 3 } + .let { parts -> + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = parts?.get(0) ?: 35.6812, + longitude = parts?.get(1) ?: 139.7671, + ), + zoom = parts?.get(2) ?: 11.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + } + + private val _markerList = MutableStateFlow>(emptyList()) + val markerList: StateFlow> = _markerList.asStateFlow() + + private var treeData: StreetTreeData? = null + + /** 樹種ごとの点。ラベルを外すときはこれに戻す。 */ + private var dotIcons: List = emptyList() + + /** 樹種 × 向きのラベル付きアイコン。画像を持たないので軽い。 */ + private val labelIcons = HashMap() + + /** いまラベルを付けている木と向き。 */ + private var labelled: Map = emptyMap() + + /** 道路ごとに最後に選んだ向き。パンしても同じ通りのラベルが上下・左右で入れ替わらないように。 */ + private val roadSides = java.util.concurrent.ConcurrentHashMap() + + private var labelJob: Job? = null + + /** 木を読み終える前に止まったカメラ。読み終えたらここでラベルを付ける。 */ + private var lastCamera: MapCameraPosition? = null + + private val _selectedMarker = MutableStateFlow(null) + val selectedMarker: StateFlow = _selectedMarker.asStateFlow() + + private val _mapViewState = MutableStateFlow?>(null) + val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + private val _isMapLoaded = MutableStateFlow(false) + val isMapLoaded: StateFlow = _isMapLoaded.asStateFlow() + + private val _isDataLoading = MutableStateFlow(false) + val isDataLoading: StateFlow = _isDataLoading.asStateFlow() + + val markerTiling: MarkerTilingOptions = + MarkerTilingOptions.Default.copy( + // Trees are planted a few metres apart along a road, so below street + // level most of them sit on top of one another. Thinning them to one + // per icon-width halves the tile bytes and shows the same map. + declutterPx = 14, + iconScaleCallback = { _, zoom -> + when { + zoom > 15.0 -> 1.4 + zoom > 13.0 -> 1.0 + zoom > 11.0 -> 0.7 + else -> 0.5 + } + }, + ) + + fun loadTrees() { + if (_markerList.value.isNotEmpty()) return + coroutine.launch { + _isDataLoading.value = true + val data = dataLoader.load() + val icons = StreetTreeIcons.palette(data.species.size, sizeDp = DOT_SIZE_DP) + treeData = data + dotIcons = icons + _markerList.value = + data.trees.mapIndexed { index, tree -> + MarkerState( + position = tree.position, + id = index.toString(), + icon = icons[tree.speciesIndex], + extra = tree, + onClick = ::onMarkerClick, + ) + } + _isDataLoading.value = false + lastCamera?.let(::onCameraMoveEnd) + } + } + + /** + * zoom 16 以上で止まったら、画面内の木に樹種名を付ける。 + * + * どの木にどちら向きで付けるかは [StreetTreeLabels] が決める。付け替えはマーカーの一覧を + * 差し替えず、変わった木のアイコンだけを書き換える -- 14 万件の一覧を作り直すと、 + * そのたびに全件の同期が走る。 + */ + fun onCameraMoveEnd(camera: MapCameraPosition) { + lastCamera = camera + val data = treeData ?: return + val markers = _markerList.value + if (markers.size != data.trees.size) return + labelJob?.cancel() + if (camera.zoom < LABEL_MIN_ZOOM) { + setLabels(emptyMap(), data, markers) + return + } + val bounds = camera.visibleRegion?.bounds ?: return + labelJob = + coroutine.launch { + val sides = + StreetTreeLabels.choose( + trees = data.trees, + bounds = bounds, + zoom = camera.zoom, + scale = LABEL_ICON_SCALE, + dotSizeDp = DOT_SIZE_DP, + labelSizeDp = StreetTreeIcons::labelSizeDp, + previousSides = HashMap(roadSides), + ) + for ((index, side) in sides) roadSides[data.trees[index].roadName] = side + setLabels(sides, data, markers) + } + } + + private fun setLabels( + sides: Map, + data: StreetTreeData, + markers: List, + ) { + for (index in labelled.keys) { + if (index !in sides) markers[index].icon = dotIcons[data.trees[index].speciesIndex] + } + for ((index, side) in sides) { + if (labelled[index] == side) continue + val tree = data.trees[index] + markers[index].icon = + labelIcons.getOrPut("${tree.speciesIndex}/$side") { + StreetTreeIcons.labelled(dotIcons[tree.speciesIndex], tree.species, side) + } + } + labelled = sides + } + + fun onMapViewChanged(mapViewState: MapViewStateInterface<*>) { + _mapViewState.value = mapViewState + applyTreeStyle(mapViewState) + } + + /** + * Swaps in a basemap stripped down to what a tree map needs: land, water, + * the major roads and the place names. The default style draws 51 + * transportation line layers, and at this density they compete with the + * trees for every pixel — the map ends up being about the roads. + * + * Cast because the design type is provider-specific by construction: a + * MapLibre design carries a style URL, a Google one carries a map type id. + * The page runs on whatever backend is selected, so it only reaches for + * this when it is on MapLibre. + */ + private fun applyTreeStyle(mapViewState: MapViewStateInterface<*>) { + @Suppress("UNCHECKED_CAST") + val state = mapViewState as? MapLibreViewStateInterface ?: return + state.mapDesignType = + MapLibreDesign( + id = "street-tree", + styleJsonURL = "asset://street-tree-style.json", + ) + } + + fun onMapLoaded(mapViewState: MapViewStateInterface<*>) { + _isMapLoaded.value = true + loadTrees() + } + + fun onMarkerClick(clicked: MarkerState) { + _selectedMarker.value = clicked + } + + fun onMapClick(clicked: GeoPoint) { + _selectedMarker.value = null + } + + val StreetTree.label: String get() = species + + companion object { + /** ラベルを出すズーム。 */ + const val LABEL_MIN_ZOOM = 16.0 + + const val DOT_SIZE_DP = 10f + + /** zoom > 15 の iconScaleCallback と同じ値。ラベルの重なりはこの大きさで測る。 */ + const val LABEL_ICON_SCALE = 1.4f + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/offlinemap/OfflineMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/offlinemap/OfflineMapPage.kt new file mode 100644 index 000000000..873c753b2 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/offlinemap/OfflineMapPage.kt @@ -0,0 +1,385 @@ +package com.mapconductor.example.pages.offlinemap + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.FilterChip +import androidx.compose.material3.FilterChipDefaults +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.compose.marker.Marker +import com.mapconductor.compose.polygon.Polygon +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.map.VectorStyleSupportKey +import com.mapconductor.core.marker.ColorDefaultIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.pages.vectortile.VectorTileStyleLoader +import com.mapconductor.example.pages.vectortile.showProviderBasemap +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.vectortile.OfflinePackage +import com.mapconductor.vectortile.OfflinePackageDownloader +import com.mapconductor.vectortile.VectorTileLayer +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * A map that works with the network off. + * + * "Select area…" enters download mode: two draggable markers mark the + * south-west and north-east corners of an area, and everything outside it is + * shaded. "Download" then fetches the vector tiles, glyphs and sprite the + * style needs to draw that area into a package on the device, and leaves + * download mode. "Airplane mode" then cuts the layer off from the network: + * inside the area the map is drawn from the package, outside it there is + * nothing to draw -- which is how you can see the package working. + */ +@Composable +fun OfflineMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val packageDir = remember { context.filesDir.resolve("offline-map") } + + var styleJson by remember { mutableStateOf(null) } + var failure by remember { mutableStateOf(null) } + var mapViewState by remember { mutableStateOf?>(null) } + var offlinePackage by remember { mutableStateOf(OfflinePackage.open(packageDir)) } + var progress by remember { mutableStateOf(null) } + var airplane by remember { mutableStateOf(false) } + // Download mode: the area markers and the shade are shown only while an + // area is being chosen. The rest of the time the page is just the map. + var selecting by remember { mutableStateOf(false) } + var stats by remember { mutableStateOf(null) } + var diagnostics by remember { mutableStateOf>(emptyList()) } + + // Central Tokyo, an area a few kilometres across: small enough to fetch + // in seconds, large enough to pan around inside. A launch extra + // `offlineCenter` ("lat,lon") starts elsewhere, for trying other places. + val initCameraPosition = + remember { + val requested = + (context as? android.app.Activity) + ?.intent + ?.getStringExtra("offlineCenter") + ?.split(',') + ?.takeIf { it.size == 2 } + ?.let { runCatching { GeoPoint(it[0].trim().toDouble(), it[1].trim().toDouble()) }.getOrNull() } + MapCameraPosition( + position = requested ?: GeoPoint.fromLatLong(latitude = 35.6805, longitude = 139.7675), + zoom = 13.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + } + var southWest by remember { mutableStateOf(GeoPoint(35.6650, 139.7450)) } + var northEast by remember { mutableStateOf(GeoPoint(35.6960, 139.7900)) } + + // The mask: a wide ring with the area cut out of it, so the area is the + // one clear patch on a darkened map. The ring follows the area -- a hole + // has to lie inside its ring, and one that does not is not a hole but a + // second, filled polygon (which is what the map drew when the ring was + // left over Tokyo and the area was chosen in Los Angeles). + val mask = + remember { + PolygonState( + id = "offline-mask", + points = maskRing(southWest, northEast), + holes = listOf(rectangle(southWest, northEast)), + fillColor = Color(0x80000000), + strokeColor = Color.Transparent, + strokeWidth = 0.dp, + clickable = false, + // Above the tiles: on backends that order tile overlays and + // shapes in one z space, a shade at 0 sits under the map. + zIndex = 10_000, + ) + } + + fun cornerMoved(dragged: MarkerState) { + val point = GeoPoint.from(dragged.position) + if (dragged.id == "sw") southWest = point else northEast = point + mask.points = maskRing(southWest, northEast) + mask.holes = listOf(rectangle(southWest, northEast)) + } + + lateinit var swMarker: MarkerState + lateinit var neMarker: MarkerState + + /** Enters download mode with the area centred on the map as it is now. */ + fun beginSelection() { + val center = mapViewState?.cameraPosition?.position?.let { GeoPoint.from(it) } ?: GeoPoint(35.6805, 139.7675) + southWest = GeoPoint(center.latitude - 0.0155, center.longitude - 0.0225) + northEast = GeoPoint(center.latitude + 0.0155, center.longitude + 0.0225) + swMarker.position = southWest + neMarker.position = northEast + mask.points = maskRing(southWest, northEast) + mask.holes = listOf(rectangle(southWest, northEast)) + selecting = true + } + swMarker = + remember { + MarkerState( + id = "sw", + position = southWest, + draggable = true, + clickable = false, + icon = + ColorDefaultIcon( + fillColor = Color(0xFF1D4ED8), + strokeColor = Color.White, + label = "SW", + labelTextColor = Color.White, + ), + onDrag = ::cornerMoved, + onDragEnd = ::cornerMoved, + ) + } + neMarker = + remember { + MarkerState( + id = "ne", + position = northEast, + draggable = true, + clickable = false, + icon = + ColorDefaultIcon( + fillColor = Color(0xFFB91C1C), + strokeColor = Color.White, + label = "NE", + labelTextColor = Color.White, + ), + onDrag = ::cornerMoved, + onDragEnd = ::cornerMoved, + ) + } + + // The style comes from the package when there is one -- it carries the + // style it was made from -- and from the network only when there is not. + // Opening the page with the device offline and a package on it must not + // need the network for anything. + LaunchedEffect(offlinePackage?.manifest?.createdAt) { + if (styleJson != null) return@LaunchedEffect + offlinePackage?.let { pkg -> + styleJson = pkg.styleJson + return@LaunchedEffect + } + runCatching { withContext(Dispatchers.IO) { VectorTileStyleLoader.load() } } + .onSuccess { styleJson = it } + .onFailure { failure = "style could not be fetched (offline with no package?): ${it.message ?: it}" } + } + + // The style is the map here: the backend's own basemap is blanked + // wherever the backend can, and the MapLibre-based backends take the + // style directly (and read the package through the local server). + LaunchedEffect(mapViewState) { + val state = mapViewState ?: return@LaunchedEffect + if (state.serviceRegistry.has(VectorStyleSupportKey)) return@LaunchedEffect + showProviderBasemap(state, visible = false) + } + + fun download() { + val style = styleJson ?: return + val bounds = + OfflinePackage.Bounds( + south = minOf(southWest.latitude, northEast.latitude), + west = minOf(southWest.longitude, northEast.longitude), + north = maxOf(southWest.latitude, northEast.latitude), + east = maxOf(southWest.longitude, northEast.longitude), + ) + scope.launch { + offlinePackage = null + runCatching { + OfflinePackageDownloader.download( + styleJson = style, + bounds = bounds, + minZoom = 0, + maxZoom = 14, + directory = packageDir, + onProgress = { progress = it }, + ) + }.onSuccess { + offlinePackage = it + progress = null + selecting = false + }.onFailure { + failure = "download failed: ${it.message}" + progress = null + } + } + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { mapViewState = it }, + ) { paddings -> + Box( + modifier = + modifier + .fillMaxSize() + .padding(paddings), + contentAlignment = Alignment.Center, + ) { + mapViewState?.let { state -> + MapViewContainer(state = state) { + val style = styleJson + if (style != null) { + // Keyed on the mode so that flipping it rebuilds the + // layer: every tile and every source is then fetched + // afresh, and what the package cannot answer stays + // blank instead of lingering from a cache. That is the + // point of the demonstration. + key(airplane, offlinePackage) { + VectorTileLayer( + styleJson = style, + asBasemap = true, + offlinePackage = offlinePackage, + online = !airplane, + onOfflineStats = { stats = it }, + onDiagnostics = { diagnostics = it }, + ) + } + } + if (selecting) { + Polygon(mask) + Marker(swMarker) + Marker(neMarker) + } + } + } + + Card( + modifier = + Modifier + .align(Alignment.BottomCenter) + .padding(start = 8.dp, end = 8.dp, top = 8.dp, bottom = 28.dp), + ) { + Column(modifier = Modifier.padding(8.dp)) { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (selecting) { + Button( + onClick = ::download, + enabled = styleJson != null && progress == null, + modifier = Modifier.testTag("downloadButton"), + ) { Text(if (progress == null) "Download" else "Downloading…", fontSize = 12.sp) } + OutlinedButton( + onClick = { selecting = false }, + enabled = progress == null, + modifier = Modifier.testTag("cancelSelectButton"), + ) { Text("Cancel", fontSize = 12.sp) } + } else { + Button( + onClick = ::beginSelection, + enabled = styleJson != null, + modifier = Modifier.testTag("selectAreaButton"), + ) { Text("Select area…", fontSize = 12.sp) } + FilterChip( + selected = airplane, + onClick = { airplane = !airplane }, + label = { + Text( + if (airplane) "✈ Airplane mode ON" else "✈ Airplane mode", + fontSize = + 12 + .sp, + ) + }, + colors = FilterChipDefaults.filterChipColors(), + modifier = Modifier.testTag("airplaneToggle"), + ) + OutlinedButton( + onClick = { + OfflinePackage.delete(packageDir) + offlinePackage = null + stats = null + }, + enabled = offlinePackage != null, + ) { Text("Clear", fontSize = 12.sp) } + } + } + val pkg = offlinePackage + val status = + when { + progress != null -> "downloading: $progress" + selecting -> "drag SW/NE to choose the area, then Download" + pkg == null -> "no package: Select area…, then Download" + else -> + "package: ${pkg.manifest.tiles} tiles, ${pkg.manifest.glyphs} glyph ranges, " + + "${pkg.manifest.sprites} sprite files, " + + "z${pkg.manifest.minZoom}-${pkg.manifest.maxZoom}, " + + "${pkg.manifest.bytes / 1024} KB" + } + Text(status, fontSize = 12.sp, modifier = Modifier.testTag("offlineStatus")) + Text( + "mode=${if (airplane) "offline" else "online"} " + + "fetches: ${stats?.toString() ?: "-"}", + fontSize = 12.sp, + modifier = Modifier.testTag("offlineFetches"), + ) + diagnostics.forEach { Text(it, fontSize = 11.sp, color = Color(0xFF7A4A00)) } + failure?.let { Text(it, fontSize = 11.sp, color = Color.Red) } + } + } + } + } +} + +/** + * The shade's outer ring: several degrees around the area, wherever it is, + * kept inside the map's latitude and longitude range so it never wraps. + */ +private fun maskRing( + a: GeoPoint, + b: GeoPoint, +): List { + val pad = 6.0 + val south = (minOf(a.latitude, b.latitude) - pad).coerceAtLeast(-85.0) + val north = (maxOf(a.latitude, b.latitude) + pad).coerceAtMost(85.0) + val west = (minOf(a.longitude, b.longitude) - pad).coerceAtLeast(-180.0) + val east = (maxOf(a.longitude, b.longitude) + pad).coerceAtMost(180.0) + return listOf(GeoPoint(south, west), GeoPoint(south, east), GeoPoint(north, east), GeoPoint(north, west)) +} + +/** The four corners between two opposite ones, as a ring. */ +private fun rectangle( + a: GeoPoint, + b: GeoPoint, +): List { + val south = minOf(a.latitude, b.latitude) + val north = maxOf(a.latitude, b.latitude) + val west = minOf(a.longitude, b.longitude) + val east = maxOf(a.longitude, b.longitude) + return listOf(GeoPoint(south, west), GeoPoint(south, east), GeoPoint(north, east), GeoPoint(north, west)) +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapComponent.kt index 98365199e..2cfa70854 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapComponent.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapComponent.kt @@ -16,7 +16,7 @@ fun PolygonMapComponent( polygonState: PolygonState, modifier: Modifier = Modifier, ) { - mapViewState?.let { it -> + mapViewState?.let { MapViewContainer( modifier = modifier, state = it, diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapPage.kt index 332350667..4de743496 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapPage.kt @@ -19,7 +19,10 @@ import com.mapconductor.example.ui.DemoMapPageScaffold import com.mapconductor.example.ui.MessageCard @Composable -fun PolygonMapPage(onToggleSidebar: () -> Unit = {}) { +fun PolygonMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel = remember { PolygonMapPageViewModel() } DemoMapPageScaffold( @@ -34,6 +37,7 @@ fun PolygonMapPage(onToggleSidebar: () -> Unit = {}) { mapViewState = mapViewState.value, polygonState = viewModel.polygonState, polygonVertexMarkers = viewModel.polygonVertexMarkers, + modifier = modifier.padding(paddingValues), ) MessageCard( title = "Polygon Example", diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapPageViewModel.kt index a8cf4fecb..e71d511a9 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/basic/PolygonMapPageViewModel.kt @@ -1,7 +1,6 @@ package com.mapconductor.example.pages.polygon.basic import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color @@ -38,9 +37,11 @@ class PolygonMapPageViewModel : private val _mapViewState = MutableStateFlow?>(null) override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - // Polygon vertices - private val polygonVertices = - mutableStateListOf( + // Polygon vertices. Kept as a read-only list and replaced as a whole on every + // drag: PolygonState only hears assignments to its fields, so editing a list + // it already holds in place would never reach the map. + private var polygonVertices: List = + listOf( GeoPoint(41.79883, 140.75675), GeoPoint(41.799240000000005, 140.75875000000002), GeoPoint(41.797650000000004, 140.75905), @@ -61,8 +62,30 @@ class PolygonMapPageViewModel : zoom = 16.0, ) - override var fillOpacity by mutableStateOf(0.3f) - override var strokeWidth by mutableStateOf(3.0.dp) + private var fillOpacityValue by mutableStateOf(0.3f) + + override var fillOpacity: Float + get() = fillOpacityValue + set(value) { + fillOpacityValue = value + polygonState.fillColor = fillColorFor(value) + } + + override var strokeWidth: Dp + get() = polygonState.strokeWidth + set(value) { + polygonState.strokeWidth = value + } + + override val polygonState = + PolygonState( + points = polygonVertices, + id = "example_polygon", + strokeColor = Color.Red, + strokeWidth = 3.0.dp, + fillColor = fillColorFor(fillOpacityValue), + geodesic = false, + ) override val polygonVertexMarkers: List = polygonVertices.mapIndexed { index, point -> @@ -81,26 +104,20 @@ class PolygonMapPageViewModel : ) } - override val polygonState: PolygonState - get() = - PolygonState( - points = polygonVertices, - id = "example_polygon", - strokeColor = Color.Red, - strokeWidth = strokeWidth, - fillColor = Color.Blue.copy(alpha = fillOpacity), - geodesic = false, - ) - override fun onMapViewChanged(state: MapViewStateInterface<*>) { _mapViewState.value = state } override fun onMarkerDrag(dragged: MarkerState) { (dragged.extra as? Int)?.let { index -> - if (index >= 0 && index < polygonVertices.size) { - polygonVertices[index] = GeoPoint.from(dragged.position) - } + if (index !in polygonVertices.indices) return + polygonVertices = + polygonVertices.mapIndexed { i, point -> + if (i == index) GeoPoint.from(dragged.position) else point + } + polygonState.points = polygonVertices } } + + private fun fillColorFor(opacity: Float): Color = Color.Blue.copy(alpha = opacity) } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonBuildingsPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonBuildingsPage.kt new file mode 100644 index 000000000..fb5f3f752 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonBuildingsPage.kt @@ -0,0 +1,173 @@ +package com.mapconductor.example.pages.polygon.boston + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.calculateEndPadding +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material3.Button +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.compose.info.InfoBubble +import com.mapconductor.compose.polygon.Polygons +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.example.ui.MessageCard +import android.app.Activity + +@Composable +fun BostonBuildingsPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val context = LocalContext.current + // `adb shell am start ... --es camera "42.35545,-71.0605,17" --es area 2` opens + // a fixed view, so a measurement sees the same thing on every provider. + val viewModel = + remember { + val intent = (context as? Activity)?.intent + BostonBuildingsViewModel( + context = context.applicationContext, + initCamera = intent?.getStringExtra("camera"), + initArea = intent?.getStringExtra("area")?.toIntOrNull(), + initDataset = + when (intent?.getStringExtra("data")) { + "buildings" -> Dataset.CITY_BUILDINGS + "parcels" -> Dataset.CITY_PARCELS + else -> null + }, + ) + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = viewModel::onMapViewChanged, + ) { paddingValues -> + val mapViewState = viewModel.mapViewState.collectAsState() + val states = viewModel.polygonStates.collectAsState() + val area = viewModel.area.collectAsState() + val dataset = viewModel.dataset.collectAsState() + val loadError = viewModel.loadError.collectAsState() + val stats = viewModel.stats.collectAsState() + val attribution = viewModel.attribution.collectAsState() + val tap = viewModel.tap.collectAsState() + val progress = viewModel.progress.collectAsState() + + // Two frames after the list reaches Polygons(), for the stats. The loading overlay waits for onAdded. + LaunchedEffect(states.value) { + val shown = states.value + withFrameNanos {} + withFrameNanos {} + viewModel.onDrawn(shown) + } + + mapViewState.value?.let { + MapViewContainer( + state = it, + modifier = modifier.padding(paddingValues), + onMapClick = viewModel::onMapClick, + ) { + Polygons(states.value) + val shownTap = tap.value + val building = shownTap?.building + val point = shownTap?.point + if (building != null && point != null) { + InfoBubble(position = point, borderWidth = 1.dp, borderColor = Color(0x33000000)) { + PolygonInfo(building) + } + } + } + } + + progress.value?.let { LoadingOverlay(it, modifier = Modifier.padding(paddingValues)) } + + Column( + modifier = + Modifier + .align(Alignment.TopStart) + .padding(top = paddingValues.calculateTopPadding() + 16.dp, start = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Dataset.entries.forEach { entry -> + if (entry == dataset.value) { + Button(onClick = {}) { Text(entry.label) } + } else { + FilledTonalButton(onClick = { viewModel.setDataset(entry) }) { Text(entry.label) } + } + } + } + if (dataset.value == Dataset.DOWNTOWN) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + AREAS.forEachIndexed { level, label -> + if (level == area.value) { + Button(onClick = {}) { Text(label) } + } else { + FilledTonalButton(onClick = { viewModel.setArea(level) }) { Text(label) } + } + } + } + } + } + + MessageCard( + title = + stats.value?.let { "Boston ${dataset.value.label}: ${it.polygons} polygons, ${it.vertices} vertices" } + ?: "Boston ${dataset.value.label}", + isCardOpen = true, + maxHeight = 260.dp, + modifier = + Modifier + .align(Alignment.BottomStart) + // On a tablet the card would otherwise run under the whole map. + .widthIn(max = PANEL_MAX_WIDTH) + .padding( + bottom = paddingValues.calculateBottomPadding() + 16.dp, + start = paddingValues.calculateStartPadding(LayoutDirection.Ltr) + 16.dp, + end = paddingValues.calculateEndPadding(LayoutDirection.Ltr) + 16.dp, + ), + ) { + loadError.value?.let { Text(it) } + if (dataset.value == Dataset.CITY_PARCELS) LandUseLegend(modifier = Modifier.padding(vertical = 4.dp)) + stats.value?.let { + val frame = it.frameMillis?.let { ms -> ", next frame $ms ms" } ?: "" + val added = it.addedMillis?.let { ms -> ", on the map $ms ms" } ?: "" + Text("Load ${it.loadMillis} ms, states ${it.buildMillis} ms$frame$added") + } + tap.value?.let { tap -> + val building = tap.building + val use = building?.use + Text( + when { + building == null -> "No building here" + use != null -> "Parcel · ${use.label} · ${formatArea(areaSquareMetres(building))}" + else -> { + val height = building.height?.let { "$it m" } ?: "height unknown" + "${building.name ?: "Building"} · $height · ${formatArea(areaSquareMetres(building))}" + } + }, + ) + } + Text(attribution.value, fontSize = 11.sp) + } + } +} + +/** Wide enough for the title and two legend columns without wrapping. */ +private val PANEL_MAX_WIDTH = 480.dp diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonBuildingsViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonBuildingsViewModel.kt new file mode 100644 index 000000000..80a7e5a80 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonBuildingsViewModel.kt @@ -0,0 +1,353 @@ +package com.mapconductor.example.pages.polygon.boston + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.polygon.PolygonState +import android.content.Context +import android.os.SystemClock +import android.util.Log +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +private const val TAP_LOG_TAG = "BostonTap" +private val TAPPED = Color(0xD92563EB) + +/** The three nested areas around Downtown Crossing; a building belongs to the smallest that holds it. */ +val AREAS = listOf("0.8 × 1.1 km", "1.6 × 2.2 km", "3.2 × 4.4 km") + +class Building( + val id: String, + val level: Int, + val height: Double?, + val name: String?, + val rings: List, + /** A parcel's land use, from the City of Boston's Property Assessment. */ + val use: LandUse? = null, + /** A road's class (the roads file): the index in [com.mapconductor.example.pages.polyline.boston.RoadClass]. */ + val roadClass: Int? = null, +) + +/** What the last tap hit: a building, or nothing (`building` null), and where it landed. */ +data class Tap( + val seq: Int, + val building: Building?, + val point: GeoPoint?, +) + +data class BuildingStats( + val polygons: Int, + val vertices: Int, + val loadMillis: Long, + val buildMillis: Long, + /** From handing the list to Polygons() until two frames later; null until then. */ + val frameMillis: Long? = null, + /** From handing the list to Polygons() until the map had all of it (every onAdded); null until then. */ + val addedMillis: Long? = null, +) + +/** + * Polygons of Boston drawn on top of the real map: Overture building footprints + * of downtown in three nested areas (0.8 x 1.1 km, 1.6 x 2.2 km, 3.2 x 4.4 km), + * or the whole city's buildings or parcels (about 100,000 polygons each, see + * [Dataset]) as a load test. + * + * Tapping a polygon highlights it and shows what it carries in an InfoBubble at + * the tap; tapping elsewhere closes it and says nothing was hit. Every tap is + * also logged under `BostonTap`, which is how the hit testing is checked from + * outside. Parcels are coloured by land use. A loading overlay shows how far + * reading, decoding, building the states and drawing have got; it stays up + * until every polygon shown has been added to the map ([PolygonState.onAdded]), + * not just until the list has been handed over. + * + * `camera` ("lat,lng,zoom"), `data` (downtown, buildings or parcels) and `area` + * (0, 1 or 2) come from the intent extras, so a measurement opens the same view + * on every provider. + */ +class BostonBuildingsViewModel( + private val context: Context, + initCamera: String?, + initArea: Int?, + initDataset: Dataset?, +) : ViewModel() { + private val _mapViewState = MutableStateFlow?>(null) + val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + val initCameraPosition: MapCameraPosition = + initCamera + ?.split(',') + ?.mapNotNull { it.trim().toDoubleOrNull() } + ?.takeIf { it.size == 3 } + ?.let { (lat, lng, zoom) -> MapCameraPosition(position = GeoPoint(lat, lng), zoom = zoom) } + ?: MapCameraPosition(position = GeoPoint(42.35545, -71.0605), zoom = 16.0) + + private val _area = MutableStateFlow(initArea?.takeIf { it in AREAS.indices } ?: 0) + val area: StateFlow = _area.asStateFlow() + + private val _dataset = MutableStateFlow(initDataset ?: Dataset.DOWNTOWN) + val dataset: StateFlow = _dataset.asStateFlow() + + private val _loadError = MutableStateFlow(null) + val loadError: StateFlow = _loadError.asStateFlow() + + private val _polygonStates = MutableStateFlow>(emptyList()) + val polygonStates: StateFlow> = _polygonStates.asStateFlow() + + private val _stats = MutableStateFlow(null) + val stats: StateFlow = _stats.asStateFlow() + + private val _attribution = MutableStateFlow("") + val attribution: StateFlow = _attribution.asStateFlow() + + private val _tap = MutableStateFlow(null) + val tap: StateFlow = _tap.asStateFlow() + + /** Non-null while a dataset is on its way; drives the loading overlay. */ + private val _progress = MutableStateFlow(null) + val progress: StateFlow = _progress.asStateFlow() + + private var shownAt = 0L + + /** + * Which load the polygons' onAdded belongs to. A callback from an earlier + * dataset (its polygons may still be arriving when the next one is picked) + * is ignored. + */ + private var generation = 0 + + /** + * Which ids of this load have reached the map, from their states' onAdded. + * The loading overlay stays up until every id of the list now handed to the + * map is here. + * + * An id stays recorded when its building leaves the list (the area shrank). + * The SDK calls onAdded again only for a polygon it saw leave, and a list + * replaced before the SDK got to it is never seen: forgetting the id there + * left the overlay up for good when the area was switched mid-load. So the + * count is redone against each new list ([show]), and an id already on the + * map counts for it. + */ + private var addedIds = HashSet() + + /** The distinct ids of the list now handed to the map. */ + private var listIds: Set = emptySet() + + /** How many of [listIds] are in [addedIds]. */ + private var onMapCount = 0 + + /** True from handing this load's first list to the map until all of it is there. */ + private var waitingForAdds = false + + private var buildings: List = emptyList() + private var states: List = emptyList() + private var loadMillis = 0L + private var buildMillis = 0L + private var highlighted: Pair? = null + + init { + load() + } + + fun setDataset(dataset: Dataset) { + if (_dataset.value == dataset) return + _dataset.value = dataset + load() + } + + private fun load() { + val dataset = _dataset.value + val gen = ++generation + addedIds = HashSet() + listIds = emptySet() + onMapCount = 0 + waitingForAdds = false + // Until this load's states are built there is nothing to show; an area + // switch meanwhile only records the area (see [setArea]). + buildings = emptyList() + states = emptyList() + _polygonStates.value = emptyList() + _stats.value = null + _loadError.value = null + _tap.value = null + highlighted = null + _progress.value = LoadPhase.Read(0, null) + viewModelScope.launch { + val started = SystemClock.elapsedRealtime() + val loaded = + try { + withContext(Dispatchers.IO) { + loadBostonData(context, dataset) { phase -> _progress.value = phase } + } + } catch (e: Exception) { + _progress.value = null + _loadError.value = e.message + return@launch + } + loadMillis = SystemClock.elapsedRealtime() - started + _attribution.value = loaded.attribution + _progress.value = LoadPhase.Build + val built = SystemClock.elapsedRealtime() + // One callback for the whole load; it knows which load it belongs to. + val onAdded: (PolygonState) -> Unit = { state -> onPolygonAdded(gen, state.id) } + val newStates = + withContext(Dispatchers.Default) { + loaded.buildings.map { toState(it, dataset, onAdded) } + } + // A newer load started meanwhile; its states are the ones to show. + if (gen != generation) return@launch + buildings = loaded.buildings + states = newStates + buildMillis = SystemClock.elapsedRealtime() - built + waitingForAdds = true + show() + } + } + + fun onMapViewChanged(state: MapViewStateInterface<*>) { + _mapViewState.value = state + } + + fun setArea(level: Int) { + if (_area.value == level) return + _area.value = level + show() + } + + fun onMapClick(point: GeoPointInterface) { + onTap(null, null, point) + } + + /** + * Hands the area's polygons to the map. While this load waits for its + * polygons ([waitingForAdds]) the loading overlay stays up until every id of + * this list has reported onAdded, whichever list it first arrived for. + */ + private fun show() { + // An area switch while the dataset is still being read or built: the + // load shows the area picked by then. + if (states.isEmpty()) return + val level = _area.value + val shown = states.filterIndexed { i, _ -> buildings[i].level <= level } + val vertices = shown.sumOf { state -> state.points.size + state.holes.sumOf { it.size } } + _stats.value = BuildingStats(shown.size, vertices, loadMillis, buildMillis) + Log.i( + TAP_LOG_TAG, + "shown dataset=${_dataset.value} polygons=${shown.size} vertices=$vertices load=$loadMillis build=$buildMillis", + ) + shownAt = SystemClock.elapsedRealtime() + // Counted against the new list from here on. + listIds = shown.mapTo(HashSet()) { it.id } + onMapCount = listIds.count { it in addedIds } + if (waitingForAdds && _progress.value != null) _progress.value = LoadPhase.Draw + _polygonStates.value = shown + finishIfAllAdded() + } + + // Runs on the main thread, once per polygon each time the map takes it in. + private fun onPolygonAdded( + gen: Int, + id: String, + ) { + if (gen != generation || !addedIds.add(id)) return + // A building of a list since replaced: on the map, but not one waited for now. + if (id !in listIds) return + onMapCount++ + finishIfAllAdded() + } + + private fun finishIfAllAdded() { + if (!waitingForAdds || onMapCount < listIds.size) return + waitingForAdds = false + onAllAdded() + } + + /** Every polygon shown is on the map: tiles handed over or native objects made. */ + private fun onAllAdded() { + val shown = _polygonStates.value + _progress.value = null + if (shown.isEmpty()) return + val added = SystemClock.elapsedRealtime() - shownAt + _stats.value = _stats.value?.copy(addedMillis = added) + Log.i(TAP_LOG_TAG, "added dataset=${_dataset.value} polygons=${shown.size} added=$added") + } + + /** + * The page calls this two frames after the list reached Polygons(). The + * loading overlay stays up: the map is still taking the polygons in + * (see [onAllAdded]). + */ + fun onDrawn(states: List) { + if (states.isEmpty() || states !== _polygonStates.value) return + val frame = SystemClock.elapsedRealtime() - shownAt + _stats.value = _stats.value?.copy(frameMillis = frame) + Log.i(TAP_LOG_TAG, "drawn dataset=${_dataset.value} polygons=${states.size} frame=$frame") + } + + // Moves the highlight to `state` (or clears it) and records the tap. + private fun onTap( + state: PolygonState?, + building: Building?, + point: GeoPointInterface? = null, + ) { + highlighted?.let { (previous, fill) -> previous.fillColor = fill } + highlighted = state?.let { it to it.fillColor } + state?.fillColor = TAPPED + val seq = (_tap.value?.seq ?: 0) + 1 + _tap.value = Tap(seq, building, point?.let { GeoPoint(it.latitude, it.longitude) }) + Log.i( + TAP_LOG_TAG, + "seq=$seq id=${building?.id ?: ""} lat=${point?.latitude ?: ""} lng=${point?.longitude ?: ""}", + ) + } + + private fun toState( + building: Building, + dataset: Dataset, + onAdded: (PolygonState) -> Unit, + ): PolygonState { + val rings = building.rings.map(::toPoints) + return PolygonState( + points = rings.first(), + holes = rings.drop(1), + id = building.id, + strokeColor = if (dataset == Dataset.CITY_PARCELS) Color(0xB3475569) else Color(0xCC44403C), + strokeWidth = 1.dp, + fillColor = + if (dataset == + Dataset.CITY_PARCELS + ) { + (building.use ?: LandUse.UNKNOWN).fill + } else { + fillForHeight(building.height) + }, + extra = building.id, + onClick = { event -> onTap(event.state, building, event.clicked) }, + onAdded = onAdded, + ) + } +} + +private fun toPoints(ring: DoubleArray): List = + List(ring.size / 2) { + GeoPoint(ring[it * 2 + 1], ring[it * 2]) + } + +// Darker for taller buildings; grey when the height is unknown. +private fun fillForHeight(height: Double?): Color = + when { + height == null -> Color(0x9994A3B8) + height < 15 -> Color(0xB3FEF08A) + height < 30 -> Color(0xB3FDBA74) + height < 60 -> Color(0xB3F97316) + height < 120 -> Color(0xB3DC2626) + else -> Color(0xBF7F1D1D) + } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonData.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonData.kt new file mode 100644 index 000000000..86a639921 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonData.kt @@ -0,0 +1,218 @@ +package com.mapconductor.example.pages.polygon.boston + +import androidx.compose.ui.graphics.Color +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.spherical.Spherical +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer +import java.nio.ByteOrder +import android.content.Context + +/** + * The polygons the Boston page draws. + * + * - [DOWNTOWN]: Overture building footprints of downtown in three nested areas. + * - [CITY_BUILDINGS] / [CITY_PARCELS]: the whole city: Overture buildings, and + * Analyze Boston Parcels 2025 joined with the FY2026 Property Assessment land use. + * + * All three are bundled (assets/boston). The React sample's + * `examples/basic/tools/boston/` builds them from the official sources (see its + * README). The files carry no ids: this is a polygon demo, and a polygon's id on + * the map is its index in the file. + * + * The binary layout is the same as the React sample's (bostonData.ts), MCPG v2: + * 'MCPG' u32 version=2 u32 count u8 fields u8 digits (little-endian) + * fields: 1 = height, 2 = land use, 4 = area, 8 = name, 16 = road class (what the file carries), + * 32 = lines: the shapes are polylines, not polygons (the roads file, see BostonRoadsData) + * digits: coordinates are integers of 10^-digits degree (buildings 6, parcels 5) + * per polygon, only the fields present, in this order: + * height varint, 0 = unknown, else the height in 0.1 m plus 1 + * land use u8, the index in [LandUse] (family … unknown) + * area u8, the smallest downtown area (0, 1 or 2) the building fits in + * name varint byte length (0 = none), UTF-8 + * road class u8, the index in RoadClass (highway … path) + * varint ringCount, per ring: varint n, n x (svarint dLat, svarint dLng) + * varint is LEB128 (7 bits at a time, low first); svarint is a zigzag varint. + * Coordinates are integers of 10^-digits degree, each the difference from the + * previous vertex across the whole file. A ring's closing vertex (the same as its first) + * is not stored: n counts the others, and the reader closes the ring again. + * With the lines bit a "ring" is an open polyline: every vertex is stored and + * the reader does not close it. + */ +enum class Dataset( + val label: String, + /** The file in assets. */ + val file: String, + val attribution: String, +) { + DOWNTOWN("Downtown", "boston/boston-downtown.bin", OVERTURE_ATTRIBUTION), + CITY_BUILDINGS("City buildings", "boston/boston-city-buildings.bin", OVERTURE_ATTRIBUTION), + CITY_PARCELS( + "City parcels", + "boston/boston-city-parcels.bin", + "City of Boston, Parcels 2025 and FY2026 Property Assessment (Analyze Boston) (ODC PDDL)", + ), +} + +private const val OVERTURE_ATTRIBUTION = + "© OpenStreetMap contributors, Esri Community Maps contributors, USGS, Microsoft — via Overture Maps Foundation (ODbL 1.0)" + +/** + * Land use of a parcel (Property Assessment `LU`, grouped) and how it is drawn; the same as the React sample. + * The order is the file's: a land use is stored as its index here. + */ +enum class LandUse( + val key: String, + val label: String, + val fill: Color, +) { + FAMILY("family", "1–3 family", Color(0x8CFACC15)), + APARTMENT("apartment", "Apartments", Color(0x8CF97316)), + CONDO("condo", "Condominium", Color(0x80EC4899)), + MIXED("mixed", "Residential + commercial", Color(0x80A855F7)), + COMMERCIAL("commercial", "Commercial", Color(0x8CEF4444)), + INDUSTRIAL("industrial", "Industrial", Color(0x9964748B)), + EXEMPT("exempt", "Exempt (public, institutions)", Color(0x803B82F6)), + VACANT("vacant", "Vacant land", Color(0x7322C55E)), + UNKNOWN("unknown", "No assessment (roads, islands)", Color(0x5994A3B8)), +} + +/** Where loading has got to, for the overlay. */ +sealed class LoadPhase { + data class Read( + val loaded: Long, + val total: Long?, + ) : LoadPhase() + + data object Decode : LoadPhase() + + data object Build : LoadPhase() + + data object Draw : LoadPhase() +} + +class BostonData( + val attribution: String, + val buildings: List, +) + +fun loadBostonData( + context: Context, + dataset: Dataset, + onProgress: (LoadPhase) -> Unit = {}, +): BostonData { + // openFd works only on an uncompressed asset; without it the progress has no total. + val length = runCatching { context.assets.openFd(dataset.file).use { it.length } }.getOrNull() + val bytes = readWithProgress(context.assets.open(dataset.file), length, onProgress) + onProgress(LoadPhase.Decode) + return BostonData(dataset.attribution, decodeMcpg(bytes, dataset.name.lowercase())) +} + +private fun readWithProgress( + input: java.io.InputStream, + total: Long?, + onProgress: (LoadPhase) -> Unit, +): ByteArray = + input.use { stream -> + val out = ByteArrayOutputStream(total?.toInt() ?: 1 shl 20) + val chunk = ByteArray(256 * 1024) + var loaded = 0L + onProgress(LoadPhase.Read(loaded, total)) + while (true) { + val n = stream.read(chunk) + if (n < 0) break + out.write(chunk, 0, n) + loaded += n + onProgress(LoadPhase.Read(loaded, total)) + } + out.toByteArray() + } + +private const val FIELD_HEIGHT = 1 +private const val FIELD_USE = 2 +private const val FIELD_AREA = 4 +private const val FIELD_NAME = 8 +private const val FIELD_CLASS = 16 +private const val FIELD_LINES = 32 + +/** Decodes an MCPG v2 file (see the top of this file); shape `i` gets the id "-". */ +internal fun decodeMcpg( + bytes: ByteArray, + idPrefix: String, +): List { + val header = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + val magic = String(bytes, 0, 4, Charsets.US_ASCII) + require(magic == "MCPG" && header.getInt(4) == 2) { "not an MCPG v2 file" } + val count = header.getInt(8) + val fields = bytes[12].toInt() and 0xFF + val scale = Math.pow(10.0, (bytes[13].toInt() and 0xFF).toDouble()) + var offset = 14 + val lines = (fields and FIELD_LINES) != 0 + + fun varint(): Int { + var value = 0 + var shift = 0 + while (true) { + val b = bytes[offset++].toInt() and 0xFF + value = value or ((b and 0x7F) shl shift) + if (b < 0x80) return value + shift += 7 + } + } + + fun svarint(): Int { + val v = varint() + return (v ushr 1) xor -(v and 1) + } + + var lat = 0 + var lng = 0 + return List(count) { i -> + var height: Double? = null + var use: LandUse? = null + var level = 0 + var name: String? = null + var roadClass: Int? = null + if ((fields and FIELD_HEIGHT) != 0) height = varint().takeIf { it > 0 }?.let { (it - 1) / 10.0 } + if ((fields and FIELD_USE) != 0) use = LandUse.entries[bytes[offset++].toInt() and 0xFF] + if ((fields and FIELD_AREA) != 0) level = bytes[offset++].toInt() and 0xFF + if ((fields and FIELD_NAME) != 0) { + val length = varint() + if (length > 0) name = String(bytes, offset, length, Charsets.UTF_8) + offset += length + } + if ((fields and FIELD_CLASS) != 0) roadClass = bytes[offset++].toInt() and 0xFF + val rings = + List(varint()) { + val n = varint() + // The closing vertex is not stored; it is the first one again. A line is open. + val ring = DoubleArray((if (lines) n else n + 1) * 2) + for (v in 0 until n) { + lat += svarint() + lng += svarint() + ring[v * 2] = lng / scale + ring[v * 2 + 1] = lat / scale + } + if (!lines) { + ring[n * 2] = ring[0] + ring[n * 2 + 1] = ring[1] + } + ring + } + Building( + id = "$idPrefix-$i", + level = level, + height = height, + name = name, + rings = rings, + use = use, + roadClass = roadClass, + ) + } +} + +/** The area of [building] in square metres: its outline less its holes. */ +fun areaSquareMetres(building: Building): Double { + val rings = building.rings.map { ring -> List(ring.size / 2) { GeoPoint(ring[it * 2 + 1], ring[it * 2]) } } + return Spherical.computeArea(rings.first()) - rings.drop(1).sumOf { Spherical.computeArea(it) } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonOverlays.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonOverlays.kt new file mode 100644 index 000000000..adb6d91e5 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/boston/BostonOverlays.kt @@ -0,0 +1,141 @@ +package com.mapconductor.example.pages.polygon.boston + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import java.util.Locale + +/** The land-use colours, two to a row. */ +@Composable +fun LandUseLegend(modifier: Modifier = Modifier) { + Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(2.dp)) { + LandUse.entries.chunked(2).forEach { row -> + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + row.forEach { use -> + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = + Modifier + .size(10.dp) + .background(use.fill, RoundedCornerShape(2.dp)) + .border(1.dp, Color(0x80475569), RoundedCornerShape(2.dp)), + ) + Text(use.label, fontSize = 11.sp, modifier = Modifier.padding(start = 4.dp)) + } + } + } + } + } +} + +private const val MB = 1024.0 * 1024.0 + +/** Covers the map while a dataset loads, saying which phase it is in. */ +@Composable +fun LoadingOverlay( + phase: LoadPhase, + modifier: Modifier = Modifier, + /** What is loading, for the text: "polygons" or "roads". */ + shapes: String = "polygons", +) { + var fraction: Float? = null + val text = + when (phase) { + is LoadPhase.Read -> { + val loaded = String.format(Locale.US, "%.1f", phase.loaded / MB) + val total = phase.total?.takeIf { it > 0 } + if (total != null) { + fraction = (phase.loaded.toFloat() / total).coerceIn(0f, 1f) + "Loading data… $loaded / ${String.format(Locale.US, "%.1f", total / MB)} MB" + } else { + "Loading data… $loaded MB" + } + } + + LoadPhase.Decode -> "Reading the $shapes…" + LoadPhase.Build -> "Preparing the $shapes…" + LoadPhase.Draw -> "Drawing the map…" + } + Box( + modifier = + modifier + .fillMaxSize() + .background(Color(0x590F172A)), + contentAlignment = Alignment.Center, + ) { + Column( + modifier = + Modifier + .width(260.dp) + .background(Color.White, RoundedCornerShape(10.dp)) + .padding(horizontal = 20.dp, vertical = 16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + CircularProgressIndicator(modifier = Modifier.size(28.dp), strokeWidth = 3.dp, color = Color(0xFF2563EB)) + Text(text, fontSize = 14.sp, color = Color(0xFF0F172A)) + fraction?.let { + LinearProgressIndicator(progress = { + it + }, modifier = Modifier.fillMaxWidth(), color = Color(0xFF2563EB)) + } + } + } +} + +/** What a tapped polygon carries, shown in an InfoBubble at the tap. */ +@Composable +fun PolygonInfo(building: Building) { + val rows = mutableListOf>() + val use = building.use + if (use != null) { + rows += "Land use" to use.label + } else { + building.name?.let { rows += "Name" to it } + rows += "Height" to (building.height?.let { "$it m" } ?: "unknown") + } + rows += "Area" to formatArea(areaSquareMetres(building)) + val vertices = building.rings.sumOf { it.size / 2 } + rows += "Vertices" to (if (building.rings.size > 1) "$vertices (holes ${building.rings.size - 1})" else "$vertices") + Column { + rows.forEach { (key, value) -> + Row { + Text( + key, + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + color = Color(0xFF475569), + modifier = Modifier.width(84.dp), + ) + Text(value, fontSize = 12.sp, color = Color(0xFF0F172A)) + } + } + } +} + +/** "1,234 m²", or hectares from 10,000 m² up. */ +fun formatArea(squareMetres: Double): String = + if (squareMetres >= 10_000) { + String.format(Locale.US, "%.2f ha", squareMetres / 10_000) + } else { + String.format(Locale.US, "%,.0f m²", squareMetres) + } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/click/PolygonClickPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/click/PolygonClickPage.kt index 1b2e0e3a6..6726b6909 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polygon/click/PolygonClickPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/click/PolygonClickPage.kt @@ -25,7 +25,10 @@ import com.mapconductor.example.ui.DemoMapPageScaffold import com.mapconductor.example.ui.MessageCard @Composable -fun PolygonClickPage(onToggleSidebar: () -> Unit = {}) { +fun PolygonClickPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel = remember { PolygonClickPageViewModel() } val isDarkTheme = isSystemInDarkTheme() @@ -42,6 +45,7 @@ fun PolygonClickPage(onToggleSidebar: () -> Unit = {}) { mapViewState.value?.let { MapViewContainer( state = it, + modifier = modifier, onMapClick = viewModel::onMapClicked, ) { key(california) { diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/collection/PolygonsMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/collection/PolygonsMapPage.kt new file mode 100644 index 000000000..8778dfe00 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/collection/PolygonsMapPage.kt @@ -0,0 +1,79 @@ +package com.mapconductor.example.pages.polygon.collection + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.calculateEndPadding +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Button +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import com.mapconductor.compose.polygon.Polygons +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.example.ui.MessageCard + +@Composable +fun PolygonsMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val viewModel = remember { PolygonsMapPageViewModel() } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = viewModel::onMapViewChanged, + ) { paddingValues -> + val mapViewState = viewModel.mapViewState.collectAsState() + val states = viewModel.polygonStates.collectAsState() + + mapViewState.value?.let { + MapViewContainer( + state = it, + modifier = modifier.padding(paddingValues), + ) { + Polygons(states.value) + } + } + + Row( + modifier = + Modifier + .align(Alignment.TopStart) + .padding(top = paddingValues.calculateTopPadding() + 16.dp, start = 16.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button(onClick = viewModel::removeRow) { Text("−") } + Button(onClick = viewModel::addRow) { Text("+") } + Button(onClick = viewModel::recolor) { Text("Recolor") } + } + + MessageCard( + title = "Polygons (${states.value.size})", + modifier = + Modifier + .align(Alignment.BottomStart) + .padding( + bottom = paddingValues.calculateBottomPadding() + 16.dp, + start = paddingValues.calculateStartPadding(LayoutDirection.Ltr) + 16.dp, + end = paddingValues.calculateEndPadding(LayoutDirection.Ltr) + 16.dp, + ), + ) { + Text( + """ + A grid of hexagons registered with a single Polygons(states) call. + + / − add or remove a row, Recolor replaces every state with a new fill, + and tapping a hexagon changes its own fill in place. + """.trimIndent(), + ) + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/collection/PolygonsMapPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/collection/PolygonsMapPageViewModel.kt new file mode 100644 index 000000000..de710a60f --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/collection/PolygonsMapPageViewModel.kt @@ -0,0 +1,97 @@ +package com.mapconductor.example.pages.polygon.collection + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.polygon.PolygonEvent +import com.mapconductor.core.polygon.PolygonState +import kotlin.math.cos +import kotlin.math.sin +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +private const val COLUMNS = 10 +private const val SPACING = 0.004 +private val ORIGIN = GeoPoint(35.6895, 139.6917) +private val PALETTE = + listOf( + Color(0x664285F4), + Color(0x66EA4335), + Color(0x66FBBC05), + Color(0x6634A853), + ) +private val TAPPED = Color(0xCC9C27B0) + +class PolygonsMapPageViewModel : ViewModel() { + private val _mapViewState = MutableStateFlow?>(null) + val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + val initCameraPosition = + MapCameraPosition( + position = GeoPoint(ORIGIN.latitude - 0.006, ORIGIN.longitude + 0.018), + zoom = 14.0, + ) + + private var rows = 3 + private var paletteIndex = 0 + + private val _polygonStates = MutableStateFlow(buildStates()) + val polygonStates: StateFlow> = _polygonStates.asStateFlow() + + fun onMapViewChanged(state: MapViewStateInterface<*>) { + _mapViewState.value = state + } + + fun addRow() { + rows++ + _polygonStates.value = _polygonStates.value + buildRow(rows - 1) + } + + fun removeRow() { + if (rows == 0) return + rows-- + _polygonStates.value = _polygonStates.value.dropLast(COLUMNS) + } + + // New state objects with the same ids: the collection must replace them, not add. + fun recolor() { + paletteIndex = (paletteIndex + 1) % PALETTE.size + _polygonStates.value = buildStates() + } + + private fun buildStates(): List = (0 until rows).flatMap(::buildRow) + + private fun buildRow(row: Int): List = + (0 until COLUMNS).map { column -> + val center = + GeoPoint( + ORIGIN.latitude - row * SPACING, + ORIGIN.longitude + column * SPACING + if (row % 2 == 1) SPACING / 2 else 0.0, + ) + PolygonState( + points = hexagon(center, SPACING * 0.45), + id = "hex-$row-$column", + strokeColor = Color.DarkGray, + strokeWidth = 1.dp, + fillColor = PALETTE[(paletteIndex + row + column) % PALETTE.size], + onClick = ::onPolygonClick, + ) + } + + private fun onPolygonClick(event: PolygonEvent) { + event.state.fillColor = TAPPED + } + + private fun hexagon( + center: GeoPoint, + radius: Double, + ): List = + (0..6).map { i -> + val angle = Math.toRadians(60.0 * i) + GeoPoint(center.latitude + radius * sin(angle), center.longitude + radius * cos(angle)) + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/geodesic/PolygonGeodesicPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/geodesic/PolygonGeodesicPage.kt index e461cba42..8fca5b7b7 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polygon/geodesic/PolygonGeodesicPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/geodesic/PolygonGeodesicPage.kt @@ -25,7 +25,10 @@ import com.mapconductor.example.ui.DemoMapPageScaffold import com.mapconductor.example.ui.MessageCard @Composable -fun PolygonGeodesicPage(onToggleSidebar: () -> Unit = {}) { +fun PolygonGeodesicPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel = remember { PolygonGeodesicPageViewModel() } val isDarkTheme = isSystemInDarkTheme() @@ -75,6 +78,7 @@ fun PolygonGeodesicPage(onToggleSidebar: () -> Unit = {}) { mapViewState.value?.let { MapViewContainer( state = it, + modifier = modifier.padding(paddingValues), ) { Polygon(polylineState) Polygon(geodesicPolylineState) diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polygon/hole/HolePolygonMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polygon/hole/HolePolygonMapPage.kt index f4d630c1e..68152502d 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polygon/hole/HolePolygonMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polygon/hole/HolePolygonMapPage.kt @@ -19,7 +19,10 @@ import com.mapconductor.example.ui.DemoMapPageScaffold import com.mapconductor.example.ui.MessageCard @Composable -fun HolePolygonMapPage(onToggleSidebar: () -> Unit = {}) { +fun HolePolygonMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel = remember { HolePolygonMapPageViewModel() } DemoMapPageScaffold( @@ -33,6 +36,7 @@ fun HolePolygonMapPage(onToggleSidebar: () -> Unit = {}) { MapViewContainer( state = it, cameraRestriction = viewModel.cameraRestriction, + modifier = modifier.padding(paddingValues), ) { Polygon(viewModel.polygonState) viewModel.holeVertexMarkers.forEach { marker -> diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylineMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylineMapComponent.kt index 3281f9adb..88bc2eec8 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylineMapComponent.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylineMapComponent.kt @@ -16,7 +16,7 @@ fun PolylineMapComponent( wayPointMarkers: List, modifier: Modifier = Modifier, ) { - mapViewState?.let { it -> + mapViewState?.let { MapViewContainer( modifier = modifier, state = it, diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylineMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylineMapPage.kt index 2ebd75d0d..32b1f4c0f 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylineMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylineMapPage.kt @@ -1,25 +1,31 @@ package com.mapconductor.example.pages.polyline +import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier import com.mapconductor.example.ui.DefaultMapViewItems import com.mapconductor.example.ui.DemoMapPageScaffold @Composable -fun PolylineMapPage(onToggleSidebar: () -> Unit = {}) { +fun PolylineMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel = remember { PolylinePageViewModel() } DemoMapPageScaffold( menuItems = DefaultMapViewItems(viewModel.initCameraPosition), onToggleSidebar = onToggleSidebar, onMapViewStateChanged = viewModel::onMapViewChanged, - ) { + ) { paddings -> val mapViewState = viewModel.mapViewState.collectAsState() PolylineMapComponent( polylineState = viewModel.polylineState, wayPointMarkers = viewModel.wayPointMarkers, mapViewState = mapViewState.value, + modifier = modifier.padding(paddings), ) } } diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylinePageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylinePageViewModel.kt index 6d779e467..6c08bd4b7 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylinePageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/basic/PolylinePageViewModel.kt @@ -1,117 +1,117 @@ -package com.mapconductor.example.pages.polyline - -import androidx.compose.runtime.mutableStateListOf -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.dp -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.polyline.PolylineState -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -interface PolylinePageViewModelInterface { - val initCameraPosition: MapCameraPosition - val mapViewState: StateFlow?> - - val wayPointMarkers: List - val polylineState: PolylineState - - fun onMapViewChanged(state: MapViewStateInterface<*>) - - fun onMarkerDrag(dragged: MarkerState) -} - -class PolylinePageViewModel : - ViewModel(), - PolylinePageViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 21.382314, - longitude = -157.933097, - ), - zoom = 15.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - - private val polylinePoints = - mutableStateListOf( - GeoPoint.fromLatLong(21.382314, -157.933097), // Honolulu center - GeoPoint.fromLatLong(21.385314, -157.930097), // Northeast - GeoPoint.fromLatLong(21.387314, -157.935097), // Northwest - GeoPoint.fromLatLong(21.380314, -157.937097), // Southwest - GeoPoint.fromLatLong(21.378314, -157.930097), // Southeast - GeoPoint.fromLatLong(21.382314, -157.933097), // Back to center - ) - - override val wayPointMarkers: List = - polylinePoints.mapIndexed { index, point -> - val markerColor = - when { - index == 0 -> Color.Green - index == polylinePoints.size - 1 -> Color.Green - else -> Color.Yellow - } - val label = - when { - index == 0 -> "S" - index == polylinePoints.size - 1 -> "E" - else -> "$index" - } - MarkerState( - id = "waypoint_$index", - position = point, - icon = - DefaultMarkerIcon( - fillColor = markerColor, - strokeColor = Color.Black, - label = label, - ), - draggable = true, - extra = index, - onDragStart = this::onMarkerDrag, - onDrag = this::onMarkerDrag, - onDragEnd = this::onMarkerDrag, - ) - } - - override val polylineState: PolylineState - get() = - PolylineState( - id = "example_polyline", - points = polylinePoints, - strokeColor = Color.Red, - strokeWidth = 4.dp, - geodesic = true, - ) - - private val _mapViewState = MutableStateFlow?>(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - override fun onMapViewChanged(state: MapViewStateInterface<*>) { - mapViewState.value?.cameraPosition?.let { - state.moveCameraTo(it) - } - this._mapViewState.value = state - } - - override fun onMarkerDrag(dragged: MarkerState) { - (dragged.extra as? Int)?.let { index -> - if (index >= 0 && index < polylinePoints.size) { - polylinePoints[index] = GeoPoint.from(dragged.position) - } - } - } - - override fun onCleared() { - super.onCleared() - } -} +package com.mapconductor.example.pages.polyline + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.polyline.PolylineState +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +interface PolylinePageViewModelInterface { + val initCameraPosition: MapCameraPosition + val mapViewState: StateFlow?> + + val wayPointMarkers: List + val polylineState: PolylineState + + fun onMapViewChanged(state: MapViewStateInterface<*>) + + fun onMarkerDrag(dragged: MarkerState) +} + +class PolylinePageViewModel : + ViewModel(), + PolylinePageViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 21.382314, + longitude = -157.933097, + ), + zoom = 15.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + + // Kept as a read-only list and replaced as a whole on every drag: PolylineState + // only hears assignments to its fields, so editing a list it already holds in + // place would never reach the map. + private var polylinePoints: List = + listOf( + GeoPoint.fromLatLong(21.382314, -157.933097), // Honolulu center + GeoPoint.fromLatLong(21.385314, -157.930097), // Northeast + GeoPoint.fromLatLong(21.387314, -157.935097), // Northwest + GeoPoint.fromLatLong(21.380314, -157.937097), // Southwest + GeoPoint.fromLatLong(21.378314, -157.930097), // Southeast + GeoPoint.fromLatLong(21.382314, -157.933097), // Back to center + ) + + override val wayPointMarkers: List = + polylinePoints.mapIndexed { index, point -> + val markerColor = + when { + index == 0 -> Color.Green + index == polylinePoints.size - 1 -> Color.Green + else -> Color.Yellow + } + val label = + when { + index == 0 -> "S" + index == polylinePoints.size - 1 -> "E" + else -> "$index" + } + MarkerState( + id = "waypoint_$index", + position = point, + icon = + DefaultMarkerIcon( + fillColor = markerColor, + strokeColor = Color.Black, + label = label, + ), + draggable = true, + extra = index, + onDragStart = this::onMarkerDrag, + onDrag = this::onMarkerDrag, + onDragEnd = this::onMarkerDrag, + ) + } + + override val polylineState = + PolylineState( + id = "example_polyline", + points = polylinePoints, + strokeColor = Color.Red, + strokeWidth = 4.dp, + geodesic = true, + ) + + private val _mapViewState = MutableStateFlow?>(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + override fun onMapViewChanged(state: MapViewStateInterface<*>) { + mapViewState.value?.cameraPosition?.let { + state.moveCameraTo(it) + } + this._mapViewState.value = state + } + + override fun onMarkerDrag(dragged: MarkerState) { + (dragged.extra as? Int)?.let { index -> + if (index !in polylinePoints.indices) return + polylinePoints = + polylinePoints.mapIndexed { i, point -> + if (i == index) GeoPoint.from(dragged.position) else point + } + polylineState.points = polylinePoints + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsData.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsData.kt new file mode 100644 index 000000000..ada8a5779 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsData.kt @@ -0,0 +1,87 @@ +package com.mapconductor.example.pages.polyline.boston + +import androidx.compose.ui.graphics.Color +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.spherical.Spherical +import com.mapconductor.example.pages.polygon.boston.LoadPhase +import com.mapconductor.example.pages.polygon.boston.decodeMcpg +import android.content.Context + +/** + * The roads the Boston roads page draws: every road of the city, from Overture + * Maps `transportation/segment` (road subtype), cut at the city boundary. 54,645 + * polylines, 234,765 points, about 1 MB. + * + * Bundled as assets/boston/boston-city-roads.bin. The React sample's + * `examples/basic/tools/boston/` builds it (`pack.py roads`, see its README for + * the source, licence and why not Analyze Boston's street centerlines). The file + * carries no ids: this is a polyline demo, and a road's id on the map is its + * index in the file. + * + * The format is the polygons' MCPG v2 (see BostonData.kt) with two more header + * bits: 16, the road class (u8, after the name), and 32, lines: each record's + * one "ring" is an open polyline, every vertex stored, never closed by the + * reader. Coordinates are 1e-5 degree; points almost on a straight line (0.5 m) + * are left out, the ends kept. + */ +const val ROADS_FILE = "boston/boston-city-roads.bin" + +const val ROADS_ATTRIBUTION = + "© OpenStreetMap contributors, TomTom — via Overture Maps Foundation (ODbL 1.0)" + +/** + * A road's class (the file's index, grouped from Overture's segment classes) and + * how the page draws it: bigger roads wider, brighter and on top. The same table + * on the web and iOS. + */ +enum class RoadClass( + val label: String, + val color: Color, + /** dp. */ + val width: Float, + val zIndex: Int, +) { + HIGHWAY("Highway", Color(0xFFE8590C), 5f, 6), + PRIMARY("Primary", Color(0xFFF08C00), 4f, 5), + SECONDARY("Secondary", Color(0xFFFAB005), 3.5f, 4), + TERTIARY("Tertiary", Color(0xFFFFD43B), 3f, 3), + LOCAL("Local", Color(0xFF868E96), 2f, 2), + SERVICE("Service", Color(0xFFADB5BD), 1.5f, 1), + PATH("Path", Color(0xFF74B816), 1f, 0), +} + +class Road( + val id: String, + val roadClass: RoadClass, + val name: String?, + /** `[lng0, lat0, lng1, lat1, ...]`, open. */ + val path: DoubleArray, +) { + val points: List get() = List(path.size / 2) { GeoPoint(path[it * 2 + 1], path[it * 2]) } +} + +/** Decodes the roads file: MCPG v2 with the road class and lines bits; road `i` gets the id "road-". */ +fun decodeRoads(bytes: ByteArray): List = + decodeMcpg(bytes, "road").map { shape -> + Road( + id = shape.id, + roadClass = RoadClass.entries[shape.roadClass ?: RoadClass.LOCAL.ordinal], + name = shape.name, + path = shape.rings.single(), + ) + } + +fun loadBostonRoads( + context: Context, + onProgress: (LoadPhase) -> Unit = {}, +): List { + val length = runCatching { context.assets.openFd(ROADS_FILE).use { it.length } }.getOrNull() + onProgress(LoadPhase.Read(0, length)) + val bytes = context.assets.open(ROADS_FILE).use { it.readBytes() } + onProgress(LoadPhase.Read(bytes.size.toLong(), length)) + onProgress(LoadPhase.Decode) + return decodeRoads(bytes) +} + +/** The road's length in metres: the geodesic length of its points. */ +fun lengthMetres(road: Road): Double = Spherical.computeLength(road.points) diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsPage.kt new file mode 100644 index 000000000..906ffa168 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsPage.kt @@ -0,0 +1,280 @@ +package com.mapconductor.example.pages.polyline.boston + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.calculateEndPadding +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Button +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.compose.MapViewScope +import com.mapconductor.compose.circle.Circle +import com.mapconductor.compose.info.InfoBubble +import com.mapconductor.compose.marker.Marker +import com.mapconductor.compose.polygon.Polygons +import com.mapconductor.compose.polyline.PolylineTiling +import com.mapconductor.compose.polyline.Polylines +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.pages.polygon.boston.LoadingOverlay +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.example.ui.MessageCard +import java.util.Locale +import android.app.Activity + +@Composable +fun BostonRoadsPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val context = LocalContext.current + // `adb shell am start ... --es page boston-roads --es camera "42.3555,-71.0605,15" --es tiling off` + // opens a fixed view, so a measurement sees the same thing on every provider. + val viewModel = + remember { + val intent = (context as? Activity)?.intent + BostonRoadsViewModel( + context = context.applicationContext, + initCamera = intent?.getStringExtra("camera"), + initTiling = + when (intent?.getStringExtra("tiling")) { + "off" -> false + "on" -> true + else -> null + }, + initOverlap = intent?.getStringExtra("overlap") == "on", + ) + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(viewModel.initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = viewModel::onMapViewChanged, + ) { paddingValues -> + val mapViewState = viewModel.mapViewState.collectAsState() + val states = viewModel.polylineStates.collectAsState() + val tiling = viewModel.tiling.collectAsState() + val overlap = viewModel.overlap.collectAsState() + val loadError = viewModel.loadError.collectAsState() + val stats = viewModel.stats.collectAsState() + val tap = viewModel.tap.collectAsState() + val progress = viewModel.progress.collectAsState() + + // Two frames after the list reaches Polylines(), for the stats. The loading overlay waits for onAdded. + LaunchedEffect(states.value) { + val shown = states.value + withFrameNanos {} + withFrameNanos {} + viewModel.onDrawn(shown) + } + + mapViewState.value?.let { + MapViewContainer( + state = it, + modifier = modifier.padding(paddingValues), + onMapClick = viewModel::onMapClick, + ) { + // Before Polylines(): read when the roads are handed over. + PolylineTiling(viewModel.tilingOptions(tiling.value)) + Polylines(states.value) + if (overlap.value) OverlapCheck() + val shownTap = tap.value + val road = shownTap?.road + val point = shownTap?.point + if (road != null && point != null) { + InfoBubble(position = point, borderWidth = 1.dp, borderColor = Color(0x33000000)) { + RoadInfo(road) + } + } + } + } + + progress.value?.let { LoadingOverlay(it, modifier = Modifier.padding(paddingValues), shapes = "roads") } + + Column( + modifier = + Modifier + .align(Alignment.TopStart) + .padding(top = paddingValues.calculateTopPadding() + 16.dp, start = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(true to "Tiles", false to "Native").forEach { (tiled, label) -> + if (tiling.value == tiled) { + Button(onClick = {}) { Text(label) } + } else { + FilledTonalButton(onClick = { viewModel.setTiling(tiled) }) { Text(label) } + } + } + if (overlap.value) { + Button(onClick = { viewModel.setOverlap(false) }) { Text("Overlap check") } + } else { + FilledTonalButton(onClick = { viewModel.setOverlap(true) }) { Text("Overlap check") } + } + } + } + + MessageCard( + title = + stats.value?.let { "Boston roads: ${it.roads} polylines, ${it.points} points" } + ?: "Boston roads", + isCardOpen = true, + maxHeight = 300.dp, + modifier = + Modifier + .align(Alignment.BottomStart) + .widthIn(max = 480.dp) + .padding( + bottom = paddingValues.calculateBottomPadding() + 16.dp, + start = paddingValues.calculateStartPadding(LayoutDirection.Ltr) + 16.dp, + end = paddingValues.calculateEndPadding(LayoutDirection.Ltr) + 16.dp, + ), + ) { + loadError.value?.let { Text(it) } + RoadClassLegend(modifier = Modifier.padding(vertical = 4.dp)) + stats.value?.let { + val how = if (it.tiled) "tiles" else "native" + val frame = it.frameMillis?.let { ms -> ", next frame $ms ms" } ?: "" + val added = it.addedMillis?.let { ms -> ", on the map $ms ms" } ?: "" + Text("[$how] Load ${it.loadMillis} ms, states ${it.buildMillis} ms$frame$added") + } + tap.value?.let { tap -> + val road = tap.road + Text( + if (road == null) { + "No road here" + } else { + "${road.name ?: road.roadClass.label} · ${road.roadClass.label} · ${ + formatLength( + lengthMetres( + road, + ), + ) + }" + }, + ) + } + Text(ROADS_ATTRIBUTION, fontSize = 11.sp) + } + } +} + +/** The road classes: a line as wide and as coloured as on the map, two to a row. */ +@Composable +fun RoadClassLegend(modifier: Modifier = Modifier) { + Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(2.dp)) { + RoadClass.entries.chunked(2).forEach { row -> + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + row.forEach { roadClass -> + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = + Modifier + .width(18.dp) + .height(roadClass.width.dp) + .background(roadClass.color, RoadedEnds), + ) + Text(roadClass.label, fontSize = 11.sp, modifier = Modifier.padding(start = 6.dp)) + } + } + if (row.size == 1) Box(modifier = Modifier.weight(1f)) + } + } + } +} + +private val RoadedEnds = RoundedCornerShape(50) + +/** What a tapped road carries, shown in an InfoBubble at the point on the road nearest the tap. */ +@Composable +fun RoadInfo(road: Road) { + val rows = mutableListOf>() + rows += "Class" to road.roadClass.label + road.name?.let { rows += "Name" to it } + rows += "Length" to formatLength(lengthMetres(road)) + rows += "Points" to "${road.path.size / 2}" + Column { + rows.forEach { (key, value) -> + Row { + Text( + key, + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + color = Color(0xFF475569), + modifier = Modifier.width(64.dp), + ) + Text(value, fontSize = 12.sp, color = Color(0xFF0F172A)) + } + } + } +} + +/** "123 m", or kilometres from 1,000 m up. */ +fun formatLength(metres: Double): String = + if (metres >= 1000) { + String.format(Locale.US, "%.2f km", metres / 1000) + } else { + String.format(Locale.US, "%,.0f m", metres) + } + +/** + * The stacking check: over the roads downtown, a grid of 2,500 small polygons + * (enough to be drawn as polygon tiles), a circle and a marker. From the bottom + * the map shows polygon tiles, the circle, the road tiles, then the marker. + */ +@Composable +private fun MapViewScope.OverlapCheck() { + val polygons = + remember { + List(2500) { i -> + val lat = 42.3500 + (i / 50) * 0.0002 + val lng = -71.0660 + (i % 50) * 0.0002 + PolygonState( + points = + listOf( + GeoPoint(lat, lng), + GeoPoint(lat, lng + 0.00016), + GeoPoint(lat + 0.00016, lng + 0.00016), + GeoPoint(lat + 0.00016, lng), + ), + id = "overlap-$i", + fillColor = Color(0xCC7C3AED), + strokeColor = Color(0xFF4C1D95), + strokeWidth = 1.dp, + ) + } + } + Polygons(polygons) + Circle( + center = GeoPoint(42.3550, -71.0610), + radiusMeters = 250.0, + id = "overlap-circle", + fillColor = Color(0xCC0EA5E9), + strokeColor = Color(0xFF0369A1), + ) + Marker(position = GeoPoint(42.3550, -71.0610), id = "overlap-marker") +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsViewModel.kt new file mode 100644 index 000000000..9911d0e4f --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsViewModel.kt @@ -0,0 +1,242 @@ +package com.mapconductor.example.pages.polyline.boston + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.core.polyline.PolylineTilingOptions +import com.mapconductor.example.pages.polygon.boston.LoadPhase +import android.content.Context +import android.os.SystemClock +import android.util.Log +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +private const val LOG_TAG = "BostonRoads" +private val TAPPED = Color(0xFF2563EB) + +/** What the last tap hit: a road, or nothing (`road` null), and the point on the road nearest the tap. */ +data class RoadTap( + val seq: Int, + val road: Road?, + val point: GeoPoint?, +) + +data class RoadStats( + val roads: Int, + val points: Int, + val tiled: Boolean, + val loadMillis: Long, + val buildMillis: Long, + /** From handing the list to Polylines() until two frames later; null until then. */ + val frameMillis: Long? = null, + /** From handing the list to Polylines() until the map had all of it (every onAdded); null until then. */ + val addedMillis: Long? = null, +) + +/** + * Every road of Boston (Overture Maps, 54,645 polylines) drawn on the real map + * with one Polylines() call: the polyline counterpart of the Boston buildings + * page. Past the tiling threshold the SDK draws them as raster tiles; the + * "Tiles" switch turns that off for this map ([PolylineTilingOptions.Disabled]) + * so the two can be compared, and reloads the roads so the time from handing + * them over to the last onAdded is measured again. + * + * Roads are coloured, widened and stacked by class ([RoadClass]). Tapping a road + * highlights it (an in-place change: only the tiles it is in are drawn again) + * and shows its class, name and length in an InfoBubble at the point on the road + * nearest the tap; tapping elsewhere closes it. Taps, loads and the time to the + * last onAdded are logged under `BostonRoads`. + * + * "Overlap check" adds a tiled set of polygons, a circle and a marker over the + * roads downtown, to see the stacking: polygon tiles < circles < polyline tiles + * < markers. + * + * `camera` ("lat,lng,zoom") and `tiling` ("on" / "off") come from the intent + * extras, so a measurement opens the same view on every provider. + */ +class BostonRoadsViewModel( + private val context: Context, + initCamera: String?, + initTiling: Boolean?, + initOverlap: Boolean, +) : ViewModel() { + private val _mapViewState = MutableStateFlow?>(null) + val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + val initCameraPosition: MapCameraPosition = + initCamera + ?.split(',') + ?.mapNotNull { it.trim().toDoubleOrNull() } + ?.takeIf { it.size == 3 } + ?.let { (lat, lng, zoom) -> MapCameraPosition(position = GeoPoint(lat, lng), zoom = zoom) } + ?: MapCameraPosition(position = GeoPoint(42.3555, -71.0605), zoom = 14.0) + + private val _tiling = MutableStateFlow(initTiling ?: true) + + /** Whether this map may draw the roads as tiles (else every road is a native polyline). */ + val tiling: StateFlow = _tiling.asStateFlow() + + private val _overlap = MutableStateFlow(initOverlap) + val overlap: StateFlow = _overlap.asStateFlow() + + private val _loadError = MutableStateFlow(null) + val loadError: StateFlow = _loadError.asStateFlow() + + private val _polylineStates = MutableStateFlow>(emptyList()) + val polylineStates: StateFlow> = _polylineStates.asStateFlow() + + private val _stats = MutableStateFlow(null) + val stats: StateFlow = _stats.asStateFlow() + + private val _tap = MutableStateFlow(null) + val tap: StateFlow = _tap.asStateFlow() + + /** Non-null while the roads are on their way; drives the loading overlay. */ + private val _progress = MutableStateFlow(null) + val progress: StateFlow = _progress.asStateFlow() + + private var shownAt = 0L + + /** Which load the roads' onAdded belongs to; a callback from an earlier load is ignored. */ + private var generation = 0 + + /** The ids of this load that have reached the map, from their states' onAdded. */ + private var addedIds = HashSet() + private var listSize = 0 + private var waitingForAdds = false + private var highlighted: Pair? = null + + init { + load() + } + + /** The options for this map's [com.mapconductor.compose.polyline.PolylineTiling]. */ + fun tilingOptions(tiled: Boolean): PolylineTilingOptions = + if (tiled) PolylineTilingOptions.Default else PolylineTilingOptions.Disabled + + fun setTiling(tiled: Boolean) { + if (_tiling.value == tiled) return + _tiling.value = tiled + // The roads leave the map and come back, drawn the other way; timed again. + load() + } + + fun setOverlap(on: Boolean) { + _overlap.value = on + } + + fun onMapViewChanged(state: MapViewStateInterface<*>) { + _mapViewState.value = state + } + + fun onMapClick(point: GeoPointInterface) { + onTap(null, null, point) + } + + private fun load() { + val gen = ++generation + addedIds = HashSet() + listSize = 0 + waitingForAdds = false + _polylineStates.value = emptyList() + _stats.value = null + _loadError.value = null + _tap.value = null + highlighted = null + _progress.value = LoadPhase.Read(0, null) + val tiled = _tiling.value + viewModelScope.launch { + val started = SystemClock.elapsedRealtime() + val roads = + try { + withContext(Dispatchers.IO) { + loadBostonRoads(context) { phase -> _progress.value = phase } + } + } catch (e: Exception) { + _progress.value = null + _loadError.value = e.message + return@launch + } + val loadMillis = SystemClock.elapsedRealtime() - started + _progress.value = LoadPhase.Build + val built = SystemClock.elapsedRealtime() + val onAdded: (PolylineState) -> Unit = { state -> onRoadAdded(gen, state.id) } + val states = withContext(Dispatchers.Default) { roads.map { toState(it, onAdded) } } + if (gen != generation) return@launch + val buildMillis = SystemClock.elapsedRealtime() - built + val points = states.sumOf { it.points.size } + _stats.value = RoadStats(states.size, points, tiled, loadMillis, buildMillis) + Log.i(LOG_TAG, "shown roads=${states.size} points=$points tiled=$tiled load=$loadMillis build=$buildMillis") + listSize = states.size + waitingForAdds = true + _progress.value = LoadPhase.Draw + shownAt = SystemClock.elapsedRealtime() + _polylineStates.value = states + } + } + + // Runs on the main thread, once per road each time the map takes it in. + private fun onRoadAdded( + gen: Int, + id: String, + ) { + if (gen != generation || !addedIds.add(id)) return + if (!waitingForAdds || addedIds.size < listSize) return + waitingForAdds = false + _progress.value = null + val added = SystemClock.elapsedRealtime() - shownAt + _stats.value = _stats.value?.copy(addedMillis = added) + Log.i(LOG_TAG, "added roads=$listSize tiled=${_tiling.value} added=$added") + } + + /** The page calls this two frames after the list reached Polylines(). */ + fun onDrawn(states: List) { + if (states.isEmpty() || states !== _polylineStates.value) return + val frame = SystemClock.elapsedRealtime() - shownAt + _stats.value = _stats.value?.copy(frameMillis = frame) + Log.i(LOG_TAG, "drawn roads=${states.size} tiled=${_tiling.value} frame=$frame") + } + + // Moves the highlight to `state` (or clears it) and records the tap. + private fun onTap( + state: PolylineState?, + road: Road?, + point: GeoPointInterface?, + ) { + highlighted?.let { (previous, color) -> previous.strokeColor = color } + highlighted = state?.let { it to it.strokeColor } + state?.strokeColor = TAPPED + val seq = (_tap.value?.seq ?: 0) + 1 + _tap.value = RoadTap(seq, road, point?.let { GeoPoint(it.latitude, it.longitude) }) + Log.i( + LOG_TAG, + "tap seq=$seq id=${road?.id ?: ""} class=${road?.roadClass ?: ""} " + + "lat=${point?.latitude ?: ""} lng=${point?.longitude ?: ""}", + ) + } + + private fun toState( + road: Road, + onAdded: (PolylineState) -> Unit, + ): PolylineState = + PolylineState( + points = road.points, + id = road.id, + strokeColor = road.roadClass.color, + strokeWidth = road.roadClass.width.dp, + zIndex = road.roadClass.zIndex, + extra = road.id, + onClick = { event -> onTap(event.state, road, event.clicked) }, + onAdded = onAdded, + ) +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickMapComponent.kt index 16e22e1b0..c3c17fb14 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickMapComponent.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickMapComponent.kt @@ -17,7 +17,7 @@ fun PolylineClickMapComponent( markers: List, modifier: Modifier = Modifier, ) { - mapViewState?.let { it -> + mapViewState?.let { MapViewContainer( modifier = modifier, state = it, diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickMapPage.kt index d3ff408de..3bcdbe743 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickMapPage.kt @@ -16,7 +16,10 @@ import com.mapconductor.example.ui.DemoMapPageScaffold import com.mapconductor.example.ui.MessageCard @Composable -fun PolylineClickMapPage(onToggleSidebar: () -> Unit = {}) { +fun PolylineClickMapPage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { val viewModel = remember { PolylineClickPageViewModel() } DemoMapPageScaffold( menuItems = DefaultMapViewItems(viewModel.initCameraPosition), @@ -29,6 +32,7 @@ fun PolylineClickMapPage(onToggleSidebar: () -> Unit = {}) { polylineState = viewModel.polylineState, markers = markers.value, mapViewState = mapViewState.value, + modifier = modifier.padding(paddingValues), ) MessageCard( diff --git a/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickPageViewModel.kt index f7c0cb4a4..2aaf36076 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/polyline/click/PolylineClickPageViewModel.kt @@ -1,92 +1,86 @@ -package com.mapconductor.example.pages.polyline - -import androidx.compose.runtime.mutableStateListOf -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.dp -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerAnimation -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.polyline.PolylineEvent -import com.mapconductor.core.polyline.PolylineState -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -interface PolylineClickPageViewModelInterface { - val initCameraPosition: MapCameraPosition - val mapViewState: StateFlow?> - - val markers: StateFlow> - val polylineState: PolylineState - - fun onMapViewChanged(state: MapViewStateInterface<*>) - - fun onPolylineClicked(clicked: PolylineEvent) -} - -class PolylineClickPageViewModel : - ViewModel(), - PolylineClickPageViewModelInterface { - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong(35.548852, 139.784086), - zoom = 4.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - - private val polylinePoints = - mutableStateListOf( - GeoPoint.fromLatLong(35.548852, 139.784086), // HND_AIR_PORT - GeoPoint.fromLatLong(37.615223, -122.389979), // SFO_AIR_PORT - GeoPoint.fromLatLong(21.324513, -157.925074), // HNL_AIR_PORT - ) - - private var _markers: MutableStateFlow> = MutableStateFlow(emptyList()) - - override val markers: StateFlow> = _markers.asStateFlow() - - override val polylineState: PolylineState - get() = - PolylineState( - id = "example_polyline", - points = polylinePoints, - strokeColor = Color.Red, - strokeWidth = 4.dp, - geodesic = true, - onClick = this::onPolylineClicked, - ) - - private val _mapViewState = MutableStateFlow?>(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - override fun onMapViewChanged(state: MapViewStateInterface<*>) { - _markers.value = emptyList() - mapViewState.value?.cameraPosition?.let { - state.moveCameraTo(it) - } - this._mapViewState.value = state - } - - override fun onPolylineClicked(clicked: PolylineEvent) { - _markers.value = _markers.value + - MarkerState( - position = clicked.clicked, - animation = MarkerAnimation.Drop, - icon = - DefaultMarkerIcon( - fillColor = clicked.state.strokeColor, - ), - ) - } - - override fun onCleared() { - super.onCleared() - } -} +package com.mapconductor.example.pages.polyline + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerAnimation +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.polyline.PolylineEvent +import com.mapconductor.core.polyline.PolylineState +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +interface PolylineClickPageViewModelInterface { + val initCameraPosition: MapCameraPosition + val mapViewState: StateFlow?> + + val markers: StateFlow> + val polylineState: PolylineState + + fun onMapViewChanged(state: MapViewStateInterface<*>) + + fun onPolylineClicked(clicked: PolylineEvent) +} + +class PolylineClickPageViewModel : + ViewModel(), + PolylineClickPageViewModelInterface { + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong(35.548852, 139.784086), + zoom = 4.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + + private val polylinePoints = + listOf( + GeoPoint.fromLatLong(35.548852, 139.784086), // HND_AIR_PORT + GeoPoint.fromLatLong(37.615223, -122.389979), // SFO_AIR_PORT + GeoPoint.fromLatLong(21.324513, -157.925074), // HNL_AIR_PORT + ) + + private var _markers: MutableStateFlow> = MutableStateFlow(emptyList()) + + override val markers: StateFlow> = _markers.asStateFlow() + + override val polylineState = + PolylineState( + id = "example_polyline", + points = polylinePoints, + strokeColor = Color.Red, + strokeWidth = 4.dp, + geodesic = true, + onClick = this::onPolylineClicked, + ) + + private val _mapViewState = MutableStateFlow?>(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + override fun onMapViewChanged(state: MapViewStateInterface<*>) { + _markers.value = emptyList() + mapViewState.value?.cameraPosition?.let { + state.moveCameraTo(it) + } + this._mapViewState.value = state + } + + override fun onPolylineClicked(clicked: PolylineEvent) { + _markers.value = _markers.value + + MarkerState( + position = clicked.clicked, + animation = MarkerAnimation.Drop, + icon = + DefaultMarkerIcon( + fillColor = clicked.state.strokeColor, + ), + ) + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterHeaderProbePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterHeaderProbePage.kt index 6c64bbeb4..b53fb66c7 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterHeaderProbePage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterHeaderProbePage.kt @@ -1,78 +1,85 @@ -package com.mapconductor.example.pages.rasterlayer - -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.raster.RasterLayerSource -import com.mapconductor.core.raster.RasterLayerState -import com.mapconductor.example.ui.DefaultMapViewItems -import com.mapconductor.example.ui.DemoMapPageScaffold - -/** - * `RasterHeaderInstrumentedTest` が使う計測ページ。 - * - * `RasterLayerState` の `userAgent` / `extraHeaders` が**実際にタイル要求に載るか**を - * プロバイダごとに確かめる。タイルの取得はプロバイダのネイティブ SDK が握っているので、 - * 送り出す側のコードを読んでも「載っているか」は分からない。受け取る側を立てて - * 届いたヘッダをそのまま読む。 - * - * タイルの配信元 URL は [probeTemplate] にテストが入れる。Android の計装テストは - * アプリと**同じプロセス**で動くので、テスト側で立てたサーバの URL をそのまま渡せる。 - * - * ページを別に用意しているのは、通常の `RasterLayerMapPage` は地理院タイルを見に行く - * ためで、計測には使えないから。プロバイダの選択は `--es provider ` に従う - * ([DemoMapPageScaffold] が見る既存の仕組み)。 - */ -@Composable -fun RasterHeaderProbePage(onToggleSidebar: () -> Unit = {}) { - val camera = - remember { - MapCameraPosition( - position = GeoPoint(latitude = 35.681236, longitude = 139.767125), - zoom = 8.0, - ) - } - val rasterLayerState = - remember { - RasterLayerState( - source = - RasterLayerSource.UrlTemplate( - template = probeTemplate ?: "http://127.0.0.1:1/tiles/{z}/{x}/{y}.png", - tileSize = 256, - ), - userAgent = probeUserAgent, - extraHeaders = probeExtraHeaders, - id = "raster_header_probe", - ) - } - - var mapViewState by remember { mutableStateOf?>(null) } - - DemoMapPageScaffold( - menuItems = DefaultMapViewItems(camera), - onToggleSidebar = onToggleSidebar, - onMapViewStateChanged = { mapViewState = it }, - ) { - RasterLayerMapComponent( - mapViewState = mapViewState, - rasterLayerState = rasterLayerState, - modifier = Modifier.fillMaxSize(), - ) - } -} - -/** テストが立てた計測サーバの URL テンプレート。 */ -var probeTemplate: String? = null - -/** 送信を期待する User-Agent。 */ -var probeUserAgent: String = RasterLayerState.DEFAULT_USER_AGENT - -/** 送信を期待する追加ヘッダ。 */ -var probeExtraHeaders: Map? = null +package com.mapconductor.example.pages.rasterlayer + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold + +/** + * `RasterHeaderInstrumentedTest` が使う計測ページ。 + * + * `RasterLayerState` の `userAgent` / `extraHeaders` が**実際にタイル要求に載るか**を + * プロバイダごとに確かめる。タイルの取得はプロバイダのネイティブ SDK が握っているので、 + * 送り出す側のコードを読んでも「載っているか」は分からない。受け取る側を立てて + * 届いたヘッダをそのまま読む。 + * + * タイルの配信元 URL は [probeTemplate] にテストが入れる。Android の計装テストは + * アプリと**同じプロセス**で動くので、テスト側で立てたサーバの URL をそのまま渡せる。 + * + * ページを別に用意しているのは、通常の `RasterLayerMapPage` は地理院タイルを見に行く + * ためで、計測には使えないから。プロバイダの選択は `--es provider ` に従う + * ([DemoMapPageScaffold] が見る既存の仕組み)。 + */ +@Composable +fun RasterHeaderProbePage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + val camera = + remember { + MapCameraPosition( + position = GeoPoint(latitude = 35.681236, longitude = 139.767125), + zoom = 8.0, + ) + } + val rasterLayerState = + remember { + RasterLayerState( + source = + RasterLayerSource.UrlTemplate( + template = probeTemplate ?: "http://127.0.0.1:1/tiles/{z}/{x}/{y}.png", + tileSize = 256, + ), + userAgent = probeUserAgent, + extraHeaders = probeExtraHeaders, + id = "raster_header_probe", + ) + } + + var mapViewState by remember { mutableStateOf?>(null) } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(camera), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { mapViewState = it }, + ) { paddings -> + RasterLayerMapComponent( + mapViewState = mapViewState, + rasterLayerState = rasterLayerState, + modifier = + modifier + .fillMaxSize() + .padding(paddings), + ) + } +} + +/** テストが立てた計測サーバの URL テンプレート。 */ +var probeTemplate: String? = null + +/** 送信を期待する User-Agent。 */ +var probeUserAgent: String = RasterLayerState.DEFAULT_USER_AGENT + +/** 送信を期待する追加ヘッダ。 */ +var probeExtraHeaders: Map? = null diff --git a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerMapComponent.kt index 060e4e4e6..df104917d 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerMapComponent.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerMapComponent.kt @@ -13,7 +13,7 @@ fun RasterLayerMapComponent( rasterLayerState: RasterLayerState, modifier: Modifier = Modifier, ) { - mapViewState?.let { it -> + mapViewState?.let { MapViewContainer( modifier = modifier, state = it, diff --git a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerMapPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerMapPage.kt index 57d6e0718..25d9f2a41 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerMapPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerMapPage.kt @@ -32,9 +32,10 @@ import com.mapconductor.tomtom.TomTomMapViewState @OptIn(ExperimentalMaterial3Api::class) @Composable fun RasterLayerMapPage( - onToggleSidebar: () -> Unit = {}, + modifier: Modifier = Modifier, layers: List = DefaultGsiLayers.all, initialLayer: GsiLayer = DefaultGsiLayers.nasa, + onToggleSidebar: () -> Unit = {}, ) { val viewModelFactory = remember(layers, initialLayer) { @@ -64,6 +65,7 @@ fun RasterLayerMapPage( RasterLayerMapComponent( mapViewState = mapViewState.value, rasterLayerState = viewModel.rasterLayerState, + modifier = modifier, ) MessageCard( diff --git a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerPageViewModel.kt b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerPageViewModel.kt index ca11ef8e4..b74648123 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerPageViewModel.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/rasterlayer/RasterLayerPageViewModel.kt @@ -1,95 +1,91 @@ -package com.mapconductor.example.pages.rasterlayer - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.map.MapViewStateInterface -import com.mapconductor.core.raster.RasterLayerState -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -interface RasterLayerPageViewModelInterface { - val initCameraPosition: MapCameraPosition - val mapViewState: StateFlow?> - var opacity: Float - - val availableLayers: List - val selectedLayer: GsiLayer - - val rasterLayerState: RasterLayerState - - fun selectLayer(layer: GsiLayer) - - fun onMapViewChanged(state: MapViewStateInterface<*>) -} - -class RasterLayerPageViewModel( - layers: List, - initialLayer: GsiLayer, -) : ViewModel(), - RasterLayerPageViewModelInterface { - init { - require(layers.isNotEmpty()) { "At least one GSI layer must be injected" } - require(layers.distinctBy(GsiLayer::id).size == layers.size) { - "Injected GSI layer IDs must be unique" - } - require(layers.any { it.id == initialLayer.id }) { - "The initial GSI layer must be included in the injected layers" - } - } - - override val availableLayers = layers.toList() - - override val initCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = 35.6812, - longitude = 139.7671, - ), - zoom = 7.0, - bearing = 0.0, - tilt = 0.0, - paddings = null, - ) - - override var opacity by mutableStateOf(0.75f) - - override var selectedLayer by - mutableStateOf( - availableLayers.first { it.id == initialLayer.id }, - ) - private set - - override val rasterLayerState: RasterLayerState - get() = - RasterLayerState( - id = "rasterLayer", - source = selectedLayer.source, - opacity = opacity, - ) - - private val _mapViewState = MutableStateFlow?>(null) - override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() - - override fun selectLayer(layer: GsiLayer) { - selectedLayer = - availableLayers.firstOrNull { it.id == layer.id } - ?: throw IllegalArgumentException("Unknown GSI layer: ${layer.id}") - } - - override fun onMapViewChanged(state: MapViewStateInterface<*>) { - mapViewState.value?.cameraPosition?.let { - state.moveCameraTo(it) - } - this._mapViewState.value = state - } - - override fun onCleared() { - super.onCleared() - } -} +package com.mapconductor.example.pages.rasterlayer + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.raster.RasterLayerState +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +interface RasterLayerPageViewModelInterface { + val initCameraPosition: MapCameraPosition + val mapViewState: StateFlow?> + var opacity: Float + + val availableLayers: List + val selectedLayer: GsiLayer + + val rasterLayerState: RasterLayerState + + fun selectLayer(layer: GsiLayer) + + fun onMapViewChanged(state: MapViewStateInterface<*>) +} + +class RasterLayerPageViewModel( + layers: List, + initialLayer: GsiLayer, +) : ViewModel(), + RasterLayerPageViewModelInterface { + init { + require(layers.isNotEmpty()) { "At least one GSI layer must be injected" } + require(layers.distinctBy(GsiLayer::id).size == layers.size) { + "Injected GSI layer IDs must be unique" + } + require(layers.any { it.id == initialLayer.id }) { + "The initial GSI layer must be included in the injected layers" + } + } + + override val availableLayers = layers.toList() + + override val initCameraPosition = + MapCameraPosition( + position = + GeoPoint.fromLatLong( + latitude = 35.6812, + longitude = 139.7671, + ), + zoom = 7.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + + override var opacity by mutableStateOf(0.75f) + + override var selectedLayer by + mutableStateOf( + availableLayers.first { it.id == initialLayer.id }, + ) + private set + + override val rasterLayerState: RasterLayerState + get() = + RasterLayerState( + id = "rasterLayer", + source = selectedLayer.source, + opacity = opacity, + ) + + private val _mapViewState = MutableStateFlow?>(null) + override val mapViewState: StateFlow?> = _mapViewState.asStateFlow() + + override fun selectLayer(layer: GsiLayer) { + selectedLayer = + availableLayers.firstOrNull { it.id == layer.id } + ?: throw IllegalArgumentException("Unknown GSI layer: ${layer.id}") + } + + override fun onMapViewChanged(state: MapViewStateInterface<*>) { + mapViewState.value?.cameraPosition?.let { + state.moveCameraTo(it) + } + this._mapViewState.value = state + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/startup/StartUpPage.kt b/example-app/src/main/java/com/mapconductor/example/pages/startup/StartUpPage.kt index cfdc45379..e26170cca 100644 --- a/example-app/src/main/java/com/mapconductor/example/pages/startup/StartUpPage.kt +++ b/example-app/src/main/java/com/mapconductor/example/pages/startup/StartUpPage.kt @@ -1,112 +1,112 @@ -package com.mapconductor.example.pages.startup - -import androidx.compose.foundation.Image -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.calculateStartPadding -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.LayoutDirection -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.mapconductor.example.R - -@Composable -fun StartUpPage(onToggleSidebar: () -> Unit = {}) { - Scaffold { paddingValues -> - Column( - modifier = - Modifier - .fillMaxSize() - .padding( - horizontal = paddingValues.calculateStartPadding(layoutDirection = LayoutDirection.Ltr) + 10.dp, - vertical = paddingValues.calculateBottomPadding(), - ).verticalScroll(rememberScrollState()), - ) { - Image( - painter = painterResource(R.drawable.mapcat), - contentDescription = "MapConductor", - modifier = Modifier.align(Alignment.CenterHorizontally), - ) - - Text( - text = "MAP CONDUCTOR", - fontWeight = FontWeight.Bold, - fontSize = 42.sp, - modifier = Modifier.align(Alignment.CenterHorizontally), - ) - Text( - text = "UNIFIED MAP SDK API", - fontSize = 26.sp, - modifier = Modifier.align(Alignment.CenterHorizontally), - ) - Spacer( - modifier = Modifier.size(10.dp), - ) - Text( - text = stringResource(R.string.demo_application), - fontSize = 22.sp, - modifier = Modifier.align(Alignment.CenterHorizontally), - ) - Spacer( - modifier = Modifier.size(30.dp), - ) - Text( - text = stringResource(R.string.startup_abstract).trimIndent(), - ) - - Text( - text = stringResource(R.string.feature), - fontSize = 18.sp, - modifier = - Modifier.padding( - top = 20.dp, - bottom = 10.dp, - ), - ) - Column { - Text( - text = stringResource(R.string.feature_multi_provider).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - Text( - text = stringResource(R.string.feature_unigied_interface).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - Text( - text = stringResource(R.string.feature_high_performance).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - Text( - text = stringResource(R.string.feature_reactive_state).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - Text( - text = stringResource(R.string.feature_jetpack_compose).trimIndent(), - modifier = Modifier.padding(10.dp), - ) - } - Button( - modifier = - Modifier - .fillMaxSize() - .padding(20.dp), - onClick = onToggleSidebar, - ) { - Text(text = "Open menu") - } - } - } -} +package com.mapconductor.example.pages.startup + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.example.R + +@Composable +fun StartUpPage(onToggleSidebar: () -> Unit = {}) { + Scaffold { paddingValues -> + Column( + modifier = + Modifier + .fillMaxSize() + .padding( + horizontal = paddingValues.calculateStartPadding(layoutDirection = LayoutDirection.Ltr) + 10.dp, + vertical = paddingValues.calculateBottomPadding(), + ).verticalScroll(rememberScrollState()), + ) { + Image( + painter = painterResource(R.drawable.mapcat), + contentDescription = "MapConductor", + modifier = Modifier.align(Alignment.CenterHorizontally), + ) + + Text( + text = "MAP CONDUCTOR", + fontWeight = FontWeight.Bold, + fontSize = 42.sp, + modifier = Modifier.align(Alignment.CenterHorizontally), + ) + Text( + text = "UNIFIED MAP SDK API", + fontSize = 26.sp, + modifier = Modifier.align(Alignment.CenterHorizontally), + ) + Spacer( + modifier = Modifier.size(10.dp), + ) + Text( + text = stringResource(R.string.demo_application), + fontSize = 22.sp, + modifier = Modifier.align(Alignment.CenterHorizontally), + ) + Spacer( + modifier = Modifier.size(30.dp), + ) + Text( + text = stringResource(R.string.startup_abstract).trimIndent(), + ) + + Text( + text = stringResource(R.string.feature), + fontSize = 18.sp, + modifier = + Modifier.padding( + top = 20.dp, + bottom = 10.dp, + ), + ) + Column { + Text( + text = stringResource(R.string.feature_multi_provider).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + Text( + text = stringResource(R.string.feature_unigied_interface).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + Text( + text = stringResource(R.string.feature_high_performance).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + Text( + text = stringResource(R.string.feature_reactive_state).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + Text( + text = stringResource(R.string.feature_jetpack_compose).trimIndent(), + modifier = Modifier.padding(10.dp), + ) + } + Button( + modifier = + Modifier + .fillMaxSize() + .padding(20.dp), + onClick = onToggleSidebar, + ) { + Text(text = "Open menu") + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/vectorstyle/VectorStylePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/vectorstyle/VectorStylePage.kt new file mode 100644 index 000000000..f5471c20d --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/vectorstyle/VectorStylePage.kt @@ -0,0 +1,264 @@ +package com.mapconductor.example.pages.vectorstyle + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Card +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.map.VectorStyleSupportKey +import com.mapconductor.example.MapViewContainer +import com.mapconductor.example.pages.vectortile.VectorTileStyleLoader +import com.mapconductor.example.pages.vectortile.showProviderBasemap +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.utils.LoadingDialog +import com.mapconductor.vectorstyle.LayerRole +import com.mapconductor.vectorstyle.StyleRules +import com.mapconductor.vectorstyle.VectorStyle +import com.mapconductor.vectorstyle.VectorStyleSource +import com.mapconductor.vectortile.VectorTileRasteriser +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * The same style adjustment on every backend, through `MapView(style = ...)`. + * + * Two things are worth watching rather than just looking at: + * + * - **The provider switcher.** MapLibre, Mapbox and MapTiler are handed the + * document and then told the per-layer differences; the rest cannot read a + * style at all and say so in the diagnostics (until the rasteriser is + * wired in). Same rules, and the map that can take them looks the way the + * rules asked. + * - **The road-colour slider.** Dragging it writes a new rule set on every + * frame, which on a vector backend sends differences and reloads nothing. + * If a drag makes the tiles flash, the in-place path is broken and the + * style is being reinstalled — which is the whole failure this design + * exists to prevent, and it is visible to the eye. + */ +@Composable +fun VectorStylePage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + var styleJson by remember { mutableStateOf(null) } + var failure by remember { mutableStateOf(null) } + var diagnostics by remember { mutableStateOf>(emptyList()) } + var mapViewState by remember { mutableStateOf?>(null) } + + /** Set once the map is up, which is when its capabilities are registered. */ + var loadedState by remember { mutableStateOf?>(null) } + var preset by remember { mutableStateOf(Preset.ROAD_EMPHASIS) } + var roadLightness by remember { mutableFloatStateOf(1.0f) } + // The style the app supplies, or the one the map happens to be drawing. + // The second is the interesting case and the one that can fail: a backend + // with no vector style has nothing to adjust, and says so. + var fromCurrentDesign by remember { mutableStateOf(false) } + + val initCameraPosition = + remember { + MapCameraPosition( + position = GeoPoint.fromLatLong(latitude = 35.68049, longitude = 139.76669), + zoom = 12.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + } + + /** + * A style *is* the basemap, so the backend's own one is blanked while + * one is drawn — but only where it has to be. + * + * Not for a backend that reads the style itself: it replaces its own + * design, and blanking first would load a basemap to throw it away. + * + * And **not while adjusting the map's own style**: there the whole point + * is the design the backend is already drawing, so blanking it is + * self-defeating. On a backend that cannot read a style at all (Open + * Mobile Maps draws raster XYZ tiles and has no style to read) that mode + * cannot work, and leaving the basemap up shows the map it could not + * adjust next to the message saying so — rather than a white screen. + */ + LaunchedEffect(loadedState, fromCurrentDesign) { + val loaded = loadedState ?: return@LaunchedEffect + val readsStyles = loaded.serviceRegistry.has(VectorStyleSupportKey) + showProviderBasemap(loaded, visible = readsStyles || fromCurrentDesign) + } + + LaunchedEffect(Unit) { + runCatching { withContext(Dispatchers.IO) { VectorTileStyleLoader.load() } } + .onSuccess { styleJson = it } + .onFailure { failure = it.message ?: it.toString() } + } + + /** + * What draws the style on a backend that cannot read one. + * + * Google Maps, MapKit, HERE, ArcGIS, Longdo, TomTom and the rest have no + * vector renderer; this renders the style to tiles on the device. The + * three that *can* read a style never call it. + */ + val rasteriser = remember { VectorTileRasteriser() } + + val roadColor = Color(roadLightness, roadLightness, roadLightness) + val rules = + remember(preset, roadColor) { + when (preset) { + Preset.NONE -> StyleRules.NONE + Preset.ROAD_EMPHASIS -> + StyleRules.build { + all { color = Color.Black } + role(LayerRole.LABEL) { visible = false } + role(LayerRole.ROAD_CASING) { color = Color(0xFF303030) } + role(LayerRole.ROAD) { + color = roadColor + widthScale = 1.4f + } + } + + Preset.NIGHT -> + StyleRules.build { + all { darken(0.55f) } + role(LayerRole.ROAD) { color = roadColor } + role(LayerRole.WATER) { color = Color(0xFF0B1B2B) } + } + + Preset.WATER_ONLY -> + StyleRules.build { + all { visible = false } + role(LayerRole.BACKGROUND) { + visible = true + color = Color(0xFFF2F2F2) + } + role(LayerRole.WATER) { + visible = true + color = Color(0xFF2E6FB7) + } + } + } + } + + // A new instance on every slider frame, by design: what decides whether + // the map reinstalls is `MapViewStyle.key`, not identity. Same document + // plus different rules is the cheap path. + val style = + if (fromCurrentDesign) { + VectorStyle( + document = VectorStyleSource.CurrentDesign, + rules = rules, + rasteriser = rasteriser, + onDiagnostics = { diagnostics = it }, + ) + } else { + styleJson?.let { json -> + VectorStyle( + document = VectorStyleSource.Text(json), + rules = rules, + rasteriser = rasteriser, + onDiagnostics = { diagnostics = it }, + ) + } + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { mapViewState = it }, + ) { paddings -> + Box( + modifier = + modifier + .fillMaxSize() + .padding(paddings), + contentAlignment = Alignment.Center, + ) { + mapViewState?.let { state -> + MapViewContainer( + modifier = Modifier.fillMaxSize(), + state = state, + style = style, + onStyleDiagnostics = { diagnostics = it }, + // **On map-loaded, not when the state arrives.** The + // capability is registered while the controller is being + // built, so asking earlier says "cannot read a style" + // about MapLibre — and then `CurrentDesign` finds a blank + // design and reports that there is nothing to adjust. + onMapLoaded = { loadedState = it }, + ) + } + + Card( + modifier = + Modifier + .align(Alignment.BottomCenter) + // Clear of the attribution band: this page draws + // OpenStreetMap, whose licence needs the credit + // readable. + .padding(start = 8.dp, end = 8.dp, top = 8.dp, bottom = 28.dp), + ) { + Column(modifier = Modifier.padding(8.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Preset.entries.forEach { option -> + FilterChip( + selected = preset == option, + onClick = { preset = option }, + label = { Text(option.label, fontSize = 12.sp) }, + ) + } + } + FilterChip( + selected = fromCurrentDesign, + onClick = { fromCurrentDesign = !fromCurrentDesign }, + label = { Text("Adjust the map's own style", fontSize = 12.sp) }, + ) + Text("Road lightness ${"%.2f".format(roadLightness)}", fontSize = 12.sp) + Slider( + value = roadLightness, + onValueChange = { roadLightness = it }, + valueRange = 0f..1f, + ) + // The rule that matched nothing, the adjustment this + // backend would not take, the style that could not be + // read: the failures here all look like "it nearly + // worked" and nothing else reports them. + diagnostics.forEach { Text(it, fontSize = 11.sp, color = Color(0xFF7A4A00)) } + failure?.let { Text("style failed: $it", fontSize = 11.sp, color = Color.Red) } + } + } + + if (styleJson == null && failure == null && !fromCurrentDesign) { + LoadingDialog(title = "Vector style", message = "Loading style…") + } + } + } +} + +private enum class Preset( + val label: String, +) { + ROAD_EMPHASIS("Roads"), + NIGHT("Night"), + WATER_ONLY("Water"), + NONE("As authored"), +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/vectortile/SampleBasemap.kt b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/SampleBasemap.kt new file mode 100644 index 000000000..f66493110 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/SampleBasemap.kt @@ -0,0 +1,66 @@ +package com.mapconductor.example.pages.vectortile + +import com.mapconductor.arcgis.ArcGISDesign +import com.mapconductor.arcgis.ArcGISMapViewStateInterface +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.googlemaps.GoogleMapDesign +import com.mapconductor.googlemaps.GoogleMapViewStateInterface +import com.mapconductor.longdo.LongdoDesign +import com.mapconductor.longdo.LongdoViewStateInterface +import com.mapconductor.mapbox.MapboxMapDesign +import com.mapconductor.mapbox.MapboxViewStateInterface +import com.mapconductor.maplibre.MapLibreDesign +import com.mapconductor.maplibre.MapLibreViewStateInterface +import com.mapconductor.maptiler.MapTilerDesign +import com.mapconductor.maptiler.MapTilerViewStateInterface +import com.mapconductor.openmobilemaps.OpenMobileMapsDesign +import com.mapconductor.openmobilemaps.OpenMobileMapsViewStateInterface +import com.mapconductor.tomtom.TomTomMapDesign +import com.mapconductor.tomtom.TomTomMapViewStateInterface + +/** + * Blanks the backend's own basemap, or restores it. + * + * Per provider by construction: the design type is provider-specific, and + * only some of them have a "draw nothing" value. Where there is none the + * opaque tiles cover it anyway -- the difference is whether the device also + * fetches a basemap nobody sees. HERE and Mappls have no such design. + */ +fun showProviderBasemap( + state: MapViewStateInterface<*>, + visible: Boolean, +) { + when (state) { + is MapLibreViewStateInterface -> + state.mapDesignType = + if (visible) { + MapLibreDesign.OsmBrightJa + } else { + MapLibreDesign(id = "blank", styleJsonURL = "asset://blank-style.json") + } + + is GoogleMapViewStateInterface -> + state.mapDesignType = if (visible) GoogleMapDesign.Normal else GoogleMapDesign.None + + is ArcGISMapViewStateInterface -> + state.mapDesignType = if (visible) ArcGISDesign.OsmStandard else ArcGISDesign.None + + is MapboxViewStateInterface -> + state.mapDesignType = if (visible) MapboxMapDesign.Standard else MapboxMapDesign.None + + is TomTomMapViewStateInterface -> + state.mapDesignType = if (visible) TomTomMapDesign.Standard else TomTomMapDesign.None + + is MapTilerViewStateInterface -> + state.mapDesignType = if (visible) MapTilerDesign.Streets else MapTilerDesign.None + + is LongdoViewStateInterface -> + state.mapDesignType = if (visible) LongdoDesign.Normal else LongdoDesign.None + + is OpenMobileMapsViewStateInterface -> + state.mapDesignType = + if (visible) OpenMobileMapsDesign.OpenStreetMap else OpenMobileMapsDesign.None + + else -> Unit + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTileCategory.kt b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTileCategory.kt new file mode 100644 index 000000000..94d40dd17 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTileCategory.kt @@ -0,0 +1,73 @@ +package com.mapconductor.example.pages.vectortile + +import androidx.compose.ui.graphics.Color +import com.mapconductor.vectorstyle.LayerRole + +/** + * ベクタータイルのサンプルで触れる「地図の上のもの」と、それが指すスタイルの + * 中の role。 + * + * 1 つに role が複数あるのは、**つまみは地図の上のもの、role はスタイルの中の + * もの**だから。人が「陸」と呼ぶのは地図が乗っている背景([LayerRole.BACKGROUND]) + * +その上の土地利用([LayerRole.LAND])+敷地([LayerRole.LANDUSE])で、真ん中 + * だけ消したり塗ったりしても地面の色は変わらない。「水域」も面と川筋の両方。 + * + * レイヤー id ではなく role で指すので、別のスタイルに差し替えても同じ言葉が + * 通る。ios-sdk の `VectorTileMapPage` と react-sdk の `VectorTileLayerPage` + * も同じ並び・同じ既定色。 + */ +data class VectorTileCategory( + val label: String, + val key: String, + val roles: List, + /** + * 色を選べるか。 + * + * ラベルだけ false。tint は当たったレイヤーを全部 1 色へ寄せるので、文字に + * やると公園の緑も川の青も、ページを開いただけで潰れる。消すほうは要るので + * スイッチだけ出す。 + */ + val tinted: Boolean = true, +) { + companion object { + val all = + listOf( + VectorTileCategory("Water", "water", listOf(LayerRole.WATER, LayerRole.WATERWAY)), + VectorTileCategory( + "Land", + "land", + listOf(LayerRole.BACKGROUND, LayerRole.LAND, LayerRole.LANDUSE), + ), + // 縁取りは road でもあるので、これで一緒に拾える。 + VectorTileCategory("Roads", "road", listOf(LayerRole.ROAD)), + VectorTileCategory("Buildings", "building", listOf(LayerRole.BUILDING)), + // 地名・POI・路線記号・一方通行の矢印まで、記号レイヤーすべて。 + // ラスタ経路ではこれが透明なオーバーレイなので、外すとその半分が + // 空になる。 + VectorTileCategory("Labels", "label", listOf(LayerRole.LABEL), tinted = false), + ) + + val defaultPalette: Map = + mapOf( + "water" to Color(0xFF3A7CA5), + "land" to Color(0xFFF2EFE6), + "road" to Color(0xFFFFFFFF), + "building" to Color(0xFFD9D0C9), + ) + + /** 見本帳。サンプルに要るだけの色数。 */ + val swatches = + listOf( + Color(0xFFFFFFFF), + Color(0xFFD9D0C9), + Color(0xFF9E9E9E), + Color(0xFF424242), + Color(0xFF000000), + Color(0xFF3A7CA5), + Color(0xFF2E7D32), + Color(0xFFF2EFE6), + Color(0xFFE65100), + Color(0xFF8E24AA), + ) + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTileMapComponent.kt b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTileMapComponent.kt new file mode 100644 index 000000000..8d77cf8f5 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTileMapComponent.kt @@ -0,0 +1,62 @@ +package com.mapconductor.example.pages.vectortile + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import com.mapconductor.core.OnMapLoadedHandler +import com.mapconductor.core.map.MapViewStateInterface +import com.mapconductor.core.map.VectorStyleSupportKey +import com.mapconductor.example.MapViewContainer +import com.mapconductor.vectorstyle.StyleRules +import com.mapconductor.vectortile.VectorTileLayer + +@Composable +fun VectorTileMapComponent( + mapViewState: MapViewStateInterface<*>?, + styleJson: String?, + opacity: Float, + rules: StyleRules = StyleRules.NONE, + asBasemap: Boolean = false, + tileSize: Int? = null, + modifier: Modifier = Modifier, + onMapLoaded: OnMapLoadedHandler? = null, + onDiagnostics: (List) -> Unit = {}, +) { + val diskCacheDir = LocalContext.current.cacheDir.resolve("vectortile") + + // Blanking the backend's own basemap is per-provider by construction: the + // design type is provider-specific, and only some of them have a "draw + // nothing" value. Where there is none, the opaque tiles cover it anyway — + // the difference is whether the device also fetches a basemap nobody sees. + LaunchedEffect(mapViewState, asBasemap) { + val state = mapViewState ?: return@LaunchedEffect + // A map that takes the style directly gets it *as* its design from + // the layer; blanking first would only load one style to throw it + // away. Going back to the provider's own basemap is still done here. + if (asBasemap && state.serviceRegistry.has(VectorStyleSupportKey)) return@LaunchedEffect + showProviderBasemap(state, visible = !asBasemap) + } + + mapViewState?.let { state -> + MapViewContainer( + modifier = modifier, + state = state, + onMapLoaded = onMapLoaded, + ) { + // The layer is what any backend sees: an ordinary raster layer, + // whose tiles happen to be rendered on-device from a vector style. + if (styleJson != null) { + VectorTileLayer( + styleJson = styleJson, + rules = rules, + tileSize = tileSize, + opacity = opacity, + diskCacheDir = diskCacheDir, + onDiagnostics = onDiagnostics, + asBasemap = asBasemap, + ) + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTilePage.kt b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTilePage.kt new file mode 100644 index 000000000..f88d5f35d --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTilePage.kt @@ -0,0 +1,292 @@ +package com.mapconductor.example.pages.vectortile + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.FilterChip +import androidx.compose.material3.FilterChipDefaults +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.example.ui.DefaultMapViewItems +import com.mapconductor.example.ui.DemoMapPageScaffold +import com.mapconductor.utils.LoadingDialog +import com.mapconductor.vectorstyle.StyleRules +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * Draws a MapLibre vector style on whichever backend is selected. + * + * The point of the page is the provider switcher at the top: Google Maps, + * MapKit-equivalents, HERE, ArcGIS and the rest cannot render a vector style, + * yet all of them show this one — because what they are handed is an ordinary + * raster layer whose tiles were rendered on the device. + */ +@Composable +fun VectorTilePage( + modifier: Modifier = Modifier, + onToggleSidebar: () -> Unit = {}, +) { + var styleJson by remember { mutableStateOf(null) } + var failure by remember { mutableStateOf(null) } + var diagnostics by remember { mutableStateOf>(emptyList()) } + var opacity by remember { mutableFloatStateOf(1.0f) } + // 256 quarters the pixels per tile but needs four times as many tiles for + // the same screen — and four times the source fetches. Which wins is not + // predictable, so it is switchable and measured. + // null は「地図 SDK の好みに任せる」。ArcGIS の 3D だけ 256 を要求してくる。 + var tileSize by remember { mutableStateOf(null) } + var mapViewState by remember { mutableStateOf?>(null) } + // Basemap mode: blank whatever the backend would draw underneath, so the + // only thing on screen is the style rendered here. What the backend keeps + // is its own business — this is the part of `MapConductorDesign` that can + // be tried before the design type itself exists. + var asBasemap by remember { mutableStateOf(false) } + + // 「描かない」を選べる種別と、それが隠す role。 + // + // 1 つの種別に role が複数あるのは、種別が**地図の上のもの**で role が + // **スタイルの中のもの**だから。人が「陸」と呼ぶのは、地図が乗っている + // 背景(background)+その上の土地利用(land)+敷地(landuse)で、 + // 真ん中だけ消しても地面の色は変わらない。「水域」も面(water)と + // 川筋(waterway)の両方。色のつまみも同じまとめ方をしている。 + // react-sdk の VectorTileLayerPage と同じ並び。 + val categories = remember { VectorTileCategory.all } + var hidden by remember { mutableStateOf(emptySet()) } + var palette by remember { mutableStateOf(VectorTileCategory.defaultPalette) } + // 置き換えではなく混ぜる。本物のベースマップは森・草地・農地を十数通りの + // 緑で描き分けていて、1 色に潰すとその差が消えて地図に見えなくなる。 + var strength by remember { mutableFloatStateOf(0.6f) } + var picking by remember { mutableStateOf(null) } + + /** + * つまみの状態をそのままルールにしたもの。 + * + * 外した種別はレイヤーごと落ちるので**描かれない**(背景と同じ色を塗るので + * はない)。色は `mix` で元の色から寄せる。強さ 0 なら何も書かず、文書は + * 作者が書いたままになる。 + */ + val rules = + remember(hidden, palette, strength) { + // `visible` という名前は使えない: パッチ側の `visible` を隠す。 + val shown = categories.filter { it.key !in hidden } + val gone = categories.filter { it.key in hidden } + if (gone.isEmpty() && strength <= 0f) { + StyleRules.NONE + } else { + StyleRules.build { + gone.flatMap { it.roles }.forEach { role -> role(role) { visible = false } } + if (strength > 0f) { + shown.filter { it.tinted }.forEach { category -> + val target = palette.getValue(category.key) + category.roles.forEach { role -> role(role) { mix(target, strength) } } + } + } + } + } + } + + // Central Tokyo: the OSMF Shortbread service has street-level detail here, + // so the layer is obviously doing something at the default zoom. + val initCameraPosition = + remember { + MapCameraPosition( + position = GeoPoint.fromLatLong(latitude = 35.68049, longitude = 139.76669), + zoom = 12.0, + bearing = 0.0, + tilt = 0.0, + paddings = null, + ) + } + + LaunchedEffect(Unit) { + runCatching { withContext(Dispatchers.IO) { VectorTileStyleLoader.load() } } + .onSuccess { styleJson = it } + .onFailure { failure = it.message ?: it.toString() } + } + + DemoMapPageScaffold( + menuItems = DefaultMapViewItems(initCameraPosition), + onToggleSidebar = onToggleSidebar, + onMapViewStateChanged = { mapViewState = it }, + ) { paddings -> + Box( + modifier = + modifier + .fillMaxSize() + .padding(paddings), + contentAlignment = Alignment.Center, + ) { + VectorTileMapComponent( + mapViewState = mapViewState, + asBasemap = asBasemap, + styleJson = styleJson, + opacity = opacity, + rules = rules, + tileSize = tileSize, + onDiagnostics = { diagnostics = it }, + ) + + Card( + modifier = + Modifier + .align(Alignment.BottomCenter) + // Clear of the attribution band the SDK draws along the + // bottom edge. A credit half-hidden behind this demo's + // own controls is not a credit -- and this page draws + // OpenStreetMap, whose licence requires one. + .padding(start = 8.dp, end = 8.dp, top = 8.dp, bottom = 28.dp), + ) { + Column( + modifier = Modifier.padding(8.dp), + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + FilterChip( + selected = asBasemap, + onClick = { asBasemap = !asBasemap }, + label = { Text("As basemap", fontSize = 12.sp) }, + colors = FilterChipDefaults.filterChipColors(), + ) + FilterChip( + selected = tileSize == null, + onClick = { tileSize = null }, + label = { Text("Auto", fontSize = 12.sp) }, + colors = FilterChipDefaults.filterChipColors(), + ) + listOf(256, 512).forEach { size -> + FilterChip( + selected = tileSize == size, + onClick = { tileSize = size }, + label = { Text("${size}px", fontSize = 12.sp) }, + colors = FilterChipDefaults.filterChipColors(), + ) + } + } + // 上の段で描くかどうか、下の段でその色。色を持つのは面と線の + // 4 つで、ラベルは消すだけ(下の段に四角は出ない)。 + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + categories.forEach { category -> + FilterChip( + selected = category.key !in hidden, + onClick = { + hidden = + if (category.key in hidden) { + hidden - category.key + } else { + hidden + category.key + } + }, + label = { Text(category.label, fontSize = 12.sp) }, + colors = FilterChipDefaults.filterChipColors(), + ) + } + } + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + categories.filter { it.tinted }.forEach { category -> + Box( + modifier = + Modifier + .width(72.dp) + .size(height = 24.dp, width = 72.dp) + .background( + palette.getValue(category.key), + RoundedCornerShape(6.dp), + ).border(1.dp, Color(0x33000000), RoundedCornerShape(6.dp)) + .clickable { picking = category.key }, + ) + } + } + Text( + text = "Tint strength ${"%.2f".format(strength)}", + fontSize = 12.sp, + ) + Slider( + value = strength, + onValueChange = { strength = it }, + valueRange = 0f..1f, + ) + Text( + text = "Opacity ${"%.2f".format(opacity)}", + fontSize = 12.sp, + ) + Slider( + value = opacity, + onValueChange = { opacity = it }, + valueRange = 0f..1f, + ) + // Undrawn layer types and unusable sources are worth showing: the + // failure mode that matters is a blank tile with no explanation. + diagnostics.forEach { Text(it, fontSize = 11.sp, color = Color(0xFF7A4A00)) } + failure?.let { Text("style failed: $it", fontSize = 11.sp, color = Color.Red) } + } + } + + // Compose には色のピッカーが無いので、サンプルに要るぶんだけの + // 見本帳を出す。選べる色の少なさはデモの都合で、API の都合ではない。 + picking?.let { key -> + AlertDialog( + onDismissRequest = { picking = null }, + confirmButton = { TextButton(onClick = { picking = null }) { Text("Close") } }, + title = { Text(categories.first { it.key == key }.label, fontSize = 14.sp) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + VectorTileCategory.swatches.chunked(5).forEach { row -> + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + row.forEach { swatch -> + Box( + modifier = + Modifier + .size(40.dp) + .background(swatch, RoundedCornerShape(6.dp)) + .border(1.dp, Color(0x33000000), RoundedCornerShape(6.dp)) + .clickable { + palette = palette + (key to swatch) + picking = null + }, + ) + } + } + } + } + }, + ) + } + + if (styleJson == null && failure == null) { + LoadingDialog(title = "Vector tiles", message = "Loading vector style…") + } + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTileStyleLoader.kt b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTileStyleLoader.kt new file mode 100644 index 000000000..9ec5c0fcb --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/example/pages/vectortile/VectorTileStyleLoader.kt @@ -0,0 +1,70 @@ +package com.mapconductor.example.pages.vectortile + +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL + +/** + * Fetches a Shortbread-schema style and repoints it at the OSMF tile service. + * + * The style and the tiles come from different hosts on purpose: Shortbread is + * an open schema, so any style written against it works with any server that + * serves it. Neither needs an API key. + */ +object VectorTileStyleLoader { + private const val STYLE_URL = "https://tiles.versatiles.org/assets/styles/colorful/style.json" + private const val OSM_TILES = "https://vector.openstreetmap.org/shortbread_v1/{z}/{x}/{y}.mvt" + + /** + * What the tiles this points at are owed. + * + * Kept here rather than taken on trust from the upstream style: the + * sources are being repointed at the OSMF service, so the credit that + * matters is the one *those* tiles require, whatever the original style + * happened to say. The style's own wording is preferred when it has one -- + * it is the same licence, in the publisher's own phrasing. + */ + private const val OSM_ATTRIBUTION = + "© OpenStreetMap contributors" + + /** Blocking; call from a background dispatcher. */ + fun load(): String { + val style = JSONObject(fetch(STYLE_URL)) + val sources = style.getJSONObject("sources") + for (id in sources.keys()) { + // Carried across rather than dropped. Rewriting a source is not a + // reason to stop crediting the data, and a bare replacement object + // is how the credit went missing in the first place. + val attribution = + sources + .optJSONObject(id) + ?.optString("attribution") + ?.takeIf { it.isNotBlank() } + ?: OSM_ATTRIBUTION + sources.put( + id, + JSONObject() + .put("type", "vector") + .put("tiles", org.json.JSONArray().put(OSM_TILES)) + .put("minzoom", 0) + .put("maxzoom", 14) + .put("attribution", attribution), + ) + } + return style.toString() + } + + private fun fetch(url: String): String { + val connection = URL(url).openConnection() as HttpURLConnection + return try { + connection.connectTimeout = 20_000 + connection.readTimeout = 20_000 + if (connection.responseCode !in 200..299) { + throw java.io.IOException("style fetch failed: ${connection.responseCode}") + } + connection.inputStream.use { it.readBytes().decodeToString() } + } finally { + connection.disconnect() + } + } +} diff --git a/example-app/src/main/java/com/mapconductor/example/ui/DemoMapPageScaffold.kt b/example-app/src/main/java/com/mapconductor/example/ui/DemoMapPageScaffold.kt index f4f7e52c3..c1c42a62f 100644 --- a/example-app/src/main/java/com/mapconductor/example/ui/DemoMapPageScaffold.kt +++ b/example-app/src/main/java/com/mapconductor/example/ui/DemoMapPageScaffold.kt @@ -268,6 +268,7 @@ fun DefaultMapViewItems(initCameraPosition: MapCameraPositionInterface): List>>, + modifier: Modifier = Modifier, initSelect: Int = 0, onToggleSidebar: () -> Unit, onMapViewStateChanged: (MapViewStateInterface<*>) -> Unit = {}, @@ -293,11 +294,13 @@ fun DemoMapPageScaffold( Scaffold { paddingValues -> Box( modifier = - Modifier.fillMaxSize().padding( - start = paddingValues.calculateStartPadding(layoutDirection = LayoutDirection.Ltr), - end = paddingValues.calculateStartPadding(layoutDirection = LayoutDirection.Ltr), - bottom = paddingValues.calculateBottomPadding(), - ), + modifier + .fillMaxSize() + .padding( + start = paddingValues.calculateStartPadding(layoutDirection = LayoutDirection.Ltr), + end = paddingValues.calculateStartPadding(layoutDirection = LayoutDirection.Ltr), + bottom = paddingValues.calculateBottomPadding(), + ), ) { content(paddingValues) diff --git a/example-app/src/main/java/com/mapconductor/example/ui/MapViewStatePanel.kt b/example-app/src/main/java/com/mapconductor/example/ui/MapViewStatePanel.kt index bbd7498de..e93a62540 100644 --- a/example-app/src/main/java/com/mapconductor/example/ui/MapViewStatePanel.kt +++ b/example-app/src/main/java/com/mapconductor/example/ui/MapViewStatePanel.kt @@ -1,37 +1,37 @@ -package com.mapconductor.example.ui - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.BoxScope -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.wrapContentHeight -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.toFixed - -@Composable -fun BoxScope.MapViewStatePanel(camera: MapCameraPosition?) { - Column( - modifier = - Modifier - .align(Alignment.TopEnd) - .background( - Color( - red = 0.9f, - green = 0.9f, - blue = 0.9f, - alpha = 0.75f, - ), - ).wrapContentHeight() - .fillMaxWidth(), - ) { - Text("LatLng: (${camera?.position?.toUrlValue()})", color = Color.Black) - Text("Zoom: ${camera?.zoom?.toFixed(2)}", color = Color.Black) - Text("bearing: ${camera?.bearing?.toInt()}", color = Color.Black) - Text("tilt: ${camera?.tilt?.toInt()}", color = Color.Black) - } -} +package com.mapconductor.example.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.wrapContentHeight +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.toFixed + +@Composable +fun BoxScope.MapViewStatePanel(camera: MapCameraPosition?) { + Column( + modifier = + Modifier + .align(Alignment.TopEnd) + .background( + Color( + red = 0.9f, + green = 0.9f, + blue = 0.9f, + alpha = 0.75f, + ), + ).wrapContentHeight() + .fillMaxWidth(), + ) { + Text("LatLng: (${camera?.position?.toUrlValue()})", color = Color.Black) + Text("Zoom: ${camera?.zoom?.toFixed(2)}", color = Color.Black) + Text("bearing: ${camera?.bearing?.toInt()}", color = Color.Black) + Text("tilt: ${camera?.tilt?.toInt()}", color = Color.Black) + } +} diff --git a/example-app/src/main/java/com/mapconductor/postoffice/PostOfficeDataLoader.kt b/example-app/src/main/java/com/mapconductor/postoffice/PostOfficeDataLoader.kt index 0dcb4dfaf..74632f82d 100644 --- a/example-app/src/main/java/com/mapconductor/postoffice/PostOfficeDataLoader.kt +++ b/example-app/src/main/java/com/mapconductor/postoffice/PostOfficeDataLoader.kt @@ -129,6 +129,7 @@ class PostOfficeDataLoader( } json.endArray() } + else -> json.skipValue() } } @@ -164,6 +165,7 @@ class PostOfficeDataLoader( latitude = coords.second } } + "properties" -> { json.beginObject() while (json.hasNext()) { @@ -176,6 +178,7 @@ class PostOfficeDataLoader( } else { json.nextString() } + "address" -> address = if (json.peek() == JsonToken.NULL) { @@ -184,11 +187,13 @@ class PostOfficeDataLoader( } else { json.nextString() } + else -> json.skipValue() } } json.endObject() } + else -> json.skipValue() } } @@ -213,6 +218,7 @@ class PostOfficeDataLoader( while (json.hasNext()) json.skipValue() json.endArray() } + else -> json.skipValue() } } diff --git a/example-app/src/main/java/com/mapconductor/streettree/StreetTree.kt b/example-app/src/main/java/com/mapconductor/streettree/StreetTree.kt new file mode 100644 index 000000000..4c6217380 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/streettree/StreetTree.kt @@ -0,0 +1,240 @@ +package com.mapconductor.streettree + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color as ComposeColor +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.core.graphics.drawable.toDrawable +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.marker.ImageIcon +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.ceil +import kotlin.math.max +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Typeface +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * Tokyo's street trees: 144,183 of them, from the metropolitan government's + * open data. + * + * A harder shape than the post office set. There are six times as many, they + * sit inside one metropolitan area rather than spread over a country, and each + * species draws its own colour — so the renderer cannot collapse two trees of + * different species that land on the same pixel. + * + * Species with fewer than a hundred trees are folded into one bucket. The + * distribution has a long tail: a hundred species cover 96% of the trees, and + * the remaining three hundred would be indistinguishable colours nobody could + * read off a legend. The bucket is still the fifth largest group, so it is not + * a rounding error being hidden. + */ +data class StreetTree( + val position: GeoPoint, + val species: String, + val speciesIndex: Int, + /** Height in metres, as recorded in the survey. */ + val heightM: Float, + /** Trunk circumference in centimetres. */ + val girthCm: Int, + val ward: String, + val roadName: String, + // Serializable because MarkerState.extra is: the SDK carries this across + // the marker abstraction without knowing what it is. +) : java.io.Serializable + +/** 点のどちら側にラベルを描くか。 */ +enum class LabelSide { RIGHT, LEFT, TOP, BOTTOM } + +object StreetTreeIcons { + /** ラベルの文字の大きさ(sp)。ラベルの重なり判定もこの値で測る。 */ + const val LABEL_TEXT_SP = 11f + + /** 点とラベルのすき間(dp)。SDK の配置(縁取りの太さ 1dp)と同じ値。 */ + const val LABEL_GAP_DP = 1f + + /** 縁取りの太さ(dp)。SDK はラベルの幅と高さにこの 2 倍を足す。 */ + private const val LABEL_OUTLINE_DP = 1f + + private val labelTypeface: Typeface = Typeface.DEFAULT_BOLD + + /** 点の上下に置くラベルは縦書きにする。横の通りでは点が横に詰まって並ぶので、横書きだと数本に 1 つしか名前を付けられない。 */ + fun isVertical(side: LabelSide): Boolean = side == LabelSide.TOP || side == LabelSide.BOTTOM + + private val labelSizes = java.util.concurrent.ConcurrentHashMap>() + + /** + * ラベルの幅と高さ(dp、縁取りを含む)。樹種名と向きごとに 1 回だけ測る。 + * SDK と同じ測り方(縦書きは縦書き用の字形で 1 文字 1em に積む)。 + */ + fun labelSizeDp( + text: String, + vertical: Boolean, + ): Pair = + labelSizes.getOrPut(if (vertical) "v/$text" else "h/$text") { + val density = ResourceProvider.dpToPxForBitmap(1f).toFloat() + val paint = + Paint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = ResourceProvider.spToPx(LABEL_TEXT_SP).toFloat() + typeface = labelTypeface + if (vertical) fontFeatureSettings = "'vert' 1" + } + val outline = LABEL_OUTLINE_DP * 2 + if (vertical) { + var column = paint.textSize + text.forEach { column = max(column, paint.measureText(it.toString())) } + ceil(column) / density + outline to text.length * paint.textSize / density + outline + } else { + val metrics = paint.fontMetrics + paint.measureText(text) / density + outline to (metrics.descent - metrics.ascent) / density + outline + } + } + + /** + * 点の [side] 側に樹種名を添えたアイコン。 + * + * SDK の [ImageIcon] のラベルを使う。画像は作らない -- タイル描画は点の画像と + * 文字を別々に描くので、ラベル付きのアイコンをいくつ作っても点の画像は 1 枚のまま。 + */ + fun labelled( + dot: ImageIcon, + text: String, + side: LabelSide, + ): ImageIcon = + dot.copy( + label = text, + labelTextColor = ComposeColor(0xFF282828), + labelTextSize = LABEL_TEXT_SP.sp, + labelTypeFace = labelTypeface, + labelStrokeColor = ComposeColor.White, + labelPosition = + when (side) { + LabelSide.RIGHT -> "right" + LabelSide.LEFT -> "left" + LabelSide.TOP -> "top" + LabelSide.BOTTOM -> "bottom" + }, + labelWritingMode = if (isVertical(side)) "vertical-rl" else "horizontal-tb", + ) + + /** + * 種ごとの色分けドット。 + * + * [sizeDp] は **dp**。ビットマップは密度倍したピクセルで作る -- core の + * [com.mapconductor.core.marker.AbstractDefaultIcon] が + * `dpToPxForBitmap(iconSize)` でそうしているのと同じ流儀で、ここだけ生ピクセル + * で作ると端末が精細になるほど小さく見える。 + * + * 実測(density 2.13 の端末、zoom > 15): 生ピクセルだと見かけ 8.47dp、 + * dp 基準だと 18dp。ios-sdk は既定アイコンもサンプルもポイント基準なので、 + * dp 基準にして初めて 3 プラットフォームが揃う。 + */ + fun palette( + count: Int, + sizeDp: Float, + ): List { + val resources = ResourceProvider.getAppContext().resources + val sizePx = ResourceProvider.dpToPxForBitmap(sizeDp).toInt().coerceAtLeast(1) + val paint = Paint(Paint.ANTI_ALIAS_FLAG) + return (0 until count).map { index -> + // Golden-angle hue rotation, so neighbouring species indices do not + // come out as neighbouring colours. + val hue = (index * 137.508f) % 360f + val colour = + if (index == count - 1) { + // The "other" bucket reads as grey rather than competing + // with a named species for a hue. + Color.rgb(150, 150, 155) + } else { + Color.HSVToColor(floatArrayOf(hue, 0.70f, 0.80f)) + } + val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888) + Canvas(bitmap).apply { + val radius = sizePx / 2f - 1f + paint.color = colour + paint.style = Paint.Style.FILL + drawCircle(sizePx / 2f, sizePx / 2f, radius, paint) + paint.color = Color.argb(110, 0, 0, 0) + paint.style = Paint.Style.STROKE + paint.strokeWidth = 1f + drawCircle(sizePx / 2f, sizePx / 2f, radius, paint) + } + ImageIcon( + image = bitmap.toDrawable(resources), + iconSize = sizeDp.dp, + // 吹き出しは点の上端に出す。 + infoAnchor = Offset(0.5f, 0.0f), + ) + } + } +} + +class StreetTreeDataLoader( + private val context: Context, +) { + /** + * Reads the packed asset: string tables for species, ward and road, then a + * fixed record per tree. The source is a 12 MB Shift-JIS CSV; parsing that + * on the device would measure CSV parsing rather than the map. + */ + suspend fun load(): StreetTreeData = + withContext(Dispatchers.IO) { + val bytes = context.assets.open("tokyo-trees.bin").use { it.readBytes() } + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + + val magic = ByteArray(5) + buffer.get(magic) + require(String(magic, Charsets.US_ASCII) == "TREE\u0002") { + "unexpected street tree asset format" + } + + fun table(): List = + (0 until buffer.int).map { + val length = buffer.short.toInt() + val name = ByteArray(length) + buffer.get(name) + String(name, Charsets.UTF_8) + } + + val species = table() + val wards = table() + val roads = table() + + val count = buffer.int + val trees = ArrayList(count) + repeat(count) { + val lat = buffer.float.toDouble() + val lon = buffer.float.toDouble() + val speciesIndex = buffer.short.toInt() and 0xFFFF + val height = buffer.float + val girth = buffer.short.toInt() and 0xFFFF + val ward = buffer.short.toInt() and 0xFFFF + val road = buffer.short.toInt() and 0xFFFF + trees.add( + StreetTree( + position = GeoPoint(lat, lon), + species = species[speciesIndex], + speciesIndex = speciesIndex, + heightM = height, + girthCm = girth, + ward = wards[ward], + roadName = roads[road], + ), + ) + } + StreetTreeData(trees = trees, species = species) + } +} + +/** The trees, and the species table their colours are indexed by. */ +data class StreetTreeData( + val trees: List, + val species: List, +) diff --git a/example-app/src/main/java/com/mapconductor/streettree/StreetTreeInfoView.kt b/example-app/src/main/java/com/mapconductor/streettree/StreetTreeInfoView.kt new file mode 100644 index 000000000..9d9a936f9 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/streettree/StreetTreeInfoView.kt @@ -0,0 +1,44 @@ +package com.mapconductor.streettree + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** What the survey recorded about one tree. */ +@Composable +fun StreetTreeInfoView( + tree: StreetTree, + modifier: Modifier = Modifier, +) { + Column( + modifier = modifier.padding(horizontal = 14.dp, vertical = 10.dp), + verticalArrangement = Arrangement.spacedBy(3.dp), + ) { + Text(tree.species, fontSize = 17.sp, fontWeight = FontWeight.Bold) + // The survey leaves these blank often enough that showing "0 m" would + // read as a measurement rather than a gap. + if (tree.heightM > 0f) Field("樹高", "%.1f m".format(tree.heightM)) + if (tree.girthCm > 0) Field("幹周", "${tree.girthCm} cm") + if (tree.ward.isNotBlank()) Field("行政区", tree.ward) + if (tree.roadName.isNotBlank()) Field("路線", tree.roadName) + } +} + +@Composable +private fun Field( + label: String, + value: String, +) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(label, fontSize = 13.sp, modifier = Modifier.width(46.dp)) + Text(value, fontSize = 13.sp, fontWeight = FontWeight.Medium) + } +} diff --git a/example-app/src/main/java/com/mapconductor/streettree/StreetTreeLabels.kt b/example-app/src/main/java/com/mapconductor/streettree/StreetTreeLabels.kt new file mode 100644 index 000000000..1fea65835 --- /dev/null +++ b/example-app/src/main/java/com/mapconductor/streettree/StreetTreeLabels.kt @@ -0,0 +1,177 @@ +package com.mapconductor.streettree + +import com.mapconductor.core.features.GeoRectBounds +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.floor +import kotlin.math.ln +import kotlin.math.pow +import kotlin.math.sin +import kotlin.math.tan + +/** + * 画面内の街路樹のうち、どれにどちら向きのラベルを付けるか。 + * + * - 向きは**道路ごとに 1 つ**。道路の木の並びが横向きなら上か下、縦向きなら右か左 + * (道路に直交する向き)。同じ通りのラベルが揃って並ぶ。 + * - 2 つの候補のうち、置けるラベルが多い方を選ぶ。木の多い道路から決める。 + * ただし前回その道路で選んだ向き([previousSides])は、もう一方の 2/3 以上置けるなら + * そのまま使う。見えている範囲が変わるたびに数の多い方へ乗り換えると、パンするたびに + * ラベルが上下や左右で入れ替わる。 + * - すでに置いたラベルか、ほかの木の点の中心を覆うラベルは付けない(その木は点のまま)。 + * ラベルは点の後に描かれるので、端が隣の点に少しかかるのは許す。点の箱ごと避けると、 + * 木の間隔が詰まった斜めの通りでは隣の点がどの向きの箱にもかかり、ラベルが 1 つも置けない。 + * - 上下に置くラベルは縦書き([StreetTreeIcons.isVertical])なので、縦書きの寸法で測る。 + * + * 座標はカメラのズームでの dp。 + */ +object StreetTreeLabels { + /** [trees] の添字 -> 向き。 */ + fun choose( + trees: List, + bounds: GeoRectBounds, + zoom: Double, + /** ラベルのアイコンに掛かる倍率(タイルの iconScaleCallback と同じ値)。 */ + scale: Float, + dotSizeDp: Float, + labelSizeDp: (String, Boolean) -> Pair, + /** 前回の道路名 -> 向き。 */ + previousSides: Map = emptyMap(), + ): Map { + val southWest = bounds.southWest ?: return emptyMap() + val northEast = bounds.northEast ?: return emptyMap() + val world = 256.0 * 2.0.pow(zoom) + + fun x(longitude: Double) = (longitude + 180.0) / 360.0 * world + + fun y(latitude: Double): Double { + val phi = latitude * PI / 180.0 + return (1.0 - ln(tan(phi) + 1.0 / cos(phi)) / PI) / 2.0 * world + } + + // 道路ごとの、画面内の木 + val byRoad = HashMap>() + for ((index, tree) in trees.withIndex()) { + val p = tree.position + if (p.latitude < southWest.latitude || p.latitude > northEast.latitude) continue + if (p.longitude < southWest.longitude || p.longitude > northEast.longitude) continue + byRoad.getOrPut(tree.roadName) { ArrayList() }.add(index) + } + + val placed = PlacedRects() + val sides = HashMap() + val radius = dotSizeDp * scale / 2.0 + val gap = StreetTreeIcons.LABEL_GAP_DP * scale.toDouble() + + // 画面内のすべての点の中心。ラベルがほかの木の点の中心を覆わないかを見る + val dots = PlacedRects() + for (members in byRoad.values) { + for (index in members) { + val cx = x(trees[index].position.longitude) + val cy = y(trees[index].position.latitude) + dots.add(Rect(cx - 0.5, cy - 0.5, cx + 0.5, cy + 0.5)) + } + } + + for ((road, members) in byRoad.entries.sortedByDescending { it.value.size }) { + val xs = DoubleArray(members.size) { x(trees[members[it]].position.longitude) } + val ys = DoubleArray(members.size) { y(trees[members[it]].position.latitude) } + + // 並びの向き(主成分) + val mx = xs.average() + val my = ys.average() + var sxx = 0.0 + var syy = 0.0 + var sxy = 0.0 + for (i in xs.indices) { + val dx = xs[i] - mx + val dy = ys[i] - my + sxx += dx * dx + syy += dy * dy + sxy += dx * dy + } + val angle = 0.5 * atan2(2 * sxy, sxx - syy) + val horizontal = abs(cos(angle)) >= abs(sin(angle)) + val candidates = + if (horizontal) listOf(LabelSide.TOP, LabelSide.BOTTOM) else listOf(LabelSide.RIGHT, LabelSide.LEFT) + + // 道路に沿って並べてから置いていく + val order = xs.indices.sortedBy { xs[it] * cos(angle) + ys[it] * sin(angle) } + + fun rect( + i: Int, + side: LabelSide, + ): Rect { + val (w0, h0) = labelSizeDp(trees[members[i]].species, StreetTreeIcons.isVertical(side)) + val w = w0 * scale + val h = h0 * scale + val cx = xs[i] + val cy = ys[i] + return when (side) { + LabelSide.RIGHT -> Rect(cx + radius + gap, cy - h / 2, cx + radius + gap + w, cy + h / 2) + LabelSide.LEFT -> Rect(cx - radius - gap - w, cy - h / 2, cx - radius - gap, cy + h / 2) + LabelSide.TOP -> Rect(cx - w / 2, cy - radius - gap - h, cx + w / 2, cy - radius - gap) + LabelSide.BOTTOM -> Rect(cx - w / 2, cy + radius + gap, cx + w / 2, cy + radius + gap + h) + } + } + + fun attempt(side: LabelSide): List> { + val own = PlacedRects() + val accepted = ArrayList>() + for (i in order) { + val r = rect(i, side) + if (placed.overlaps(r) || own.overlaps(r) || dots.overlaps(r)) continue + own.add(r) + accepted.add(i to r) + } + return accepted + } + + val attempts = candidates.map { it to attempt(it) } + val most = attempts.maxBy { it.second.size } + val kept = attempts.firstOrNull { it.first == previousSides[road] } + val best = if (kept != null && kept.second.size * 3 >= most.second.size * 2) kept else most + for ((i, r) in best.second) { + placed.add(r) + sides[members[i]] = best.first + } + } + return sides + } + + private class Rect( + val left: Double, + val top: Double, + val right: Double, + val bottom: Double, + ) { + fun overlaps(other: Rect) = left < other.right && other.left < right && top < other.bottom && other.top < bottom + } + + /** 置いたラベルの箱。64dp のマス目に振り分けて、近くだけを見る。 */ + private class PlacedRects { + private val cells = HashMap>() + + private fun cellsOf(r: Rect): List { + val out = ArrayList(4) + for (cx in floor(r.left / CELL).toLong()..floor(r.right / CELL).toLong()) { + for (cy in floor(r.top / CELL).toLong()..floor(r.bottom / CELL).toLong()) { + out.add((cx shl 32) xor (cy and 0xFFFFFFFFL)) + } + } + return out + } + + fun overlaps(r: Rect): Boolean = cellsOf(r).any { key -> cells[key]?.any { it.overlaps(r) } == true } + + fun add(r: Rect) { + for (key in cellsOf(r)) cells.getOrPut(key) { ArrayList() }.add(r) + } + + companion object { + const val CELL = 64.0 + } + } +} diff --git a/example-app/src/main/jniLibs/arm64-v8a/libmapscore.so b/example-app/src/main/jniLibs/arm64-v8a/libmapscore.so new file mode 100755 index 000000000..a7a9f7827 Binary files /dev/null and b/example-app/src/main/jniLibs/arm64-v8a/libmapscore.so differ diff --git a/example-app/src/test/java/com/mapconductor/example/pages/polygon/boston/BostonDataTest.kt b/example-app/src/test/java/com/mapconductor/example/pages/polygon/boston/BostonDataTest.kt new file mode 100644 index 000000000..9f0112020 --- /dev/null +++ b/example-app/src/test/java/com/mapconductor/example/pages/polygon/boston/BostonDataTest.kt @@ -0,0 +1,121 @@ +package com.mapconductor.example.pages.polygon.boston + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +class BostonDataTest { + /** + * Two polygons with every field (fields = 15), written by the generator + * (the React sample's tools/boston/fixture.py): the same polygons at 1e-6 and + * at 1e-5 degree. The same bytes are decoded by the React and iOS tests. + */ + private val fixture = + hex( + "4d43504702000000020000000f067c020109436166c3a920e298950204f4abb228a7b0e24300d00fd00f0000cf0f03db0bd804" + + "d8040000a006000802000103ffea068ff40414142700", + ) + private val fixture5 = + hex( + "4d43504702000000020000000f057c020109436166c3a920e298950204b284850483b8e30600c801c8010000c7010395013c3c" + + "000050000802000103bf57e73e02020300", + ) + + private fun hex(text: String) = text.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + + @Test + fun `decodes every field and closes each ring again`() { + assertDecodesEveryField(fixture) + } + + @Test + fun `decodes every field at 1e-5 degree`() { + assertDecodesEveryField(fixture5) + } + + private fun assertDecodesEveryField(bytes: ByteArray) { + val polygons = decodeMcpg(bytes, "t") + assertEquals(2, polygons.size) + + val first = polygons[0] + assertEquals("t-0", first.id) + assertEquals(12.3, first.height!!, 0.0) + assertEquals(LandUse.CONDO, first.use) + assertEquals(1, first.level) + assertEquals("Café ☕", first.name) + assertEquals(2, first.rings.size) + assertArrayEquals( + doubleArrayOf( + -71.0605, 42.35545, -71.0595, 42.35545, -71.0595, 42.35645, -71.0605, 42.35645, -71.0605, 42.35545, + ), + first.rings[0], + 1e-9, + ) + assertArrayEquals( + doubleArrayOf(-71.0602, 42.3557, -71.0602, 42.356, -71.0598, 42.356, -71.0602, 42.3557), + first.rings[1], + 1e-9, + ) + + val second = polygons[1] + assertEquals("t-1", second.id) + assertNull(second.height) + assertEquals(LandUse.UNKNOWN, second.use) + assertEquals(2, second.level) + assertNull(second.name) + assertArrayEquals( + doubleArrayOf(-71.1, 42.3, -71.09999, 42.30001, -71.09999, 42.29999, -71.1, 42.3), + second.rings.single(), + 1e-9, + ) + } + + @Test + fun `the bundled downtown file has every building of the three areas`() { + val polygons = decodeMcpg(File("src/main/assets/boston/boston-downtown.bin").readBytes(), "downtown") + assertEquals(9467, polygons.size) + assertEquals(73289, polygons.sumOf { b -> b.rings.sumOf { it.size / 2 } }) + assertEquals(9504, polygons.sumOf { it.rings.size }) + assertEquals(mapOf(0 to 605, 1 to 2222, 2 to 6640), polygons.groupingBy { it.level }.eachCount()) + assertEquals(362, polygons.count { it.height == null }) + assertEquals(762, polygons.count { it.name != null }) + assertEquals(9467, polygons.map { it.id }.toSet().size) + val first = polygons.first() + assertEquals(5.2, first.height!!, 0.0) + assertEquals(2, first.level) + assertArrayEquals(doubleArrayOf(-71.076105, 42.373684), first.rings[0].copyOfRange(0, 2), 1e-9) + assertArrayEquals(first.rings[0].copyOfRange(0, 2), first.rings[0].copyOfRange(16, 18), 0.0) + } + + @Test + fun `the bundled city buildings file has every building, at 1e-6 degree`() { + val bytes = File("src/main/assets/boston/boston-city-buildings.bin").readBytes() + assertEquals(6, bytes[13].toInt()) + val polygons = decodeMcpg(bytes, "buildings") + assertEquals(105599, polygons.size) + assertEquals(722875, polygons.sumOf { b -> b.rings.sumOf { it.size / 2 } }) + } + + @Test + fun `the bundled city parcels file has every parcel with a land use, at 1e-5 degree`() { + val bytes = File("src/main/assets/boston/boston-city-parcels.bin").readBytes() + assertEquals(5, bytes[13].toInt()) + val polygons = decodeMcpg(bytes, "parcels") + assertEquals(98815, polygons.size) + assertEquals(774844, polygons.sumOf { b -> b.rings.sumOf { it.size / 2 } }) + assertTrue(polygons.all { b -> b.use != null && b.rings.all { it.size >= 8 } }) + } + + @Test + fun `area is the outline less its holes`() { + val polygon = decodeMcpg(fixture, "t")[0] + val outline = Building("o", 0, null, null, listOf(polygon.rings[0])) + val hole = Building("h", 0, null, null, listOf(polygon.rings[1])) + assertEquals(areaSquareMetres(outline) - areaSquareMetres(hole), areaSquareMetres(polygon), 1e-6) + // About 82 m x 111 m. + assertEquals(9100.0, areaSquareMetres(outline), 100.0) + } +} diff --git a/example-app/src/test/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsDataTest.kt b/example-app/src/test/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsDataTest.kt new file mode 100644 index 000000000..3c2d3aa6b --- /dev/null +++ b/example-app/src/test/java/com/mapconductor/example/pages/polyline/boston/BostonRoadsDataTest.kt @@ -0,0 +1,80 @@ +package com.mapconductor.example.pages.polyline.boston + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +class BostonRoadsDataTest { + /** + * Two roads (fields name | road class | lines = 56, 1e-5 degree), written by + * the generator (the React sample's tools/boston/fixture.py). The same bytes + * are decoded by the React and iOS tests. + */ + private val fixture = + hex( + "4d4350470200000002000000380510436166c3a92053747265657420e29895010103b284850483b8e30614140a2800060102" + + "ef56973e1313", + ) + + private fun hex(text: String) = text.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + + @Test + fun `decodes the name, the class and the open path of each road`() { + val roads = decodeRoads(fixture) + assertEquals(2, roads.size) + + val first = roads[0] + assertEquals("road-0", first.id) + assertEquals("Café Street ☕", first.name) + assertEquals(RoadClass.PRIMARY, first.roadClass) + // Three points, left open: no closing point added. + assertArrayEquals( + doubleArrayOf(-71.0605, 42.35545, -71.0604, 42.35555, -71.0602, 42.3556), + first.path, + 1e-9, + ) + + val second = roads[1] + assertEquals("road-1", second.id) + assertNull(second.name) + assertEquals(RoadClass.PATH, second.roadClass) + assertArrayEquals(doubleArrayOf(-71.1, 42.3, -71.1001, 42.2999), second.path, 1e-9) + } + + @Test + fun `the bundled roads file has every road of the city`() { + val bytes = File("src/main/assets/boston/boston-city-roads.bin").readBytes() + assertEquals(5, bytes[13].toInt()) + val roads = decodeRoads(bytes) + assertEquals(54645, roads.size) + assertEquals(234765, roads.sumOf { it.path.size / 2 }) + assertEquals( + mapOf( + RoadClass.HIGHWAY to 911, + RoadClass.PRIMARY to 2320, + RoadClass.SECONDARY to 2829, + RoadClass.TERTIARY to 1229, + RoadClass.LOCAL to 11226, + RoadClass.SERVICE to 9950, + RoadClass.PATH to 26180, + ), + roads.groupingBy { it.roadClass }.eachCount(), + ) + assertEquals(18838, roads.count { it.name != null }) + assertTrue(roads.all { it.path.size >= 4 }) + val first = roads.first() + assertEquals("Saint Vincent Section", first.name) + assertEquals(RoadClass.SERVICE, first.roadClass) + assertArrayEquals(doubleArrayOf(-71.1858, 42.28788, -71.1858, 42.28794), first.path.copyOfRange(0, 4), 1e-9) + } + + @Test + fun `length is the geodesic length of the points`() { + // About 13.6 m north-east, then 17.6 m east. + val road = decodeRoads(fixture)[0] + assertEquals(31.0, lengthMetres(road), 1.5) + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 4c9e5448c..74618dcbb 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -20,24 +20,32 @@ lifecycleViewmodelCompose = "2.8.7" # https://developer.android.com/develop/ui/compose/bom/bom-mapping composeBom = "2025.02.00" -okhttp = "5.3.2" +okhttp = "5.5.1" runner = "1.7.0" -mapboxAndroid = "11.28.0" -tomtomMaps = "2.4.2" -playServicesMaps = "20.0.0" +mapboxAndroid = "11.33.0" +tomtomMaps = "2.7.2" +playServicesMaps = "20.1.0" arcgisMapsKotlin = "300.1.0" vectordrawable = "1.2.0" ktLint = "14.2.0" -mapLibreSdk = "13.4.1" +mapLibreSdk = "13.7.1" mapLibreAnnotation = "3.0.2" -maptilerSdk = "2.1.0" +maptilerSdk = "2.5.0" longdoSdk = "1.3.0" +# 9.0.4 はクラッシュする。`MapView.` → `EncryptionUtils.decryptPublicConfig` +# → `Cipher.doFinal` で `IllegalArgumentException: Null input buffer`。 +# vector-style / vector-tile のページで再現し、9.0.3 では起きない(2026-10-09 実機)。 +# android-for-mappls の submodule は 9.0.4 を指しているので、**ここだけ据え置き**。 +# 上流が直るまで上げないこと。 mapplsSdk = "9.0.3" materialVersion = "1.14.0" coroutines = "1.9.0" ui = "1.11.4" +# material3 は compose-ui とは別のバージョン系列。composeLibs(ui 系)を流用すると +# 存在しない material3:1.7.8 を要求してクラスパスごと解決に失敗する。 +material3 = "1.4.0" [libraries] # Open Mobile Maps (https://github.com/openmobilemaps/maps-core) — MPL 2.0 @@ -47,7 +55,7 @@ androidx-core = { module = "androidx.test:core", version.ref = "core" } androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } androidx-runner = { module = "androidx.test:runner", version.ref = "runner" } -androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "composeLibs" } +androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" } androidx-material-icons-core = { group = "androidx.compose.material", name = "material-icons-core" } androidx-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" } @@ -120,6 +128,7 @@ androidx-compose-runtime = { group = "androidx.compose.runtime", name = "runtime androidx-runtime = { group = "androidx.compose.runtime", name = "runtime", version.ref = "composeLibs" } material = { group = "com.google.android.material", name = "material", version.ref = "materialVersion" } kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" } +kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" } androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics", version.ref = "composeLibs" } androidx-compose-foundation = { group = "androidx.compose.foundation", name = "foundation", version.ref = "composeLibs" } androidx-compose-ui-unit = { group = "androidx.compose.ui", name = "ui-unit", version.ref = "composeLibs" } diff --git a/local.defaults.properties b/local.defaults.properties index 82b6f9c80..6b4381990 100644 --- a/local.defaults.properties +++ b/local.defaults.properties @@ -3,3 +3,6 @@ HERE_ACCESS_KEY_SECRET=HERE_ACCESS_KEY_SECRET GOOGLE_MAPS_API_KEY=GOOGLE_MAPS_API_KEY ARCGIS_API_KEY=ARCGIS_API_KEY MAPBOX_ACCESS_TOKEN=MAPBOX_ACCESS_TOKEN +TOMTOM_API_KEY=TOMTOM_API_KEY +MAPTILER_API_KEY=MAPTILER_API_KEY +LONGDO_API_KEY=LONGDO_API_KEY diff --git a/mapconductor-bom b/mapconductor-bom index 517055737..c13065b25 160000 --- a/mapconductor-bom +++ b/mapconductor-bom @@ -1 +1 @@ -Subproject commit 517055737cfe732be73bb10d2882deef3fb5ff47 +Subproject commit c13065b25831613d4d21ba444897257e9406ef90 diff --git a/projects.properties b/projects.properties index 59ce09754..b3f0c8013 100644 --- a/projects.properties +++ b/projects.properties @@ -7,6 +7,8 @@ modules=example-app,\ android-marker-clustering,\ android-heatmap,\ android-geojson-layer,\ + android-vectorstyle,\ + android-vectortile,\ mapconductor-bom,\ android-for-here,\ android-for-mapbox,\ diff --git a/simple-map-app/src/main/java/com/mapconductor/simplemapapp/MainActivity.kt b/simple-map-app/src/main/java/com/mapconductor/simplemapapp/MainActivity.kt index b546a396f..6463c6387 100644 --- a/simple-map-app/src/main/java/com/mapconductor/simplemapapp/MainActivity.kt +++ b/simple-map-app/src/main/java/com/mapconductor/simplemapapp/MainActivity.kt @@ -3,9 +3,12 @@ package com.mapconductor.simplemapapp import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Button import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -21,6 +24,7 @@ import com.mapconductor.compose.info.InfoBubble import com.mapconductor.compose.marker.Marker import com.mapconductor.core.circle.CircleState import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.marker.MarkerState import com.mapconductor.geojson.GeoJSONFeature @@ -69,13 +73,14 @@ class MainActivity : ComponentActivity() { // via onNewIntent and setIntent keeps this in step. setContent { MapConductorSDKTheme { - var picked by remember { mutableStateOf(DocDemo.bySlug(intent?.getStringExtra("demo"))) } +// var picked by remember { mutableStateOf(DocDemo.bySlug(intent?.getStringExtra("demo"))) } Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> - val inner = Modifier.padding(innerPadding) - when (val demo = picked) { - null -> DocDemoLauncher(inner) { picked = it } - else -> DocDemoScreen(demo, inner) - } + MapScreen(modifier = Modifier.padding(innerPadding)) +// val inner = Modifier.padding(innerPadding) +// when (val demo = picked) { +// null -> DocDemoLauncher(inner) { picked = it } +// else -> DocDemoScreen(demo, inner) +// } } } } @@ -88,6 +93,8 @@ class MainActivity : ComponentActivity() { } } + + val HND_AIR_PORT = GeoPoint.fromLatLong(35.548852, 139.784086) val SFO_AIR_PORT = GeoPoint.fromLatLong(37.615223, -122.389979) val HNL_AIR_PORT = GeoPoint.fromLatLong(21.324513, -157.925074) diff --git a/simple-map-app/src/main/java/com/mapconductor/simplemapapp/MapScreen.kt b/simple-map-app/src/main/java/com/mapconductor/simplemapapp/MapScreen.kt new file mode 100644 index 000000000..bc1b7917c --- /dev/null +++ b/simple-map-app/src/main/java/com/mapconductor/simplemapapp/MapScreen.kt @@ -0,0 +1,89 @@ +package com.mapconductor.simplemapapp + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Button +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.ElevatedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.maplibre.MapLibreDesign +import com.mapconductor.maplibre.MapLibreMapView +import com.mapconductor.maplibre.rememberMapLibreMapViewState + +// コントロールは自分の状態を持ちません。ボタンが押されたことを伝えるだけで、 +// それが何を意味するかを決めるのは画面の側です。 +@Composable +fun DesignPanel( + onToner: () -> Unit, + onOsmBright: () -> Unit, + onBasic: () -> Unit, +) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button(onClick = onToner) { + Text("Toner") + } + + // コンポーザブルそのものがスタイルです。FilledTonalButton、ElevatedButton、 + // OutlinedButton、TextButton が Material 3 の他の形です。 + // 地図の上では、背面に面を持つものが読みやすいままです。 + FilledTonalButton(onClick = onOsmBright) { + Text("OSM Bright") + } + + ElevatedButton(onClick = onBasic) { + Text("Basic") + } + } +} + +// 一つひとつに名前が付いたあとに残るもの — state と、それを誰が受け取るか。 + +// setContent から呼び出されているものと仮定しています(Activity がそうするように)。 +// そしてこのプレビューはシミュレーターです。実機に近いだけで、実機ではありません。 +@Composable +fun MapScreen(modifier: Modifier = Modifier) { + val mapViewState = rememberMapLibreMapViewState( + mapDesign = MapLibreDesign.OsmBrightJa, + cameraPosition = MapCameraPosition( + position = GeoPoint(latitude = 35.0, longitude = 137.0), + zoom = 6.0, + bearing = 24.0, + tilt = 45.0, + ), + ) + + Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.TopStart) { + MapLibreMapView( + state = mapViewState, + modifier = Modifier.fillMaxSize(), + ) + + DesignPanel( + // デザインは state のプロパティなので、ボタンから変えられます。 + // 新しいスタイル URL で地図が貼り直されます。 + onToner = { + mapViewState.mapDesignType = MapLibreDesign.MapTilerTonerJa + // この出力は、端末の下のコンソールに出ます。 + println("design -> ${mapViewState.mapDesignType.id}") + }, + onOsmBright = { + mapViewState.mapDesignType = MapLibreDesign.OsmBrightJa + }, + onBasic = { + mapViewState.mapDesignType = MapLibreDesign.MapTilerBasicJa + }, + ) + } +}